blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
835f358f71f3a8e6361c2c5fa0a8ed765e58386b
jakupierblina/learning-python
/tutorial/set.py
1,059
4.1875
4
x = set('abcde') y = set('bdxyz') print('e' in x) # membership print(x-y) #difference print(x | y) #union print(x & y) #intersection print(x ^ y) #symmetric difference print(x > y, x < y) #superset, subset z = x.intersection(y) #find the same elements z.add('SPAM') print(z) z.update(set(['X', 'Y'])) #update the set and add two elements print(z) z.remove('X') #delete one element print(z) print(y) for item in y: print(item * 3) ''' Why sets? Set operations have a variety of common uses, some more practical than mathematical ''' L=[1,2,3,1,1,3,4,5] set(L) L=list(set(L)) #remove duplicates print(L) #check if an elements exits in a set print(7 in L) A = "spam" B = A B = "shrubbery" print(A) A = ["spam"] B = A B[0] = "shrubbery" print(A) A = ["spam"] B = A[:] B[0] = "shrubbery" print(A) S = 'hello,world' print(S.split(',')) print(S.isdigit()) print(S.rstrip()) print(S.lower()) print(S.endswith('spam')) print(S.encode('latin-1')) for x in S: print(x) print('spam' in S) print([c * 1 for c in S]) print(map(ord, S)) print(S * 2)
true
0a4cf1075711c3b98b5d6dfd88b0065aec99c044
stephenchenxj/myLeetCode
/findDiagonalOrder.py
1,512
4.15625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. 498. Diagonal Traverse Medium Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] Explanation: Note: The total number of elements of the given matrix will not exceed 10,000. Accepted 62,044 Submissions 133,071 """ class Solution(object): def findDiagonalOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ r = len(matrix) if r == 0: return [] c = len(matrix[0]) print(r) print(c) print(matrix[r-1][c-1]) result = [] for i in range(r-1+c): print('i = %d' %i) if i%2 == 0: #go up right for j in range(i+1): if (i-j) < r and j < c: result.append(matrix[i-j][j]) else: #go down left for j in range(i+1): if(i-j) <c and j<r: result.append(matrix[j][i-j]) return result def main(): print(len([])) matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] ret = Solution().findDiagonalOrder(matrix) print(ret) if __name__ == '__main__': main()
true
f8ff8c47fe3b6f6532182ec3474a1405f8293638
stephenchenxj/myLeetCode
/reverseInteger.py
1,146
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 5 00:44:11 2019 @author: stephen.chen """ ''' Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 -1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ''' class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ sign = 1 if x < 0: sign = -1 x= -1*x result = 0 while x > 0: y = x % 10 x = int((x-y)/10) result = result*10 + y result = sign*result if result < -2**31 or result > 2**31-1: return 0 return result def main(): mySolution = Solution() print (mySolution.reverse(12030)) if __name__ == "__main__": main()
true
da0019078824aa244442fbf23e20fb33814c05af
stephenchenxj/myLeetCode
/shuffle.py
1,386
4.15625
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 11 20:26:42 2019 @author: stephen.chen Shuffle an Array Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Resets the array back to its original configuration [1,2,3]. solution.reset(); // Returns the random shuffling of array [1,2,3]. solution.shuffle(); """ import copy import random class Solution(object): def __init__(self, nums): self.array = nums self.original = list(nums) def reset(self): self.array = self.original self.original = list(self.original) return self.array def shuffle(self): aux = list(self.array) for idx in range(len(self.array)): remove_idx = random.randrange(len(aux)) self.array[idx] = aux.pop(remove_idx) return self.array print (random.randrange(2)) l = [1,2,3,4] print(l.pop(2)) print(l) mySolution = Solution([1,2,3,4]) print(mySolution.shuffle()) print(mySolution.reset()) print(mySolution.shuffle()) # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
true
b0ba8f4f5411931d0d106a1e4ff75c15deb4a32c
christian-alexis/edd_1310_2021
/colas.py
2,818
4.15625
4
#PRUEBAS DE LAS COLAS class Queue: def __init__(self): self.__data = list() def is_empty (self): return len(self.__data)==0 def length(self): return len(self.__data) def enqueue(self,elem): self.__data.append(elem) def dequeue (self): if not self.is_empty(): return self.__data.pop(0) else: return None def to_string (self): cadena = "" for elem in self.__data: cadena = cadena + "|" + str(elem) cadena = cadena +"|" return cadena #PRUEBAS DE LAS COLAS CON PRIORIDAD NO ACOTADA class PriorityQueue: """ This priority queue uses a given number as priority order. The smallest number has the higher priority """ def __init__(self): self.__data = list() def is_empty (self): return len(self.__data)==0 def length(self): return len(self.__data) def enqueue(self, value: str, priority: int) -> None: """Add the value the queue based on its priority""" self.__data.append((value, priority)) self.__data = reorder_queue(self.__data) def dequeue (self): if not self.is_empty(): return self.__data.pop(0) else: return None def to_string (self): cadena = "" for elem in self.__data: cadena = cadena + "|" + str(elem) cadena = cadena +"|" return cadena def reorder_queue(queue): return sorted(queue, key=lambda v: v[1]) #PRUEBAS DE LAS COLAS CON PRIORIDAD ACOTADA class BoundedPriorityQueue: def __init__( self , niveles): self.__data=[Queue() for x in range(niveles) ] self.__size=0 def is_empty(self): return self.__size == 0 def length(self): return self.__size def enqueue(self,prioridad,elem): if prioridad < len(self.__data) and prioridad >= 0: self.__data[prioridad].enqueue(elem) self.__size +=1 def dequeue (self): if not self.is_empty(): for nivel in self.__data: if not nivel.is_empty(): self.__size -=1 return nivel.dequeue() def to_string (self): if not self.is_empty(): for nivel in range (len(self.__data)): print(f"Nivel {nivel}-->{ self.__data[nivel].to_string()}") print("-------------------------------------------------------") else: print("\n************** EL BARCO FUE ABANDONADO **************\n")
true
0ffe4afc95e64efe667b76c42dbae97687b2160d
mendozatori/python_beginner_proj
/rainfall_report/rainfall_report.py
1,305
4.3125
4
# Average Rainfall Application # CONSTANTS NUM_MONTHS = 12 # initialize total_inches = 0.0 # input years = int(input("How many years are we calculating for? ")) while years < 0: print("Please enter a valid number of years!") years = int(input("How many years are we calculating for? ")) # x will continue to increment by 1 until it reaches number of years inputted for x in range(years): print('') print('---------------------') print("RAINFALL FOR YEAR " + str(x + 1)) print('---------------------') print('') # y will continue to increment by 1 until it reaches 12 "months" for y in range(NUM_MONTHS): month_rain = float(input("Inches of rainfall for month " + str(y + 1) + ": ")) while month_rain < 0: print("Please enter a valid number of inches of rainfall!") month_rain = float(input("Inches of rainfall for month " + str(y + 1) + ": ")) total_inches = total_inches + month_rain # calculations total_months = NUM_MONTHS * years average_rainfall = total_inches / total_months print('') print("-------SUMMARY--------") print("Number of months: ", total_months) print("Total inches of rainfall: ", total_inches) print("Average rainfall per month: ", average_rainfall)
true
3b811ee60b5aee105510e413af107661e2127836
tenzin1308/PythonBasic
/Class/TypesOfMethods.py
711
4.125
4
""" We have 3 types of Methods: a) Instances/Object Methods b) Class Methods c) Static Methods """ class Student: # Class/Static Variable school = "ABC School" def __init__(self, m1, m2, m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 # Instances/Object Methods def avg(self): return (self.m1 + self.m2 + self.m3) / 3 # Class Methods @classmethod ## Decorator def getSchool(cls): print(cls.school) # Static Methods @staticmethod def info(): print("This is Static Method") s1 = Student(67, 87, 76) s2 = Student(98, 67, 78) print(s1.avg()) print(s2.avg()) Student.getSchool() Student.info()
true
23f386c4f97055645a6724a76dc49f3b7a93c93b
pc2459/learnpy
/csv_parse.py
2,455
4.15625
4
""" Write a script that will take three required command line arguments - input_file, output_file, and the row_limit. From those arguments, split the input CSV into multiple files based on the row_limit argument. Arguments: 1. -i: input file name 2. -o: output file name 3. -r: row limit to split Default settings: 1. output_path is the current directory 2. headers are displayed on each split file 3. the default delimiter is a comma """ from __future__ import division import argparse import csv import os import math import sys # create a parser to handle command-line arguments parser = argparse.ArgumentParser() #store input file name parser.add_argument('-i', action='store') #store output file name parser.add_argument('-o', action='store') #store number of rows parser.add_argument('-r', action='store') args = parser.parse_args() total_rows = 0 # check to see if rows is an integer try: rows = int(args.r) except ValueError: # error handle and quit if does not eixst print "You didn't input an integer" sys.exit(0) # check to see if input exists try: with open(args.i) as file: pass except IOError: # error handle and quit if does not exist print "Your input file does not exist" sys.exit(0) # count total number of rows with open(args.i) as input: total_rows = sum(1 for row in input)-1 if total_rows <= rows: print "The split number is more than or equal to the size of the CSV to split" sys.exit(0) ########################## #find out the number of CSVs needed segments = math.ceil(total_rows/rows) #open the input and begin to read input = open(args.i, "r") reader = csv.reader(input) # Store the header header = reader.next() # Create an list to store header + N rows templist = [] current = 1 rownum = 0 while current <= segments: # Add rows to the templist for i in range(rows): try: line = reader.next() templist.append(line) rownum += 1 except StopIteration: pass # Write the templist to an output with open(args.o+str(current)+".csv", "wb") as output: writer = csv.writer(output) # Write in the header writer.writerow(header) # Write in the remainder of the lines for line in templist: writer.writerow(line) # Print out message to the user print "Chunk written to {} with {} lines".format(args.o+str(current)+".csv",rownum) # Reset the templist, row counters templist = [] rownum = 0 # Move on to the next output file current += 1 input.close()
true
2791583af83b9ff15ac5fe9d30acd2313e6cfd2a
kirteekishorpatil/dictionary
/studant_data_8.py
375
4.34375
4
# i=0 # dict1={} # if i<3: # num=input("enter the student name") # num2=int(input("enter the students marks")) # i=i+1 # new_type={num:num2} # dict1.update(new_type) # print(dict1) num=input("enter the student name") num2=int(input("enter the students marks")) # i=0 dict1={} # while i<8: new_type={num:num2} dict1.update(new_type) # i=i+1 print(dict1)
true
2bbf90d8645ba21f97c0e4fc635cd50be9bffe2c
milnorms/pearson_revel
/ch7/ch7p5.py
841
4.15625
4
''' (Sorted?) Write the following function that returns True if the list is already sorted in increasing order: def isSorted(lst): Write a test program that prompts the user to enter a list of numbers separated by a space in one line and displays whether the list is sorted or not. Here is a sample run: Sample Run 1 Enter list: 1 1 3 4 4 5 7 9 10 30 11 The list is not sorted Sample Run 2 Enter list: 1 1 3 4 4 5 7 9 10 30 The list is already sorted ''' def main(): nums = getInt(input("Enter list: ")) print("The list is already sorted" if isSorted(nums) else "The list is not sorted") def getInt(string): score = string.split(" ") for i in range(len(score)): score[i] = int(score[i]) return score def isSorted(lst): s = sorted(lst) if s == lst: return True return False main()
true
97d6ffbe6671998c18f37757459a61aea61de6f0
milnorms/pearson_revel
/ch8/ch8p4.py
1,626
4.46875
4
''' (Markov matrix) An n by n matrix is called a positive Markov matrix if each element is positive and the sum of the elements in each column is 1. Write the following function to check whether a matrix is a Markov matrix: def isMarkovMatrix(m): Write a test program that prompts the user to enter a 3 by 3 matrix of numbers and tests whether it is a Markov matrix. Note that the matrix is entered by rows and the numbers in each row are separated by a space in one line. Sample Run 1 Enter a 3-by-3 matrix row by row: 0.15 0.875 0.375 0.55 0.005 0.225 0.30 0.12 0.4 It is a Markov matrix Sample Run 2 Enter a 3-by-3 matrix row by row: 0.95 -0.875 0.375 0.65 0.005 0.225 0.30 0.22 -0.4 It is not a Markov matrix ''' def main(): m = [] print("Enter a 3-by-3 matrix row by row:") for i in range(3): s = input("") s = [float(x) for x in s.split()] m.append(s) s = "" print("It is a Markov matrix" if isMarkovMatrix(m) else "It is not a Markov matrix") def isMarkovMatrix(m): total = 0 isMark = False for i in range(3): total += m[i][0] if total == 1: isMark = True total = 0 if isMark: for i in range(3): total += m[i][1] if total == 1: isMark == True total = 0 else: isMark == False if isMark: for i in range(3): total += m[i][2] if total == 1: isMark == True total = 0 else: isMark == False return isMark main()
true
d5ae42360d6c5b28032c26f94bf5570608378ae7
milnorms/pearson_revel
/ch4/ch4p2.py
888
4.3125
4
''' (Convert letter grade to number) Write a program that prompts the user to enter a letter grade A/a, B/b, C/c, D/d, or F/f and displays its corresponding numeric value 4, 3, 2, 1, or 0. Sample Run 1 Enter a letter grade: B The numeric value for grade B is 3 Sample Run 2 Enter a letter grade: b The numeric value for grade b is 3 Sample Run 3 Enter a letter grade: T T is an invalid grade ''' input = input("Enter a letter grade: ") grade = input.lower() if grade == 'a': print("The numeric value for grade", input, "is 4") elif grade == 'b': print("The numeric value for grade", input, "is 3") elif grade == 'c': print("The numeric value for grade", input, "is 2") elif grade == 'd': print("The numeric value for grade", input, "is 1") elif grade == 'f': print("The numeric value for grade", input, "is 0") else: print(input, "is an invalid grade")
true
c54e78731fa62bc05f222e87bb91d0961b89766a
milnorms/pearson_revel
/ch2/ch2p5.py
1,009
4.21875
4
''' (Financial application: calculate future investment value) Write a program that reads in an investment amount, the annual interest rate, and the number of years, and then displays the future investment value using the following formula: futureInvestmentAmount = investmentAmount * (1 + monthlyInterestRate) ^ numberOfMonths For example, if you enter the amount 1000.56, an annual interest rate of 4.25%, and the number of years as 1, the future investment value is 1043.33. Here is a sample run: Enter investment amount: 1000.56 Enter annual interest rate: 4.25 Enter number of years: 1 Accumulated value is 1043.92 ''' investmentAmount = float(input("Enter investment amount: ")) interestRate = float(input("Enter annual interest rate: ")) years = float(input("Enter number of years: ")) monthlyInterestRate = (interestRate * 0.01) / 12 numberOfMonths = years * 12 futureInvestmentAmount = investmentAmount * ((1 + monthlyInterestRate) ** numberOfMonths) print(round(futureInvestmentAmount, 2))
true
94e1e2f107723e9ea3d4ea648cbd16487b69af16
pectoraux/python_programs
/question5.py
2,323
4.125
4
''' Efficiency: ---------------------------------------------- member function get_length() of class Linked_List runs in O(1) member function get_at_position() of class Linked_List runs in O(n) make_ll() runs in O(n) So question5() runs in O(n) ''' class Node(object): def __init__(self, data): self.data = data self.next = None def __str__(self): return str(self.data) class Linked_List(object): """ Linked list class with necessary functions for the problem implemented: a printer for debugging a .get_at_position() method to get an element at a position a .get_length() method to get the element that is m position away faster by doing: ll.get_at_position(ll.get_length - m) and a .append() method to populate the linked list """ def __init__(self, head=None): self.head = head if head: self.length = 1 else: self.length = 0 def printer(self): current = self.head while current: print current current = current.next def get_length(self): return self.length def get_at_position(self, position): counter = 1 current = self.head if position < 0 : return None while current and counter <= position: if counter == position: return current current = current.next counter += 1 return None def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element self.length += 1 def question5(ll, m): """ Takes in a linked list and a position m Returns the element that is m element from the end """ ll_len = ll.get_length() return ll.get_at_position(ll_len-m) def make_ll(arr): """Takes in an array and turns it into a linked list Useful for testing purposes """ my_ll = Linked_List() for i in range(len(arr)): my_ll.append(Node(arr[i])) #my_ll.printer() # prints the final linked list; useful for debugging return my_ll def run(): # Test 1 print question5(make_ll(['elephant', 'shoes', 'basket']), 0) # Should return basket # Test 2 print question5(make_ll(range(10)), 4) # Should return 5 # Test 3 print question5(make_ll([None, 'forward', '', '-', 'right']), 1) # Should return - if __name__ == '__main__': run()
true
41ad1238055f8657136aebbfdddd50e81ac0e66b
ebrahim-j/FindMissingLab
/MissingNumber.py
662
4.125
4
def find_missing(list1, list2): inputList = [] #list with extra number checkList = [] #template list if len(list1) > len(list2): #determines the variable (input and check)lists will be assigned to inputList = list1 checkList = list2 else: inputList = list2 checkList = list1 missing_num = [] #missing number to be stored in array for i in inputList: if i not in checkList: #if current number not in template list, that is added to missing list array missing_num.append(i) if len(missing_num) == 0: #if no outstanding number/value found return 0 return missing_num.pop()
true
4cd52636027021227a8195e5a0a8ed31cb7753b3
7Aishwarya/HakerRank-Solutions
/30_Days_of_Code/day5_loops.py
343
4.125
4
'''Given an integer, n, print its first 10 multiples. Each multiple n x i (where 1<=i<=10) should be printed on a new line in the form: n x i = result.''' #!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': n = int(input()) for i in range(10): print(n,"x",i+1,"=",n*(i+1))
true
8bb2e6edbb2d703ad41e899b57cb32b228676557
7Aishwarya/HakerRank-Solutions
/Algorithms/beautiful_days_at_the_movies.py
1,685
4.46875
4
'''Lily likes to play games with integers. She has created a new game where she determines the difference between a number and its reverse. For instance, given the number 12, its reverse is 21. Their difference is 9. The number 120 reversed is 21, and their difference is 99. She decides to apply her game to decision making. She will look at a numbered range of days and will only go to a movie on a beautiful day. Given a range of numbered days, [i...j] and a number k, determine the number of days in the range that are beautiful. Beautiful numbers are defined as numbers where |i-reverse(i)| is evenly divisible by k. If a day's value is a beautiful number, it is a beautiful day. Print the number of beautiful days in the range. Function Description Complete the beautifulDays function in the editor below. It must return the number of beautiful days in the range. beautifulDays has the following parameter(s): i: the starting day number j: the ending day number k: the divisor ''' #!/bin/python3 import math import os import random import re import sys # Complete the beautifulDays function below. def beautifulDays(i, j, k): count = 0 for x in range(i,j+1,1): reverse = 0 temp = x while(x > 0): reminder = x % 10. reverse = (reverse * 10) + reminder x = x // 10 if((abs(temp - reverse))%k == 0): count+=1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') ijk = input().split() i = int(ijk[0]) j = int(ijk[1]) k = int(ijk[2]) result = beautifulDays(i, j, k) fptr.write(str(result) + '\n') fptr.close()
true
6ce7779a588924aab0caea37a70bbe7be5d93ff2
7Aishwarya/HakerRank-Solutions
/30_Days_of_Code/day25_running_time_and_complexity.py
745
4.15625
4
'''Given a number, n find if it is prime or not. Input Format The first line contains an integer, T, the number of test cases. Each of the T subsequent lines contains an integer, n, to be tested for primality. Constraints 1<=T<=30 1<=n<=2*10^9 Output Format For each test case, print whether n is Prime or Not Prime on a new line.''' # Enter your code here. Read input from STDIN. Print output to STDOUT import math n = int(input()) for i in range(n): num = int(input()) sqrt = int(math.sqrt(num)) if num > 1: for i in range(2,sqrt+1): if (num % i) == 0: print("Not prime") break else: print("Prime") else: print("Not prime")
true
abb691603f4655d3c1a116d94b76f83655d182c3
Jinx-Heniux/Python-2
/maths/odd_check.py
980
4.4375
4
def is_odd(number: int) -> bool: """ Test if a number is a odd number. :param number: the number to be checked. :return: True if the number is odd, otherwise False. >>> is_odd(-1) True >>> is_odd(-2) False >>> is_odd(0) False >>> is_odd(3) True >>> is_odd(4) False >>> all([is_odd(i) for i in range(1, 100, 2)]) True """ return number % 2 != 0 def is_odd_faster(number: int) -> bool: """ Test if a number is a odd number using bit operator. :param number: the number to be checked. :return: True if the number is odd, otherwise False. >>> is_odd_faster(-1) True >>> is_odd_faster(-2) False >>> is_odd_faster(0) False >>> is_odd_faster(3) True >>> is_odd_faster(4) False >>> all([is_odd_faster(i) for i in range(1, 100, 2)]) True """ return number & 1 != 0 if __name__ == "__main__": from doctest import testmod testmod()
true
8bd8af36d1693829ebbf3e958a11b8a15fe44e0c
Jinx-Heniux/Python-2
/sorts/quick_sort.py
1,336
4.125
4
""" https://en.wikipedia.org/wiki/Quicksort """ def quick_sort(array, left: int = 0, right: int = None): """ Quick sort algorithm. :param array: the array to be sorted. :param left: the left index of sub array. :param right: the right index of sub array. :return: sorted array >>> import random >>> array = random.sample(range(-50, 50), 10) >>> quick_sort(array) == sorted(array) True >>> import string >>> array = random.choices(string.ascii_letters + string.digits, k = 10) >>> quick_sort(array) == sorted(array) True >>> array = [random.uniform(-50.0, 50.0) for i in range(10)] >>> quick_sort(array) == sorted(array) True """ if right is None: right = len(array) - 1 if left >= right: return pivot = array[right] # pick last element as pivot i = left j = right - 1 while i <= j: while array[i] < pivot: i += 1 while j >= 0 and array[j] >= pivot: j -= 1 if i < j: array[i], array[j] = array[j], array[i] i += 1 j -= 1 array[i], array[right] = array[right], array[i] quick_sort(array, left, i - 1) quick_sort(array, i + 1, right) return array if __name__ == "__main__": from doctest import testmod testmod()
true
82c56958204986ce03caf2d8e913b06ccf433ac5
Jinx-Heniux/Python-2
/searches/binary_search_recursion.py
871
4.15625
4
""" https://en.wikipedia.org/wiki/Binary_search_algorithm """ def binary_search(array, key) -> int: """ Binary search algorithm. :param array: the sorted array to be searched. :param key: the key value to be searched. :return: index of key value if found, otherwise -1. >>> array = list(range(10)) >>> for index, item in enumerate(array): ... assert index == binary_search(array, item) >>> binary_search(array, 10) == -1 True >>> binary_search(array, -1) == -1 True """ left = 0 right = len(array) - 1 while left <= right: mid = (left + right) >> 1 if key == array[mid]: return mid elif key > array[mid]: left = mid + 1 else: right = mid - 1 return -1 if __name__ == "__main__": from doctest import testmod testmod()
true
93f1ec4e576c4d805a26e8e0a8b9adef0e021aca
rockchar/CODE_PYTHON
/Sets.py
598
4.28125
4
# sets are unordered collections of unique objects. They contain only one # unique object # Lets create a set my_set = set() my_set.add(1) my_set.add(2) my_set.add(3) print(my_set) # lets try to add a duplicate element to the set my_set.add(3) print(my_set) #lets declare a list with duplicate objects my_list = [1,2,2,3,3,4,4,4,4,4,5] print(my_list) #now lets convert it to a set my_set_frm_list = set(my_list) print(my_set_frm_list) #in the above example we can see that the duplicate objects were eliminated # the following will fail as sets are unordered print(my_set_frm_list[4])
true
6bcdb23587171691e25cd375ea30f5356487dcc9
vensder/codeacademy_python
/shout.py
289
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def shout(phrase): if phrase == phrase.upper(): return "YOU'RE SHOUTING!" print phrase else: return "Can you speak up?" print "Hello!" phrase = raw_input("Enter yours phrase:\n") print shout(phrase)
true
2bb4c43c58c24f07a6b0a2e30ae5e3a1593e1ef6
sipakhti/code-with-mosh-python
/Data Structure/Dictionaries.py
1,002
4.25
4
point = {"x": 1, "y": 2} point = dict(x=1, y=2) point["x"] = 10 # index are names of key point["z"] = 20 print(point) # to make sure the program doesnt crash due to invalid dict key if "a" in point: print(point["a"]) # Alternative approach using .get function and it makes the code cleaner print(point.get("a", 0)) # for deleting an item del point["x"] print(point) # itereating over a dictionary. When looping only the key is returned for key in point: print(key, point[key]) # .item funtion returns a tuple of (key, value) pair which can be unpacked like any other tuple for key, value in point.items(): print(key, value) # this comprehensioin can also be used with sets and dictionaries values = [x * 2 for x in range(5)] # Comprehnsion method for sets sets = {x * 2 for x in range(5)} print(sets) # Comprehension metthod for dictionary dicts = {x: x*2 for x in range(5)} print(dicts) # Topic for next lecture -- Genearator object tupes = (x * 2 for x in range(5)) print(tupes)
true
b5fc18297b318ff88610adf0cb3d3448de671d31
sipakhti/code-with-mosh-python
/Data Structure/Unpacking Operator.py
440
4.21875
4
numbers = [1, 2, 3] print(*numbers) print(1, 2, 3) values = list(range(5)) print(values) print(*range(5), *"Hello") values = [*range(5), * "Hello"] first = [1, 2] second = [3] values = [*first, *second] print(*values) first = dict(x=1) second = dict(x=10, y=2) # incase of multiple values with similar keys, the last value will be used as in this case the value from the second dict combined = {**first, **second, "Z":1} print(combined)
true
307eccd04d95e8e169f1b1cf743b10fb42686268
sipakhti/code-with-mosh-python
/Control Flow/Ternary_Operator.py
240
4.15625
4
age = 22 if (age >= 18): message = "Eligible" else: message = "Not Eligible" print(message) # more clearner way to do the same thing age = 17 message = "Eligible" if age >= 18 else "Not Eligible" # ternary Operator print(message)
true
64fef01dcc207fc7e1d965d319f03433672f2429
EarthCodeOrg/earthcode-curriculum
/modules/recursive_to_iterative.py
544
4.15625
4
# Recursive to Iterative # Approach 1: Simulate the stack def factorial(n): if n < 2: return 1 return n * factorial(n - 1) def factorial_iter(n): original_n = n results = {} inputs_to_resolve = [n] while inputs_to_resolve: n = inputs_to_resolve.pop() if n < 2: results[n] = 1 else: # we want n-1 if n-1 not in results: else: inputs_to_resolve.append(n) inputs_to_resolve.append(n-1) else: results[n] = n*results[n-1] # Approach 2: Tail End Recursion
true
f2a9b7ec51fa931682743a4957d34a9a80441679
ModellingWebLab/chaste-codegen
/chaste_codegen/_script_utils.py
676
4.15625
4
import os def write_file(file_name, file_contents): """ Write a file into the given file name :param file_name: file name including path :param file_contents: a str with the contents of the file to be written """ assert isinstance(file_name, str) and len(file_name) > 0, "Expecting a file path as string" assert isinstance(file_contents, str), "Contents should be a string" # Make sure the folder we are writing in exists path = os.path.dirname(file_name) if path != '': os.makedirs(path, exist_ok=True) # Write the file file = open(file_name, 'w') file.write(file_contents) file.close()
true
d0bf5cbec6cc10cecfd3a5e556851908df86110e
pliz/PDF-guard
/pdf-encryptor.py
651
4.15625
4
from PyPDF2 import PdfFileWriter, PdfFileReader pdfWriter = PdfFileWriter() # Read the pdf file which will be encrypted pdf = PdfFileReader("example.pdf") for page_num in range(pdf.numPages): pdfWriter.addPage(pdf.getPage(page_num)) # Encryption process goes here passw = input('Enter your password: ') pdfWriter.encrypt(passw) print('Password was set successfully !') setNewName = input('What will you name your encrypted pdf? (without ".pdf") : ') newPdfName = str(setNewName) + '.pdf' # Create a new encrypted PDF with open(newPdfName, 'wb') as f: pdfWriter.write(f) f.close() print('Excellent! You have secured your PDF file!')
true
2a185cc736922ae8baff835e5d0b9b3727dc7fc3
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q139_word_break.py
1,980
4.28125
4
import re from typing import List def wordBreak(s: str, wordDict: List[str]) -> bool: """ Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Input: s = "leetcode", wordDict = ["leet","code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code". Example 2: Input: s = "applepenapple", wordDict = ["apple","pen"] Output: true Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word. Example 3: Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: false Constraints: • 1 <= s.length <= 300 • 1 <= wordDict.length <= 1000 • 1 <= wordDict[i].length <= 20 • s and wordDict[i] consist of only lowercase English letters. • All the strings of wordDict are unique. """ assert 1 <= len(s) <= 300, "Length of s must be between 1 and 300" assert 1 <= len(wordDict) <= 1000, "Length of wordDict must be between 1 and 1000" assert re.search("[a-z]", s), "s must consist of only lowercase English letters" for word in wordDict: assert 1 <= len(word) <= 20, "Length of word in wordDict must be between 1 and 20" assert re.search("[a-z]", word), "word in wordDict must consist of only lowercase English letters" assert len(wordDict) == len(set(wordDict)), "All the strings in wordDict must be unique" dp = [False for _ in range(len(s) + 1)] dp[-1] = True for i in reversed(range(len(s))): for word in wordDict: if i + len(word) <= len(s) and s[i:i+len(word)] == word: dp[i] = dp[i+len(word)] if dp[i]: break return dp[0]
true
0c822fefe2815bf1f401a6ae0e5ca175fd252ee8
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q46_permutations.py
1,137
4.125
4
from typing import List def permute(nums: List[int]) -> List[List[int]]: """ Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: Input: nums = [0,1] Output: [[0,1],[1,0]] Example 3: Input: nums = [1] Output: [[1]] Constraints: • 1 <= nums.length <= 6 • -10 <= nums[i] <= 10 • All the integers of nums are unique. """ assert 1 <= len(nums) <= 6 for num in nums: assert -10 <= num <= 10 assert len(nums) == len(set(nums)) resultList = [] visited = set() def backtrack(visitedSet, permutation): if len(permutation) == len(nums): resultList.append(permutation.copy()) for i in range(len(nums)): if i not in visited: visitedSet.add(i) backtrack(visitedSet, permutation + [nums[i]]) visitedSet.remove(i) backtrack(visited, []) return resultList
true
6b91e70df04c6feb54be4da4c340b151951f0a4e
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q169_majority_element.py
1,126
4.28125
4
from typing import List def majorityElement(nums: List[int]) -> int: """ Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Example 1: Input: nums = [3,2,3] Output: 3 Example 2: Input: nums = [2,2,1,1,1,2,2] Output: 2 Constraints: • n == nums.length • 1 <= n <= 5 * 10 ** 4 • -10 ** 9 <= nums[i] <= 10 ** 9 """ assert 1 <= len(nums) <= 5 * 10 ** 4 for num in nums: assert -10 ** 9 <= num <= 10 ** 9 ## Moore Voting Algorithm # count = 0 # candidate = 0 # for num in nums: # if count == 0: # candidate = num # if num == candidate: # count += 1 # else: # count -= 1 # return candidate numDict = {} for num in nums: if num not in numDict: numDict[num] = 0 numDict[num] += 1 if numDict[num] > len(nums) // 2: return num
true
cd2d86cd6a9e91412e5e4eaac9d33716291177e2
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/CSES_Problem_Set/Q2_missing_number.py
1,248
4.125
4
""" You are given all numbers between 1,2,…,n except one. Your task is to find the missing number. Input The first input line contains an integer n. The second line contains n−1 numbers. Each number is distinct and between 1 and n (inclusive). Output Print the missing number. Constraints 2 ≤ n ≤ 2*10^5 Example Input: 5 2 3 1 5 Output: 4 """ import argparse import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger() def missing_number(args): assert 2 <= args.number <= 2 * 10**5, "Please input another integer within the range [2, 200000]" assert len(args.number_array) == args.number-1, "There are more than 1 missing number in the array" target_sum = int(args.number * (args.number+1) / 2) current_sum = sum(args.number_array) missing_num = target_sum - current_sum logger.info(f"Missing number in the given array is {missing_num}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Tools to find missing number") parser.add_argument('-n', dest="number", type=int, help="Integer n", required=True) parser.add_argument('-array', type=int, dest="number_array", nargs='+') args = parser.parse_args() missing_number(args)
true
856d259f74a1016e5cc43bfe2bc9bb714108ed2c
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q20_valid_parenthesis.py
1,243
4.28125
4
def isValid(s: str) -> bool: """ Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false Example 4: Input: s = "([)]" Output: false Example 5: Input: s = "{[]}" Output: true Constraints: • 1 <= s.length <= 10 ** 4 • s consists of parentheses only '()[]{}'. """ assert 1 <= len(s) <= 10 ** 4, "Length of string must be between 1 and 10 ** 4" for character in s: assert character in ['(', ')', '[', ']', '{', '}'] track_left_bracket = [] bracket_dict = {'(': ')', '[': ']', '{': '}'} for bracket in s: if bracket in bracket_dict.keys(): track_left_bracket.append(bracket) elif len(track_left_bracket) == 0 or bracket_dict[track_left_bracket.pop()] != bracket: return False return True if len(track_left_bracket) == 0 else False
true
6ad68ea092a6435db680bd485a1279b2de19292d
MLgeek96/Interview-Preparation-Kit
/Python_Interview_Questions/leetcode/problem_sets/Q11_container_with_most_water.py
1,501
4.25
4
from typing import List def container_with_most_water(height: List[int]) -> int : """" Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. Notice that you may not slant the container. Example 1: Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. Example 2: Input: height = [1,1] Output: 1 Example 3: Input: height = [4,3,2,1,4] Output: 16 Example 4: Input: height = [1,2,1] Output: 2 Constraints: • n == height.length • 2 <= n <= 3 * 104 • 0 <= height[i] <= 3 * 10 ** 4 """ assert 2 <= len(height) <= 3 * 104, "Length of height is strictly between 2 and 3 * 104" for i in range(len(height)): assert 0 <= height[i] <= 3 * 104, "Length of height is strictly between 2 and 3 * 104" max_volume = 0 n = len(height) i = 0 j = n - 1 while i < j: max_volume = max(max_volume, min(height[i], height[j]) * (j - i)) if height[i] < height[j]: i += 1 else: j -= 1 return max_volume
true
2be28d3c7f1d27878116b489ddf78409f4fe1a2c
bheinks/2018-sp-a-puzzle_4-bhbn8
/priorityqueue.py
1,194
4.21875
4
class PriorityQueue: """Represents a custom priority queue instance. While Python has a PriorityQueue library available, this is more efficient because it sorts on dequeue, rather than enqueue.""" def __init__(self, key, items=[]): """Initializes a PriorityQueue instance. Args: key: The function that will act as the sort key of our queue. items: Any initial queue items. """ self.key = key self.items = items def enqueue(self, item): """Add an item to the queue. Args: item: The item that's being added. """ self.items.append(item) def dequeue(self): """Sort using our key function and pop an item from the queue. Returns: The item at the top of the queue, post-sorting. """ # reverse the sort as pop takes the last item from the queue self.items.sort(key=self.key, reverse=True) return self.items.pop() def __len__(self): """Overload __len__ to return length of queue. Returns: The number of items in our queue. """ return len(self.items)
true
ec9ab3c13b26dfbfbf5edf2225ae6870f59a7e80
lucguittard/DS-Unit-3-Sprint-2-SQL-and-Databases
/module2-sql-for-analysis/practice.py
946
4.21875
4
# Working with sqlite # insert a table # import the needed modules import sqlite3 import pandas as pd # connect to a database connection = sqlite3.connect("myTable.db") # make a cursor curs = connection.cursor() # SQL command to create a table in the database sql_command = """CREATE TABLE emp (staff_number INTEGER PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(30), gender CHAR(1), joining DATE);""" # execute the statement curs.execute(sql_command) # SQL command to insert the data in the table sql_command = """INSERT INTO emp VALUE (23, "Joe", "Walker", "M", "2015-04-11");""" curs.execute(sql_command) # another data insertion command sql_command = """INSERT INTO emp VALUE (40, "Kam", "Greene", "F", "2004-07-23");""" curs.execute(sql_command) # save the changes made to the database file connection.commit() # close the connection connection.close() # may now run SQL queries on the populated database (continue to part 2)
true
23b32a35acc060b021706f17754c0e1479259025
saranaweera/dsp
/python/q8_parsing.py
701
4.3125
4
# The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. import pandas as pd data = pd.read_csv('football.csv') data['AbsGoalDiff'] = (abs(data['Goals'] - data['Goals Allowed'])) print('Team with the smallest difference in for and against goals: {}'.format( data.loc[data['AbsGoalDiff'].idxmin(),'Team'] ))
true
656a32a3781605c1f68539cfcdc3e8de98bf4181
sivaneshl/real_python
/implementin_linked_list/implementing_a_own_linked_list.py
1,765
4.46875
4
from linked_list import LinkedList, Node # using the above class create a linked list llist = LinkedList() print(llist) # add the first node first_node = Node('a') llist.head = first_node print(llist) # add subsequent nodes second_node = Node('b') third_node = Node('c') first_node.next = second_node second_node.next = third_node print(llist) # create the linked list by passing in the nodes list llist = LinkedList(list('abcde')) print(llist) # traversing through the linked list for e in llist: print(e) # inserting an element to the first of the linked list llist.add_first(Node('x')) llist.add_first(Node('y')) print(llist) # inserting an element to the last of the linked list llist.add_last(Node('f')) llist.add_last(Node('g')) print(llist) # inserting a node in between # adding to an empty linked list llist = LinkedList() # llist.add_after('a', Node('b')) # exception print(llist) # adding an element after a target node llist = LinkedList(list('abcde')) llist.add_after('c', Node('cc')) print(llist) # attempt to add after a non-existent target node # llist.add_after('f', Node('g')) # exception print(llist) # inserting a node before a target node llist.add_before('c', Node('bb')) print(llist) llist.add_before('a', Node('zz')) print(llist) # removing a node llist.remove_node('zz') print(llist) llist.remove_node('cc') llist.remove_node('bb') print(llist) # get the node at position i print(llist.get(3)) # print(llist.get(7)) # exception # get the node at position i using subscript print(llist[3]) # print(llist[7]) # exception # get the reversed linked list print(llist.reverse()) # get the length of the linked list print(len(llist)) print(llist.__len__())
true
37898e1d98f7a08c52d2dc6fc80779c54ba60685
nnamon/ctf101-systems-2016
/lessonfiles/offensivepython/11-stringencodings.py
864
4.125
4
#!/usr/bin/python def main(): sample_number = 65 # We can get binary representations for a number print bin(sample_number) # Results in 0b1000001 # We can also get hex representations for a number: print hex(sample_number) # Results in 0x41 # Also, octal: print oct(sample_number) # Results in 0101 sample_text = "ABCD" # Often, we want to convert a string into hex for reason that will be more # apparent as you progress further up in CTFs print sample_text.encode("hex") # Results in 41424344 # Conversely, we can also decode from a hex string print "41424344".decode("hex") # Results in ABCD # There are other useful codecs as well: print "SGVsbG8=".decode("base64") # Results in Hello print "Obawbhe".decode("rot13") # Results in Bonjour if __name__ == "__main__": main()
true
d57e662d520f5ff40408d2d410584cb32942d4aa
elrapha/Lab_Python_01
/zellers.py
1,672
4.75
5
""" Zeller’s algorithm computes the day of the week on which a given date will fall (or fell). In this exercise, you will write a program to run Zeller’s algorithm on a specific date. You will need to create a new file for this program, zellers.py. The program should use the algorithm outlined below to compute the day of the week on which the user’s birthday fell in the year you were born and print the result to the screen. Let A, B, C, D denote integer variables that have the following values: A = the month of the year, with March having the value 1, April the value 2, ... December the value 10, and January and February being counted as months 11 and 12 of the preceding year (in which case, subtract 1 from C) B = the day of the month (1, 2, 3, ... , 30, 31) C = the year of the century (e.g. C = 89 for the year 1989) D = the century (e.g. D = 19 for the year 1989) Note: if the month is January or February, then the preceding year is used for computation. This is because there was a period in history when March 1st, not January 1st, was the beginning of the year. """ A=raw_input('Enter month as a number between 1 and 12: ') B=raw_input('Enter the day of the month as numbers between 1 and 31: ') year=raw_input('Enter year (eg. 1999): ') A=int(A) A=A-2 if A<0: A=A+12 B=int(B) C=int(year)%100 D=int(year)/100 if A==11: print '11th month' C=C-1 if A==12: print '12th month' C=C-1 # print A,' ',B,' ',C,' ',D W = (13*A - 1) / 5 X=C/4 Y=D/4 Z = W + X + Y + B + C - 2*D R=Z % 7 months=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] print A+2,'/',B,'/',year,' falls on ' + months[R]
true
1faf7950718cd67c1bd3dc182059763b1c784c5c
JosephLiu04/Wave3
/PythagTheorem.py
317
4.53125
5
from math import sqrt Side1 = float(input("Input the length of the shorter first side:")) Side2 = float(input("Input the length of the shorter second side: ")) def Pythag_theorem(): Side3 = sqrt((Side1 * Side1) + (Side2 * Side2)) return Side3 print("The length of the hypotenuse is", str(Pythag_theorem()))
true
9902409c31c852fd0878827aaa3b025099f997af
mrfabroa/ICS3U
/Archives/2_ControlFlow/conditional_loops.py
1,611
4.34375
4
__author__ = 'eric' def example1(): # initialize the total and number total = 0 number = input("Enter a number: ") # the loop condition while number != -1: # the loop statements total = total + number number = input("Enter a number: ") print "The sum is", total def example1_1(): """ write a program that uses a while loop to output the numbers from 1 to 10 :return: """ # for loop style for i in range(1,11): print i # while loop version count = 1 # initialize count at 1 # repeat while count <=10 while count <= 10: print count # output count count += 1 def example2(): # Set the number and number of entries to be 0 total = 0 entries = 0 # Read a number from the user number = input("Enter a number: ") # while the number is not -1 while number != -1: # sum = sum + number total = total + number # number of entries = number of entries + 1 entries += 1 # read a number from the user number = input("Enter a number: ") # Output sum/number of entries print float(total)/entries def largest(): biggest = 0 number = input("Enter number here: ") while number != -1: if number > biggest: biggest = number number = input("Enter number here: ") print biggest def infinite(): # repeat while count <=10 count = 1 while count <= 10: print count # output count #count += 1 --> commenting this out causes an infinite loop
true
c2e42318e56cf09abd5c1a456a4e3222a80e5226
mrfabroa/ICS3U
/Archives/3_Lists/3_1_practice.py
1,341
4.1875
4
__author__ = 'eric' def middleway(list_a, list_b): """ Given 2 int lists, list_a and list_b, each length 3, write a function middle_way(list_a,list_b) that returns a new list length 2 containing their middle elements. :param list_a: int[] :param list_b: int[] :return: int[] """ list_c = [list_a[1], list_b[1]] return list_c def common_end(list_a, list_b): """ Given 2 lists of ints, list_a and list_b, write a function common_end(list_a, list_b) and return True if they have the same first element or they have the same last element. Both lists will be length 1 or more. :param list_a: int[] :param list_b: int[] :return: Boolean """ if (list_a[0] == list_b[0]) or (list_a[-1] == list_b[-1]): return True else: return False def max_end3(list3): """ given a list (list3) of ints length 3, figure out which is larger between the first and last elements in the list, set all the other elements to be that value. Return the changed list. :param list3: int :return: int[] """ # compare first and last elements if list3[0] > list3[2]: list3[1] = list3[0] list3[2] = list3[0] elif list3[0] < list3[2]: list3[0] = list3[2] list3[1] = list3[2] return list3
true
8b505676a08ba224903433f7546e35ae8f441edb
manhtruong594/vumanhtruong-fundamental-c4e24
/Fundamental/Session04/homework/SeriousEx1.py
1,313
4.125
4
items = ["T-Shirt", "Sweater"] print("Here is my items: ", sep=" ") print(*items, sep=", ") loop = True while loop: cmd = input("Welcome to our shop, what do u want (C, R, U, D or exit)? ").upper() if cmd == "R": print("Our items: ", *items, sep=", ") elif cmd == "C": new = input("Enter new item: ") items.append(new) print("Our items: ", *items, sep=", ") elif cmd == "U": while True: position_update = int(input("Update position? ")) if 0 > position_update or position_update > len(items): print("No items in this position, try again!") else: update = input("Update to new item: ") items[position_update - 1] = update print("Our items: ", *items, sep=", ") break elif cmd == "D": while True: position_del = int(input("Delete position? ")) if 0 > position_del or position_del > len(items): print("No items in this position, try again!") else: items.pop(position_del) print("Our items: ", *items, sep=", ") break elif cmd == "exit": loop = False else: print("Only chose C, R, U, D or exit!! Try again!")
true
99ec192ac77df5906950a92b131e73665a76a06a
Cole-Hayson/L1-Python-Tasks
/Names List.py
1,136
4.25
4
names = ["Evi", "Madeleine", "Dan", "Kelsey", "Cayden", "Hayley", "Darian"] user_name = input("Enter a name") if user_name in names: print("That name is already on the list!") else: print("The name you chose is not on the list.") if user_name != names: replace = input("Would you like to replace one of the names on the list with the name you picked? yes or no.") if replace.lower() == "yes": names = ["Evi", "Madeleine", user_name, "Kelsey", "Cayden", "Hayley", "Darian"] print("We have replaced Dan with the name you have chosen. You are now on the list.") print(names) elif replace.lower() == "no": print("You have chosen to not replace a name on the list.\n") add = input("Would you like to add the name you picked to the list? yes or no.") if add.lower() == "yes": names = ["Evi", "Madeleine", "Dan", "Kelsey", "Cayden", "Hayley", "Darian", user_name] print("The name you picked has been added to the list.") print(names) elif add.lower() == "no": print("You have chosen to not add the name to the list.")
true
bd64fadca3071891ce36d42ddfdd8b1ddc96901b
PuneetPowar5/Small-Python-Projects
/fibonacciSequence.py
323
4.21875
4
print("Welcome to the Fibonacci Sequence Generator\n") maxNum = int(input("How many numbers of the sequence do you want to see? \n")) maxNum = int(maxNum) a = 0 b = 1 c = 0 print("\n") for num in range(0, maxNum): if(num <= 1): c = num else: c = a + b a = b b = c print(c)
true
aa960deeb474ab57d4ef72d675a8fd4742104014
egonnelli/algorithms
/sorting_algorithms/01_bubblesort.py
544
4.34375
4
#Bubblesort algorithm in python #Time complexity - O(N^2) def bubble_sort(array): """ This functions implements the bubble sort algorithm """ is_sorted = False counter = 0 while not is_sorted: is_sorted = True for i in range(len(array) - 1 - counter) if array[i] > array[i+1]: swap(i, i+1, array) is_sorted = False counter += 1 return array def swap(i,j,array): array[i] , array[j] = array[j], array[i] """ import numpy as np array = np.array([4,5,6,7,1,2,3]) bubble_sort(array) #array([1, 2, 3, 4, 5, 6, 7]) """
true
2af5b432ac298bebe3343f9ee18ae79e5f368b3e
Dushyanttara/Competitive-Programing
/aliens.py
2,312
4.15625
4
"""#Dushyant Tara(19-06-2020): This program will help you understand dictionary as a data strucutre alien_0 = {'color': 'green', 'points': 5} #print(alien_0['color']) #print(alien_0['points']) #new_points = alien_0['points'] #print("You just earned " + str(new_points) + " points.") #Adding new key:value pairs alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0) #Starting with an empty dictionary alien_0 = {} alien_0['color'] = 'green' alien_0['points'] = 5 print(alien_0) #Modifying values in a Dictionary alien_0 = {'color': 'green'} print("The alien is " + alien_0['color'] + ".") alien_0['color'] = 'yellow' print("The alien is now " + alien_0['color'] + ".") alien_0 = {'x_position' : 0, 'y_position': 25, 'speed':'medium'} print("Original x-position: " + str(alien_0['x_position'])) alien_0['speed'] = 'fast' #Move the alien to the right #Determine how far to move the alien based on its speed. if alien_0['speed'] == 'slow': x_increment = 1 elif alien_0['speed'] == 'medium': x_increment = 2 else: x_increment = 3 #The new position is the old position plus the increment alien_0['x_position'] += x_increment print("New x-position: " + str(alien_0['x_position'])) #Removing Key-value pairs alien_0 = {'color':'green','points':5} print(alien_0) del alien_0['points'] print(alien_0) """ alien_0 = {'color': 'green', 'points':5} alien_1 = {'color': 'yellow', 'points':10} alien_2 = {'color': 'red', 'points': 15} aliens = [alien_0, alien_1, alien_2] for alien in aliens: print(alien) #More aliens #Make an empty list for storing aliens aliens = [] # Make 30 green aliens. for alien_number in range(30): new_alien = {'color':'green','points':5, 'speed':'slow'} aliens.append(new_alien) for alien in aliens[0:3]: if alien['color'] == 'green': alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 elif alien['color'] == 'yellow': alien['color'] = 'red' alien['speed'] = 'fast' alien['points'] = 15 #Show first 5 aliens for alien in aliens[:5]: print(alien) print("....") #Show how many aliens have been created. print("Total number of aliens: " + str(len(aliens)))
true
6b6c88029116d4f5de407c8c8640345bdadb10bb
PajamaProgrammer/Python_MIT-6.00_Problem-Set-Solutions
/Problem Set 2/ps2b.py
2,303
4.15625
4
# Problem Set 2 (Part 4) # Name: Pajama Programmer # Date: 28-Oct-2015 # """ Problem4. Assume that the variable packages is bound to a tuple of length 3, the values of which specify the sizes of the packages, ordered from smallest to largest. Write a program that uses exhaustive search to find the largest number (less than 200) of McNuggets that cannot be bought in exact quantity. We limit the number to be less than 200 (although this is an arbitrary choice) because in some cases there is no largest value that cannot be bought in exact quantity, and we don’t want to search forever. Please use ps2b_template.py to structure your code. Have your code print out its result in the following format: “Given package sizes <x>, <y>, and <z>, the largest number of McNuggets that cannot be bought in exact quantity is: <n>” Test your program on a variety of choices, by changing the value for packages. Include the case (6,9,20), as well as some other test cases of your own choosing. """ bestSoFar = 0 # variable that keeps track of largest number # of McNuggets that cannot be bought in exact quantity packages = (9,11,20) # variable that contains package sizes def PrintNuggetFunction (nuggets, x, y, z): print ('I want to order Chicken McNuggets in packs of', x, y, 'and', z, 'so that I have exactly', nuggets, 'nuggets') return def PrintNuggetSolution (nuggets, x, y, z): print ('It takes', x, 'packs of 6,', y, 'packs of 9, and', z, 'packs of 20 Chicken McNuggets to =', nuggets) return def FindNuggetSolution (nuggets, x, y, z): for c in range (0, nuggets): for b in range (0, nuggets): for a in range (0, nuggets): if (x*a + y*b + z*c == nuggets): #PrintNuggetSolution (nuggets, x, y, z) return 1 return 0 x = packages[0] y = packages[1] z = packages[2] for n in range(1, 200): # only search for solutions up to size 200 if FindNuggetSolution(n, x, y, z) == 0: counter = 0 bestSoFar = n else: counter +=1 #print(counter) if counter == x: break print ('Given package sizes <', x,'>, <', y,'>, and <', z, '>, the largest number of McNuggets that cannot be bought in exact quantity is: ', bestSoFar, sep='')
true
2352cc95d3464d4a7f6a7f01781d9de1278b0113
UddeshJain/Master-Computer-Science
/Data_Structure/Python/Stack.py
1,262
4.34375
4
class Stack(object): ''' class to represent a stack Implemented with an array ''' def __init__(self): ''' Constructor ''' self.datas = [] def __str__(self): return " ".join(str(e) for e in reversed(self.datas)) def size(self): ''' return the size of the stack ''' return len(self.datas) def top(self): ''' Return the top of the stack ''' return self.datas[-1] def push(self, value): ''' add a value on the stack ''' return self.datas.append(value) def pop(self): ''' pop the last element of the stack ''' value = self.top() del self.datas[-1] return value def empty(self): self.datas = [] def print_stack(stack): print(f'stack : {stack}') if __name__ == "__main__": stack = Stack() print('Pushing 1') stack.push(1) print_stack(stack) print('Pushing 5') stack.push(5) print_stack(stack) print(f'top : {stack.top()}') print('popping') print(f'value poped : {stack.pop()}') print_stack(stack)
true
e8faa90b2c9b3ee9a1d694bb6a236e80cbd27733
missystem/math-crypto
/mathfxn.py
790
4.53125
5
""" Authors: Missy Shi Date: 05/22/2020 Python Version: 3.8.1 Functions: - largest_prime_factor Find the largest prime factor of a number - prime_factors Given a integer, return a set of factors of the number """ import math def largest_prime_factor(n: int) -> int: """ Return largest prime factor of number n """ i = 2 while i * i <= n: if n % i: i += 1 else: n //= i return n def prime_factors(n_1: int) -> set: """ Return a set of factors of number n_1 """ lpf = largest_prime_factor(n_1) factors = set() factors.add(lpf) c = 16 rest = n_1 // lpf while (rest != 1): lpf = largest_prime_factor(rest) rest = rest // lpf factors.add(lpf) c -= 1 return factors
true
682d25a675d2b58c48c7359774378ae921405b24
missystem/math-crypto
/prime.py
1,155
4.21875
4
""" Author: Missy Shi Course: math 458 Date: 04/23/2020 Project: A3 - 1 Description: Write a Python function which, given n, returns a list of all the primes less than n. There should be 25 primes less than 100, for instance. Task: How many prime numbers are there which are less than 367400? """ import math def is_prime(n: int) -> bool: """ Check if a integer is prime, If it is, return True, else return False """ if n < 2: # print(f"{n} is not a prime number") return False else: for i in range(2, n): if (n % i) == 0: # print(f"{n} is not a prime number") # print(f"{n} divides {i} = {n//i}") return False return True def q1(): """ Find primes less than given number n """ # n = int(input('Input an integer: ')) n = 367400 pl = [] for i in range(1, n): if is_prime(i) is True: pl.append(i) count = len(pl) print(f"{count} prime numbers less than {n}") # print(pl) return def main(): """main program runner""" q1() if __name__ == '__main__': main()
true
cea5559f924ca0ec895074ca5898c96fc003bc74
sahilkumar4all/HMRTraining
/Day-5/calc_final.py
380
4.125
4
def calc(operator): z = eval(x+operator+y) print(z) print(''' Press 1 for addition press 2 for substraction press 3 for multiplication press 4 for division''') x = input("enter first no") y = input("enter second no") choice = input("enter operation you wanna perform") dict = {"1":"+", "2":"-", "3":"*", "4":"/"} opr = dict.get(choice) calc(opr)
true
cc669352fa7f30b87d40343ab529635289a35884
Miguelmargar/file-io
/writefile.py
698
4.125
4
f = open("newfile.txt", "a") # opens and creates file called newfile.txt to write on it with "w" - if using "a" it means append not create new or re-write f.write("\nHello World\n") # writes Hello on the file opened above - depending on where you use the \n the lines will brake accordingly f.close() # closes the file but it is still stored in memory #---------------------------------------------------------------------- words = ["the", "quick", "brown", "fox"] words_as_string = "\n".join(words) # this will append \n to the words in words list above it f = open("newfile.txt", "w") f.write(words_as_string) f.close()
true
a153c0f74861ec3c8c786b7b5d9b379331904612
cheeseaddict/think-python
/chapter-6/exercise-6.2.py
667
4.25
4
import math def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 dsquared = dx**2 + dy**2 result = math.sqrt(dsquared) return result print(distance(1,2,4,6)) """ As an exercise, use incremental development to write a function called hypotenuse that returns the length of the hypotenuse of a right triangle given the lengths of the other two legs as arguments. Record each stage of the development process as you go. """ def hypotenuse(a, b): # a**2 + b**2 = c**2 # square_a = a**2 # square_b = b**2 # c = square_a + square_b # result = math.sqrt(c) return math.sqrt(a**2 + b**2) print(hypotenuse(3, 4)) # => 5.0
true
3d045213ec7cc8711783ec2e6be8eeedf4ebf6c2
FrankchingKang/phrasehunter
/phrasehunter/character.py
1,774
4.125
4
# Create your Character class logic in here. class Character(object): """The class should include an initializer or def __init__ that receives a char parameter, which should be a single character string.""" def __init__(self,char): """An instance attribute to store the single char string character so the Character object will be able to remember the original character. You might call this instance attribute original, but that will be up to you. An instance attribute to store a boolean value (True or False) of whether or not this letter has had a guess attempted against it. You can initialize this to False inside __init__ as any new Character object will start with a default of False meaning it has not been guessed before. You might name this instance attribute was_guessed, but that will also be up to you.""" if len(char) == 1: self.original = char else: self.original = char[0] self.was_guessed = False def check_the_answer(self,guess): """An instance method that will take a single string character guess as an argument when its called. The job of this instance method is to update the instance attribute storing the boolean value, if the guess character is an exact match to the instance attribute storing the original char passed in when the Character object was created.""" if guess == self.original: self.was_guessed = True return True else: return False def show_the_char(self): if self.was_guessed: print(self.original, end = " ") else: print("_", end = " ") def reset_character(self): self.was_guessed = False
true
898ed9b37e512dca37848a040ff175ce57b65e08
mverleg/bardeen
/bardeen/inout.py
2,011
4.15625
4
""" Routines related to text input/output """ import sys, os def clear_stdout(lines = 1, stream = sys.stdout, flush = True): """ Uses escape characters to move back number of lines and empty them To write something on the empty lines, use :func:sys.stdout.write() and :func:sys.stdout.flush() :param lines: the number of lines to clear :param stream: by default, stdout is cleared, but this can be replaced by another stream that uses these \ escape characters (stderr comes to mind) :param flush: by default, uses flush after writing, but canbe overriden if you will do it yourself soon after """ stream.write('\033[F\r\x1b[K' * lines) if flush: stream.flush() def reprint(txt, lines = 1, stream = sys.stdout): """ Removes lines from stdout and prints the requested text txt instead of them :param txt: the text you want to print; works best if no more than `lines` lines :param stream: see ``clear_stdout`` :param lines: the number of lines you want to use; \ this amount is cleared and if txt is shorter, the remainder is prepended For example for status monitoring: 1. print N newlines 2. do something or check something until there is news 3. use ``reprint`` to print the as most N lines update using lines = N 4. repeat step 2 and 3 until task is done 5. if you want to remove the last status message, call clear_stdout using lines = N """ clear_stdout(lines = lines, flush = False) line_count = len(txt.splitlines()) stream.write( os.linesep * (lines - line_count) + txt + os.linesep ) stream.flush() def add_linebreaks(text, max_len=80): """ Add linebreaks on whitespace such that no line is longer than `max_len`, unless it contains a single word that's longer. There are probably way faster methods, but this is simple and works. """ br_text = '' len_cnt = 0 for word in text.split(' '): len_cnt += len(word) + 1 if len_cnt > max_len: len_cnt = len(word) br_text += '\n' + word else: br_text += ' ' + word return br_text[1:]
true
c824029a5d1ef7317bb98bd39f623292fd392d71
ms-shakil/Some_problems_with_solve
/Extra_Long_Factorial.py.py
401
4.125
4
""" The factorial of the integer n , written n! , is defined as: n! = n * (n-1)*(n-2)*... *2*1 Calculate and print the factorial of a given integer. For example Inp =25 we calculate 25* 24* 23*....*2*1 and we get 15511210043330985984000000 . """ def Factorial(inp): val = 1 for i in range(1,inp): val += val*i print(val) inp = int(input("Enter the value:")) Factorial(inp)
true
12b784aecca1d4276228b7b7ad13d3cc1d679208
lenncb/safe_password
/main.py
1,319
4.125
4
# This programm will show you how strong your password is # If your password is weak, program will generate new and strong password. # Just write your password import re, password_generator password = input(str('Enter your password: ')) #good password is if it has minimum 8 signs, inculde small and big letters and has minimum one number #strong password is if it has minimum 8 signs, inculde small and big letters, minimum one number and one special sign e.g. exclamation mark (!) good_password = re.compile(r''' ^(?=.*[A-Z]) (?=.*[a-z]) (?=.*\d) (.{8,})$ ''', re.VERBOSE) strong_password = re.compile(r''' ^(?=.*[A-Z]) (?=.*[a-z]) (?=.*\d) (?=.*[(){}[@/|:;<>+^$!%*?&'`~]) (.{8,})$ ''', re.VERBOSE) print(strong_password.findall(password)) if len(strong_password.findall(password)) == 1 : print('Your password: '+ str(''.join(strong_password.findall(password))) + " is strong password. You don't need to change it.") elif len(good_password.findall(password)) == 1: print('Your password: '+ str(''.join(good_password.findall(password))) + " is good password. You can change it but you dont need to do it.") password_generator.new_password_question() else: print('Your password: ' + password + " is too weak ! Change it as fast as it is possible !") password_generator.new_password_question()
true
37693a5b038c83a5eae1f13d6bd0540c4852b9ad
navinduJay/interview
/python/sort/insertionSort.py
635
4.34375
4
#INSERTION SORT array = [] #array declaration for everyValue in range(10): array.append(input("Enter number ")) #adding values to the array print('Unsorted array') print(array) def insertionSort(array): #function declaration for j in range(1 , len(array)): # starting index is 1(2nd position) to array length keyValue = array[j] #key = array[j] i = j - 1 #i'th index should one less than j'th index while(i >= 0 and array[i] > keyValue): array[i + 1] = array[i] i = i - 1 array[i + 1] = keyValue insertionSort(array) print('Sorted array') print(array)
true
c574d55303bce0e3e99b39777be42153f3c47a7d
minkyaw17/CECS-328
/Lab 5/lab5.py
2,656
4.15625
4
import random import time def swap(arr, a, b): # swap function to be used in the heap sort and selection sort temp = arr[a] arr[a] = arr[b] arr[b] = temp def max_heapify(arr, i, n): # parameter n for length of array max_element = i left = (2 * i) + 1 right = (2 * i) + 2 max_element = i # if there's a left child of the root and it's greater than the root if left < n and arr[left] > arr[max_element]: max_element = left # if there's a right child of the root and it's greater than the root if right < n and arr[right] > arr[max_element]: max_element = right if max_element != i: swap(arr, i, max_element) max_heapify(arr, max_element, n) def build_maxHeap(arr): n = len(arr) start_range = (n // 2) - 1 for i in range(start_range, -1, -1): max_heapify(arr, i, n) def heap_sort(arr, ind, n): build_maxHeap(arr) for i in range(n - 1, 0, -1): # removing the roots one by one until the tree/array becomes empty swap(arr, arr.index(arr[i]), arr.index(arr[0])) max_heapify(arr, 0, i) def selection_sort(arr): n = len(arr) for i in range(n - 1): min_index = i # keeping track of the min index for j in range(i + 1, n): if arr[min_index] > arr[j]: # if the element with the min index is greater than the current element, # set it equal to that index min_index = j swap(arr, i, min_index) def heap_sort_program(): print("Part A:\n") n = int(input("Please enter the number of elements you wish to put into an array (a positive integer): ")) # assuming user input will be 1000 and will do 100 reps to check the run time a = [random.randint(-100, 100) for i in range(n)] a2 = a[:] reps = 100 start_hs = time.time_ns() for i in range(reps): heap_sort(a, 0, n) stop_hs = time.time_ns() end_hs = (stop_hs - start_hs) / reps print("Average running time for heap sort:", end_hs, "ns") start_sc = time.time_ns() for i in range(reps): selection_sort(a2) stop_sc = time.time_ns() end_sc = (stop_sc - start_sc) / reps print("Average running time for selection sort:", end_sc, "ns") time_diff = end_sc - end_hs print("Time difference in which heapsort is faster by:", time_diff, "ns") def manual_heap_sort(): print("\nPart B:\n") size_arr = 10 a = [random.randint(-100, 100) for i in range(size_arr)] print("Original array:", a) heap_sort(a, 0, size_arr) print("Sorted array:", a) heap_sort_program() manual_heap_sort()
true
589aada2ad71b067e9602780edd62c7e540169db
carlosmertens/Python-Masterclass
/challenge_control_flow.py
1,456
4.34375
4
# Complete Python MasterClass Course # # This challenge is intended to practise for loops and if/else statements, # so although you could use other techniques (such as splitting the string up), # that's not the approach we're looking for here. # # Create a program that takes an IP address entered at the keyboard and prints # out the number of segments it contains, and the length of each segment. # # An IP address consists of 4 numbers, separated with a full stop. # But your program should count however many are entered since we're just # interested in the number of segments and how long each one is. # Examples of the input you may get are: # 127.0.0.1 # .192.168.0.1 # 10.0.123456.255 # 172.16 # 255 # .123.45.678.91 # 123.4567.8.9. # 123.156.289.10123456 # 10.10t.10.10 # 12.9.34.6.12.90 # '' - that is, press enter without typing anything # Retrieve input from user ip_address = input("Please enter your IP address: ") # Add a dot at the end if it is none. It ill help with count the iterations if ip_address[-1] != ".": ip_address += "." # Initiate counter variables segments_number = 1 segment_length = 0 # Iterate throught the input for i in ip_address: # Update counter when a dot is encounter if i == ".": print("Segment {} contains {} characters.".format(segments_number, segment_length)) segments_number += 1 segment_length = 0 else: segment_length += 1
true
ee6e9248a17fc4ec2426cebf57ec9404dea28955
ardaunal4/My_Python_Lessons
/ClassPython/example_of_properties_of_classes.py
1,459
4.21875
4
# -*- coding: utf-8 -*- """ Created on Wed May 27 02:35:30 2020 @author: ardau """ from abc import ABC, abstractmethod from cmath import pi class shape(ABC): """ Parent class / abstract class example """ # abstract methods @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass # overriding and polymorphism def toString(self): pass class square(shape): def __init__(self, edge): self.__edge = edge # encapsulation or with other mean private attribute def area(self): area = self.__edge ** 2 print('Square area = ', area) def perimeter(self): perimeter = self.__edge * 4 print('Perimeter of square = ', perimeter) def toString(self): print('Square edge = ', self.__edge) class circle(shape): def __init__(self, radius): self.__radius = radius def area(self): area = pi * self.__radius ** 2 print('circle area = ', area) def perimeter(self): perimeter = 2 * pi * self.__radius print("perimeter of circle = ", perimeter) def toString(self): print('Circle radius = ', self.__radius) c = circle(5) c.toString() c.area() c.perimeter() s = square(5) s.toString() s.area() s.perimeter()
true
33c1feb36398f075fc0b1d205803ad901e7366d6
ardaunal4/My_Python_Lessons
/ALGORITHMS/Fundemantals of_Python_Questions/questions3.py
723
4.25
4
# How you can convert a sorted list to random from random import shuffle my_list = [0, 1, 2, 3, 4, 5, 6, 7] print("Sorted list : ", my_list) shuffle(my_list) print("Shuffled list : ", my_list) # How you can make sorted list from random list my_list.sort() print("Sorted list : ", my_list) # What are functionality of the join() and split() functions astring = "hello" new_string = ".".join(astring) # it puts . between every latter in the word. print("Join() with '.' : ", new_string) splitted_string = new_string.split(".") # Split function seperates the word according to '.' print("Split() with '.' : ", splitted_string) joined = "".join(splitted_string) print("Join() after split() : ", joined)
true
5e2eba80e377a1eb7d2fadfe8c52999605fe8e06
ardaunal4/My_Python_Lessons
/ClassPython/abstract_class.py
488
4.28125
4
from abc import ABC, abstractmethod # abc -> abstract base class class Animal(ABC): #super class @abstractmethod # this makes the class abstract def walk(self): pass def run(self): pass # this abstract class is a kind of template for other sub classes class Bird(Animal): # sub class or child class def __init__(self): print('bird') def walk(self): print('walk') obj1 = Animal() # b1 = Bird()
true
6421bd469e371aa256b634c344f81c71072ff336
dailycodemode/dailyprogrammer
/Python/034_squareTwoLargest.py
984
4.15625
4
# https://www.reddit.com/r/dailyprogrammer/comments/rmmn8/3312012_challenge_34_easy/ # DAILY CODE MODE def square_two_largest(list): list.sort(reverse=True) return list[0] ** 2 + list[1] ** 2 print(square_two_largest([3,1,2])) # ANSWER BY Should_I_say_this def sumsq(a,b,c): l=[a,b,c] del l[l.index(min(l))] return sum(i**2 for i in l) # BREAKDOWN # del l[l.index(min(l))] # Answer has chosen to eliminate the lowest number from the list to be only left with two arguments sum(i**2 for i in l) # He then squares everything in the list and then returns the value # Comment # Not the greatest fan of the answer provided because it can only ever be used for this scenario where # three arguments are given and the sum of the two highest is returned. # With my answer, it doesn't matter the size of the list. # I should not that I should the questions a little more carefully because it asked for three arguments. # Not three arguements contained within a list.
true
4a977849536b8afc9d7cce8f715d1359009d14da
rnekadi/CSEE5590_PYTHON_DEEPLEARNING_FALL2018
/ICP3/Source/codon.py
522
4.21875
4
# Program to read DNA Codon Sequence and Split into individual Codon # Fixed Codon Sequence codonseq = 'AAAGGGTTTAAA' # Define List to hold individual Codon codon = [] # Defining function to to fill Codon list def codonlist(seq): if len(seq) % 3 == 0: for i in range(0, len(seq), 3): codon.append(seq[i:i+3]) print() # Calling Codonlist function codonlist(codonseq) # Output print('The input Sequence is ', codonseq) print('The individual codon sequence are : ', codon)
true
2d7a2d740143a19d38e290c3dc81e00cafcdeaff
smailmedjadi/jenkins_blueocean
/src/new_functions.py
570
4.1875
4
def bubbleSort(list): for passnum in range(len(list)-1,0,-1): for i in range(passnum): if list[i]>list[i+1]: temp = list[i] list[i] = list[i+1] list[i+1] = temp def insertionSort(list): for index in range(1,len(list)): currentvalue = list[index] position = index while position>0 and list[position-1]>currentvalue: list[position]=list[position-1] position = position-1 list[position]=currentvalue print ("testing functions")
true
0ec2e9f2fcb36f32ae4220b6f35fa96529a2af30
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/sum_2_binary_numbers_without_converting_to_integer.py
1,784
4.21875
4
# Task: # # Given two binary numbers represented as strings, return the sum of the two binary numbers as a new binary represented # as a string. Do this without converting the whole binary string into an integer. # # Here's an example and some starter code. # # def sum_binary(bin1, bin2): # # Fill this in. # # print(sum_binary("11101", "1011")) # # 101000 from typing import Tuple def sum_binary_digits(binary_digit1: str, binary_digit2: str, overflow: bool) -> Tuple[str, bool]: if binary_digit1 == '1': if binary_digit2 == '1': if overflow: return '1', True else: return '0', True else: if overflow: return '0', True else: return '1', False else: if binary_digit2 == '1': if overflow: return '0', True else: return '1', False else: if overflow: return '1', False else: return '0', False def sum_2_binary_numbers_without_converting_to_integer(binary_number1: str, binary_number2: str) -> str: overflow: bool = False index_in_number1: int = len(binary_number1) - 1 index_in_number2: int = len(binary_number2) - 1 result: str = '' while index_in_number1 >= 0 or index_in_number2 >= 0 or overflow: binary_digit1: str = binary_number1[index_in_number1] if index_in_number1 >= 0 else 0 binary_digit2: str = binary_number2[index_in_number2] if index_in_number2 >= 0 else 0 result_digit, overflow = sum_binary_digits(binary_digit1, binary_digit2, overflow) result = result_digit + result index_in_number1 -= 1 index_in_number2 -= 1 return result
true
480dd41bb1dfde38741970333c6442df17dd944a
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/sort_array_with_three_values_in_place.py
2,376
4.25
4
# Task: # # Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are # adjacent, with the colors in the order red, white and blue. # # Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. # # Note: You are not suppose to use the library’s sort function for this problem. # # Can you do this in a single pass? # # Example: # Input: [2,0,2,1,1,0] # Output: [0,0,1,1,2,2] # Here's a starting point: # # class Solution: # def sortColors(self, nums): # # Fill this in. # # nums = [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1] # print("Before Sort: ") # print(nums) # # [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1] # # Solution().sortColors(nums) # print("After Sort: ") # print(nums) # # [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2] from typing import List class Solution: @staticmethod def sort_colors(numbers: List[int]) -> None: number_count: int = len(numbers) if number_count > 1: last_zero_index: int = -1 last_one_index: int = -1 first_two_index: int = number_count while last_one_index + 1 < first_two_index: current_number: int = numbers[last_one_index + 1] if current_number == 0: last_zero_index += 1 last_one_index += 1 if last_zero_index != last_one_index: numbers[last_zero_index] = 0 numbers[last_one_index] = 1 elif current_number == 1: last_one_index += 1 else: first_two_index -= 1 numbers[last_one_index + 1] = numbers[first_two_index] numbers[first_two_index] = current_number def sort_and_print(numbers: List[int]) -> None: print('Before Sort: {}'.format(numbers)) Solution.sort_colors(numbers) print('After Sort: {}'.format(numbers), end='\n\n') sort_and_print([]) # [] sort_and_print([0]) # [0] sort_and_print([0, 1]) # [0, 1] sort_and_print([0, 2, 1]) # [0, 2, 1] sort_and_print([1, 1, 1]) # [1, 1, 1] sort_and_print([2, 1, 0]) # [0, 1, 2] sort_and_print([0, 0, 1, 1, 2, 2]) # [0, 0, 1, 1, 2, 2] sort_and_print([0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1]) # [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2]
true
96002e94186bdfef6a04951c5b99d55e21bb9d00
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/find_first_recurring_character.py
1,231
4.125
4
# Task: # # Given a string, return the first recurring letter that appears. If there are no recurring letters, return None. # # Example: # # Input: qwertty # Output: t # # Input: qwerty # Output: None # # Here's some starter code: # # def first_recurring_char(s): # # Fill this in. # # print(first_recurring_char('qwertty')) # # t # # print(first_recurring_char('qwerty')) # # None def first_recurring_char(s: str) -> str: if s is None: return None else: string_length: int = len(s) if string_length < 2: return None else: previous_character: str = s[0] for i in range(1, string_length): current_character: str = s[i] if current_character == previous_character: return previous_character else: previous_character = current_character return None print(first_recurring_char('qwertty')) # t print(first_recurring_char('qwerty')) # None print(first_recurring_char('qwertyt')) # None print(first_recurring_char('qwerttyy')) # t print(first_recurring_char('q')) # None print(first_recurring_char('')) # None print(first_recurring_char(None)) # None
true
04269da9800ce546e8c89a5d9cba8b74b102e05d
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/swap_every_two_nodes_in_linked_list.py
1,632
4.15625
4
# Task: # # Given a linked list, swap the position of the 1st and 2nd node, then swap the position of the 3rd and 4th node etc. # # Here's some starter code: # # class Node: # def __init__(self, value, next=None): # self.value = value # self.next = next # # def __repr__(self): # return f"{self.value}, ({self.next.__repr__()})" # # def swap_every_two(llist): # # Fill this in. # # llist = Node(1, Node(2, Node(3, Node(4, Node(5))))) # print(swap_every_two(llist)) # # 2, (1, (4, (3, (5, (None))))) from typing import Optional class Node: def __init__(self, value, next_node=None): self.value = value self.next: Optional[Node] = next_node def __repr__(self) -> str: return f"{self.value}, ({self.next.__repr__()})" def swap_every_two_nodes_in_linked_list(input_head_node: Optional[Node]) -> Optional[Node]: head: Optional[Node] = None previous_already_swapped: Optional[Node] = None current: Node = input_head_node while current is not None and current.next is not None: old_next: Node = current.next new_current: Node = old_next.next new_next: Node = current if previous_already_swapped is not None: previous_already_swapped.next = old_next else: head = old_next old_next.next = new_next previous_already_swapped = new_next new_next.next = None current = new_current if current is None: return head else: if head is None: return current else: previous_already_swapped.next = current return head
true
cc2d33ae78495714b158947820c819a25734ed64
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/find_shortest_distance_of_characters_to_given_character.py
1,560
4.15625
4
# Task: # # Given a string s and a character c, find the distance for all characters in the string to the character c in # the string s. You can assume that the character c will appear at least once in the string. # # Here's an example and some starter code: # # def shortest_dist(s, c): # # Fill this in. # # print(shortest_dist('helloworld', 'l')) # # [2, 1, 0, 0, 1, 2, 2, 1, 0, 1] from typing import List def calculate_distances_in_one_direction(input_string: str, target_character: str, distances: List[int], input_range: iter): distance_to_closest: int = len(input_string) for i in input_range: current_character: str = input_string[i] if current_character == target_character: distance_to_closest = 0 distances[i] = 0 else: distance_to_closest += 1 distances[i] = min(distances[i], distance_to_closest) def find_shortest_distance_of_characters_to_given_character(input_string: str, target_character: str) -> List[int]: """Time complexity ... O(n) where *n* is the length of the *input_string*. Reason: we iterate twice over all characters of *input_string*. """ string_length: int = len(input_string) distances: List[int] = [string_length] * string_length calculate_distances_in_one_direction(input_string, target_character, distances, range(0, string_length)) calculate_distances_in_one_direction(input_string, target_character, distances, reversed(range(0, string_length))) return distances
true
1dc29418a4324e658afdddbabd372c2dbe9ae97c
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/find_characters_appearing_in_all_strings.py
862
4.15625
4
# Task: # # Given a list of strings, find the list of characters that appear in all strings. # # Here's an example and some starter code: # # def common_characters(strs): # # Fill this in. # # print(common_characters(['google', 'facebook', 'youtube'])) # # ['e', 'o'] from typing import List, Set def find_characters_appearing_in_all_strings(strings: List[str]) -> Set[str]: string_count: int = len(strings) if string_count == 0: return set() else: common_characters: Set[str] = set(strings[0]) for i in range(1, string_count): new_common_characters: Set[str] = set() for character in list(strings[i]): if character in common_characters: new_common_characters.add(character) common_characters = new_common_characters return common_characters
true
9e6ca28b0657297cd3223daef3a3fb6eee2e0ec9
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/reverse_integer_without_converting_it_to_string.py
677
4.3125
4
# Task: # # Given an integer, reverse the digits. Do not convert the integer into a string and reverse it. # # Here's some examples and some starter code. # # def reverse_integer(num): # # Fill this in. # # print(reverse_integer(135)) # # 531 # # print(reverse_integer(-321)) # # -123 from math import floor def reverse_integer_without_converting_it_to_string(input_number: int) -> int: rest: int = input_number negative: bool = rest < 0 if negative: rest *= -1 result: int = 0 while rest > 0: new_rest: int = floor(rest / 10) result = result * 10 + rest % 10 rest = new_rest return result * (-1 if negative else 1)
true
d720bec8f8a39a08d7eba61fb7006042e54394e8
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/reverse_binary_representation_of_integer.py
980
4.15625
4
# Task: # # Given a 32 bit integer, reverse the bits and return that number. # # Example: # # Input: 1234 # # In bits this would be 0000 0000 0000 0000 0000 0100 1101 0010 # Output: 1260388352 # # Reversed bits is 0100 1011 0010 0000 0000 0000 0000 0000 # # Here's some starter code: # # def to_bits(n): # return '{0:08b}'.format(n) # # def reverse_num_bits(num): # # Fill this in. # # print(to_bits(1234)) # # 10011010010 # print(reverse_num_bits(1234)) # # 1260388352 # print(to_bits(reverse_num_bits(1234))) # # 1001011001000000000000000000000 def to_bits(n: int) -> str: return '{0:b}'.format(n) def reverse_num_bits(num: int) -> int: binary_representation: str = '{0:032b}'.format(num) reversed_binary_representation: str = binary_representation[::-1] return int(reversed_binary_representation, 2) print(to_bits(1234)) # 10011010010 print(reverse_num_bits(1234)) # 1260388352 print(to_bits(reverse_num_bits(1234))) # 1001011001000000000000000000000
true
9e1f8ae86d4092c5105f8ab43ff0356c00777fea
Sandeep8447/interview_puzzles
/src/main/python/com/skalicky/python/interviewpuzzles/search_in_matrix_with_sorted_elements.py
2,075
4.25
4
# Task: # # Given a matrix that is organized such that the numbers will always be sorted left to right, and the first number of # each row will always be greater than the last element of the last row (mat[i][0] > mat[i - 1][-1]), search for # a specific value in the matrix and return whether it exists. # # Here's an example and some starter code. # # def search_in_matrix_with_sorted_elements(matrix, searched_value): # # Fill this in. # # mat = [ # [1, 3, 5, 8], # [10, 11, 15, 16], # [24, 27, 30, 31], # ] # # print(search_in_matrix_with_sorted_elements(mat, 4)) # # False # # print(search_in_matrix_with_sorted_elements(mat, 10)) # # True from math import floor from typing import List, Tuple def convert_number_to_matrix_coordinates(number: int, column_count: int) -> Tuple[int, int]: row_index: int = floor(number / column_count) column_index: int = number % column_count return row_index, column_index def search_in_matrix_with_sorted_elements(matrix: List[List[int]], searched_value: int) -> bool: """Time complexity ... O(log n) where *n* is the size of the given matrix. Reason: binary search in matrix implemented""" row_count: int = len(matrix) column_count: int = len(matrix[0]) lower_bound_included: int = 0 upper_bound_excluded: int = row_count * column_count while lower_bound_included < upper_bound_excluded: global_index_of_element_in_middle: int = floor((upper_bound_excluded + lower_bound_included) / 2) row_index_of_element_in_middle, column_index_of_element_in_middle = convert_number_to_matrix_coordinates( global_index_of_element_in_middle, column_count) element_in_middle: int = matrix[row_index_of_element_in_middle][column_index_of_element_in_middle] if element_in_middle == searched_value: return True elif element_in_middle > searched_value: upper_bound_excluded = global_index_of_element_in_middle - 1 else: lower_bound_included = global_index_of_element_in_middle + 1 return False
true
8a5fcc17e24a57d5783b8f91a7a41f480171d9c3
ksu-is/Hotel-Python
/hotelpython2.py
1,949
4.125
4
print("Welcome to Hotel Python!") print("\t\t 1 Booking") print("\t\t 2 Payment") print("\t\t 3 Guest Requests") print("\t\t 4 Exit") reservation=" " payment=" " payment_method=" " requests=" " def guest_info(reservation="A"): print("Please collect guest information such as name, phone number, and dates of stay") reservation=" " guest_info("A") agent=input("Enter guest name: ") print(agent) agent_a=input("Enter guest phone number: ") print(agent_a) agent_b=input("Enter the desired check in date and check out date in MM/DD/YY = MM/DD/YY: ") print(agent_b) agent_c=input("Enter cash or card: ") print(agent_c) def guest_requests(requests="R"): print("Ask guest if they have any special requests for the room: ") requests="R" guest_requests("R") agent_d=input("Enter special requests: ") print(agent_d) while True: breakfast = input("Would you like to add breakfast to your stay (yes or no): ") print() if breakfast.lower() == "yes": print("Breakfast will be added to your final bill. This includes breakfast for two. Each additional meal will be $10.") break else: print("Breakfast will not be added to your final bill. Please let me know if you would like to change that.") room_rate=int(input("Enter weekend room rate: ")) hotel_stayfee=5 breakfast_charge=10 final_total=room_rate + hotel_stayfee + breakfast_charge print() print("Repeat the following information back to guest: ") print() print("Thank you for choosing to stay at Hotel Python. We have", agent, "staying with us", agent_b, "using", agent_c, "to pay for the room. We also made sure to include", agent_d, "in the room notes as well.") print() print("Final Bill as follows...") print(agent, ",thank you for choosing to stay with us.") print(agent_a) print() print("Method of Payment: ", agent_c) print("Breakfast Charge: ", breakfast) print("The total amount charged for your stay is $", final_total)
true
ce09f1c9ebded1b1b2716f017583dea3d4cf5a23
rfaroul/Activities
/Week03/3/lists.py
1,601
4.28125
4
prices = ["24","13","16000","1400"] price_nums = [int(price) for price in prices] print(prices) print(price_nums) dog = "poodle" letters = [letter for letter in dog] print(letters) print(f"We iterate over a string into a list: {letters}") capital_letters = [letter.upper() for letter in letters] print(capital_letters) #LONG VERSION OF ABOVE capital_letters2 = [] for letter in letters: capital_letters2.append(letter.upper()) print(capital_letters2) no_o = [letter for letter in letters if letter != 'o'] print(no_o) #or no_os = [] for letter in letters: if letter != 'o': no_os.append(letter) print(no_os) june_temperature = [72,65,59,87] july_temperature = [87,85,92,79] august_temperature = [88,77,66,100] temperature = [june_temperature,july_temperature,august_temperature] lowest_summer_temperatures = [min(temps) for temps in temperature] print(lowest_summer_temperatures) #or lowest_summer_temperatures2 =[] for temps in temperature: lowest_summer_temperatures2.append(min(temps)) print(lowest_summer_temperatures2) print(lowest_summer_temperatures[0]) print(lowest_summer_temperatures[1]) print(lowest_summer_temperatures[2]) print("-" * 50)#divider print(lowest_summer_temperatures2[0]) print(lowest_summer_temperatures2[1]) print(lowest_summer_temperatures2[2]) print("-" * 50)#divider #average print(sum(lowest_summer_temperatures)/len(lowest_summer_temperatures)) def name(parameter): return "Hello " + parameter print(name("Kash")) def avg(data1,data2): return (sum(data1)/len(data1))+(sum(data2)/len(data2)) print(avg([1,2,3,4,5,6],[3,4,20]))
true
131f1147267852294f9674c7b6883c1f5f580d7d
minhazalam/py
/data_collectn_and_processing/week_1/nested_iteration.py
443
4.5
4
# In this program we'll implement the nested iteration concepts using # * two for loops # * one loop and a square bracket(indexing) # * indexing(square bracket) and a for loop # nested list nested1 = [1, 2, ['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']] # iterate for x in nested1: # outer loop print("level1: ") if type(x) is list : for y in x : print(" level2: {}".format(y)) else : print(x)
true
4448b46aeb6c9ba1ea874f52aa7a0a8a10c761d7
minhazalam/py
/class_inheritance/inheritance/inheritance.py
827
4.28125
4
# Intro : Inheritance in python 3 # current year CURRENT_YEAR = 2020 # base class class Person: # constructor def __init__(self, name, year_born): self.name= name self.year_born = year_born # def methods def get_age(self): return CURRENT_YEAR - self.year_born # def __str__(self): # return self.name # inheritance syntax # class derived_class(base_class) # use inheritance to derive properties of the base class class Student (Person): # constructor def __init__(self): # derive from the person class Person.__init__(self, name, year_born) self.knowledge = 0 # def method def study(self): return self.knowledge + 1 # create instance minhaz = Person("Minhaz Alam", 1997) # print(minhaz.study()) print(minhaz.get_age())
true
b2677a1cee82e3f2a851f604804f276131f63d75
minhazalam/py
/class_inheritance/exceptions/try_exception.py
554
4.15625
4
# we'll see how this try and exception works in the python 3 programming language # syntax : # try: # <try clause code block> # except <ErrorType>: # <exception handler code block> # def square(num): # return num * num # # assertion testingg # assert square(3) == 9 # try and except block of statement a_list = ['a', 'b'] try : # if something went wrong then in try block next statement will not be executed third = a_list[2] except: print("Third element does not exist") # after except statements are executed print("heyo")
true
8c44c1692f9091b3290f50c23ee3529888b606db
adam-worley/com404
/1-basics/5-functions/4-loop/bot.py
271
4.125
4
def cross_bridge (steps): x = 0 while (steps>0): print("Crossed step") steps = (steps-1) x = x+1 if (x>=5): print("The bridge is collapsing!") else: print("we must keep going") cross_bridge(3) cross_bridge(6)
true
0a7343306387e4f6c326a8bec187da13dc2c45ed
adam-worley/com404
/1-basics/6-mocktca/1-minimumtca/Q2.py
255
4.125
4
print("Where is Forky?") forky_location=str(input()) if (forky_location=="With Bonnie"): print("Phew! Bonnie will be happy.") elif(forky_location=="Running away"): print ("Oh no! Bonnie will be upset!") else: print("Ah! I better look for him")
true
637abb15832ba8ebafa8e90d958df4ea05d3b236
keshavkummari/KT_PYTHON_6AM_June19
/Functions/Overview_Of_Functions.py
1,347
4.25
4
# Functions in Python # 1. def # 2. Function Name # 3. Open & Close Paranthesis and Parameters # 4. Colon : Suit # 5. Indented # 6. return statement - Exits a Function """ def function_name(parameters): function_suite return [expression] def sum(var1,var2): total = var1 + var2 print(total) return a = sum(10,20) #print(a) """ # Function Arguments: ''' You can call a function by using the following types of formal arguments: 1. Required arguments 2. Keyword arguments 3. Default arguments 4. Variable-length arguments # 1. Required arguments def sum(var1): print(var1) return # Create a Variable abc = 10 a = sum(abc) sum(abc) # 2. Keyword arguments def hello1(name,age): print(name) print(age) return hello1(name="Guido Van Rossum",age=50) # 3. Default arguments #!/usr/bin/python # Function definition is here def info( name, age = 35 ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return # Now you can call info function info(name="Guido",age=input("Enter the Age: ")) ''' # 4. Variable-length arguments def info(*var1): for i in var1: print(i) return info(10,20,30,40,50,60,70,80,90) # An Asterisk * is placed before the variable/argument name, # * holds the values of all the non-keyword variable arguments.
true
cfbba32a8f869a1f9afaba9381382611f70c789a
MompuPupu/ProjectEuler
/Problems 1 - 10/Problem 1.py
516
4.5
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. def determine_if_multiple_of_3_or_5(number): """Return whether the number is a multiple of 3 or 5. """ if number % 3 == 0 or number % 5 == 0: return True else: return False if __name__ == '__main__': total = 0 for i in range(1, 1000): if determine_if_multiple_of_3_or_5(i): total = total + i print(total)
true
ffd4583fc2f7498e36d5f9bd8fa7162c08295439
MompuPupu/ProjectEuler
/Problems 1 - 10/Problem 4.py
1,154
4.34375
4
# A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers # is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. import math def check_for_palindrome(num): # loads the number into an array of characters digit_list = [int(x) for x in str(num)] # iterates through the array, checking if the first is the same as the last, etc. for i in range(1, math.floor(len(digit_list) / 2) + 1): if digit_list[i - 1] != digit_list[-i]: return False print(digit_list) return True def check_if_multiple_of_three_digits(num): for i in range(999, 99, -1): if num % i == 0: other_factor = num / i if other_factor > 99 and other_factor < 1000: return True return False if __name__ == "__main__": test_number = 998001 solution_found = False # 100 * 100 to 999 * 999 = 10,000 to 998,001 while not solution_found: if check_for_palindrome(test_number): if check_if_multiple_of_three_digits(test_number): solution = test_number solution_found = True else: test_number -= 1 else: test_number -= 1 print(solution)
true
ee164fea12b17eb34cf532481c77e93bd91a2313
nda11/CS0008-f2016
/ch5/ch5,ex3.py
1,064
4.375
4
# name : Nabil Alhassani # email : nda11@pitt.edu # date :septemper/11th # class : CS0008-f2016 # instructor : Max Novelli (man8@pitt.edu) # Description:Starting with Python, Chapter 2, # Notes: # any notes to the instructor and/or TA goes here # ...and now let's program with Python # exercise 3 # Many financial experts advise that property owners should insure # their homes or buildings for at least 80 percent of the amount # it would cost to replace the structure. Write a program that # asks the user to enter the replacement cost of a building and # then displays the minimum amount of insurance he or she should # buy for the property. def main(): # Ask for the replacement cost of the insured building. replacement_cost = input('Enter the replacement cost of the building: ') replace(replacement_cost) def replace(replacement_cost): # Find what 80% of the value is. insurance_value = replacement_cost * 0.8 # State what the minimum insurance needed is. print 'The minimum amount of insurance you need is $%.2f' % insurance_value, ' dollars.' main()
true
81d1b25c60fd7043a49fb43f2cb4c808c4d21a86
nda11/CS0008-f2016
/ch2.py/ch2-ex3 bis.py
442
4.25
4
# Exercise : ch2-ex3 #This program asks the user to enter the total square meters of land and calculates the number of #acres in the tract. #set one_acre value and one_acre= 4,046.8564224**2 one_square_meter= 0.000247105 #input square_meter square_meter=float(input('enter the total square meters:',)) # calculation the acre in the tract. acre=square_meter * one_square_meter # Display the total acre print("this is the total acre:",acre)
true
2f3cf52da18ad63dcd6a9cec6710b3b1b15f1e9f
Victor-Bonnin/git-tutorial-rattrapages
/guessing_game.py
1,300
4.375
4
#! /usr/bin/python3 # The random package is needed to choose a random number import random # Define the game in a function def guess_loop(): # This is the number the user will have to guess, chosen randomly in between 1 and 100 number_to_guess = random.randint(1, 100) name = input("Write your name: ") print("I have in mind a number in between 1 and 100, can you find it?") # Replay the question until the user finds the correct number while True: try: # Read the number the user inputs guess = int(input()) # Compare it to the number to guess if guess > number_to_guess: print("The number to guess is lower") elif guess < number_to_guess: print("The number to guess is higher") else: # The user found the number to guess, let's exit print("You just found the number, it was indeed", guess) print("You won, well done", name ) return # A ValueError is raised by the int() function if the user inputs something else than a number except ValueError as err: print("Invalid input, please enter an integer") # Launch the game guess_loop()
true
3759e1450a801809bb2b00bcbf17d8ab474054a4
nagalr/algo_practice
/src/main/Python/Sort/insertion_sort.py
565
4.15625
4
def insertion_sort(l): """ Insertion Sort Implementation. Time O(n^2) run. O(1) space complexity. :param l: List :return: None, orders in place. """ # finds the next item to insert for i in range(1, len(l)): if l[i] < l[i - 1]: item = l[i] # moves the item to its right location for j in range(i, 0, -1): if item < l[j - 1]: l[j], l[j - 1] = l[j - 1], l[j] l = [2, 1, 1, -10, 10, -1, 0, 11, -1, 111, -111, -1, 0, 1000] insertion_sort(l) print(l)
true
15e3ed05dc5919e6a86fe26cd62e6fff05e65209
wulfebw/algorithms
/scripts/probability_statistics/biased_random.py
2,057
4.25
4
""" :keywords: probability, biased, random """ import random def biased_random(p=.1): """ :description: returns 1 with p probability and 0 o/w """ if random.random() < p: return 1 return 0 def unbiased_random(): """ :description: uses a biased random sampling with unknown bias to achieve an unbiased sampling :time: average case O(1/(p * (1-p))) - the probability that the while loop stops is the same as the probability that one variable is 0 and the other 1. This is equal to p * (1-p). So the expected run time is the number of coin flips with heads probability p * (1-p) until you get a heads. This is the binomial distribution with expected value 1/probability heads, which in this case is 1/(.1 * .9) = 1/.09 = 11.1. Which is actually wrong, it should be either p(1-p) or (1-p)p, doubling the probability of leaving the loop, therefore this should be O(2/(p * (1-p))), which actually should be O(1/p) :space: O(1) """ x = y = 0 counter = 0 while x == y: counter += 1 x = biased_random() y = biased_random() return x, counter if __name__ == '__main__': runs = 10000 total = 0 total_counter = 0 for i in range(runs): cur_total, cur_counter = unbiased_random() total += cur_total total_counter += cur_counter avg = total / float(runs) avg_counter = total_counter / float(runs) print 'average value and counter after {} runs: {}\t counter: {}'.format(runs, avg, avg_counter) """ :additional notes: to get an unbiased estimator from a biased estimator, or generally to undue some sampling bias, find two secondary random variables that combine earlier ones and then decide between them equally - how do you decide between them equally? - so event a is you flip two coins, one is heads the other is tails - event b is you flip two coins one is tails the other is heads - now just decide between these two equally by randomly choosing the first coin when the two coins are different """
true
914c9007a4dbf898d7d84bcdf477dc00b5a43d89
JingYiTeo/Python-Practical-2
/Q08_top2_scores.py
567
4.15625
4
NStudents = int(input("Please Enter Number of Students: ")) Names = [] Scores = [] for i in range(NStudents): Name = str(input("Please enter Name: ")) Score = int(input("Please enter Score: ")) Names.append(Name) Scores.append(Score) Scores, Names = (list(t) for t in zip(*sorted(zip(Scores, Names)))) print("{} with {} marks has the highest score.\n {} with {} marks has the second highest score.".format(Names[len(Names)-1], Scores[len(Scores)-1], Names[len(Names)-2], Scores[len(Scores)-2]))
true
ab7a5601210b13fd049b859d96aa0e25c1f6df0e
Soreasan/Python
/MoreList.py
1,135
4.4375
4
#!/usr/bin/env python3 #We can create a list from a string using the split() method w = "the quick brown fox jumps over the lazy dog".split() print(w) #We can search for a value like this which returns the index it's at i = w.index('fox') print(i) print(w[i]) #w.index('unicorn') #Error #You can check for membership with the 'in' and 'not in' keywords print(37 in [1, 78, 9, 37, 34, 53]) print(78 not in [1, 78, 9, 37, 34, 53]) #Create a new list u = "jackdaws love my big sphinx of quarts".split() print(u) #We can delete from a list by index del u[3] print(u) #We can also delete from a list by value u.remove('jackdaws') print(u) #Trying to delete an item that isn't there causes a ValueError #u.remove('pyramid') #New list... a = "I accidentally the whole universe".split() print(a) #We can insert by index a.insert(2, "destroyed") print(a) #we can combine the list into a word again using a space join operator words = ' '.join(a) print(words) #You can concatenate a list with the following syntaxes: m = [2, 1, 3] print(m) n = [4, 7, 11] print(n) k = m + n print(k) k += [18, 29, 47] print(k) k.extend([76, 129, 199]) print(k)
true
e6b4587b69e39a7e1bdbeb7befc1cd064ef1cb35
Ankitpahuja/LearnPython3.6
/Lab Assignments/Lab06 - Comprehensions,Zip/Q1.py
886
4.75
5
# Create a text file containing lot of numbers in float form. The numbers may be on separate lines and there may be several numbers on same line as well. We have to read this file, and generate a list by comprehension that contains all the float values as elements. After the data has been loaded, display the total number of values and the maximum/minimum and average values. #Next is a multi-line comment. #Step1: Write your logic """fp = open("float.txt","r") for line in fp: print(line)""" #Step2: Reducing the lines (removing objects and calling them directly as;) """ for line in open("float.txt"): print(line) """ #Step3: Writing the comprehension! L = [float(line) for line in open("float.txt","r")] print(len(L)) print("Maximum value is: ",max(L)) print("Minimum value is: ",min(L)) print("Average is: ",sum(L)/len(L)) # End of the Program!
true
6486f929c5adccc0980dc26db652e9358c001754
Ankitpahuja/LearnPython3.6
/Lab Assignments/Lab05 - RegEX/ppt_assignment.py
673
4.3125
4
''' Write a function that would validate an enrolment number. valid=validateEnrolment(eno ) Example enrolment number U101113FCS498 U-1011-13-F-CS-498 13 – is the year of registration, can be between 00 to 99 CS, EC or BT Last 3 are digits ''' import re pattern = re.compile("U1011[0-9][0-9]F(CS|BT)\d\d\d") def enroll(eno): found = pattern.search(eno) if found: return True else: return False # Main Program Proceeds eno = input("Enter Enrollment number: (I will tell if it exists or not!)\n") n = enroll(eno) if n: print("Yes, It's a valid E NO. and it exists!") else: print("No. Isn't a valid E No.")
true
76e97fc42db60802575bb4b9be80a7499298d26e
Ankitpahuja/LearnPython3.6
/Tutorials - Examples/GUI - Tkinter/boilerplate.py
1,170
4.4375
4
import tkinter as tk window = tk.Tk() window.title("Tkinter's Tutorial") window.geometry("550x400") # Label title = tk.Label(text="Hello World. Welcome to tkinter's tutorial!", font=("Times New Roman",20)) title.grid(column=0,row=0) #Button1 button1 = tk.Button(text="Click Me!", bg="red") button1.grid(column=0,row=1) #Entry Field entry_field1 = tk.Entry() entry_field1.grid(column=0, row=2) #Text Field text_field = tk.Text(master=window, height=10, width=30) text_field.grid() # mainloop() fundtion called with windows; it runs everything inside that window. Make sure this function is at the last. window.mainloop() ''' Following are the steps you need to follow in ordert to build an app using tkinter: 0. Plan out layout of app 1. Create a window for the app (Add title and geometry) 2. Declare Size, Place labels, buttons, entry fields etc. on the window (Use grids to place them!) 3. Place Labels, buttons, entry fields, onto the window! 4. Connect buttons/entries to one another through functions 5. Use .mainloop() to run the window! ''' ''' More resources can be found at: http://effbot.org/tkinterbook/ '''
true
dfe339423b83149a43710cbf6eef8ad51cb9c1e9
pavanvittanala/Coding_programs
/uniformity.py
1,475
4.15625
4
''' ----->>>>> PROBLEM STATEMENT <<<<<----- ''' ''' You are given a string that is formed from only three characters ‘a’, ‘b’, ‘c’. You are allowed to change atmost ‘k’ characters in the given string while attempting to optimize the uniformity index. Note : The uniformity index of a string is defined by the maximum length of the substring that contains same character in it. Input The first line of input contains two integers n (the size of string) and k. The next line contains a string of length n. Output A single integer denoting the maximum uniformity index that can be achieved. Constraints 1 <= n <= 10^6 0 <= k <= n String contains only ‘a’, ‘b’, ‘c’. Sample Input 0 6 3 abaccc Sample Output 0 6 Explanation First 3 letters can be changed to ‘c’ and we can get the string ‘cccccc’ ''' ''' ----->>>>> SOLUTION: <<<<<---- ''' n,k=map(int,input("\n 6 3").split()) st=input("Enter a string:") c1,c2,c3=st.count("a"),st.count("b"),st.count("c") if c1 <=c2: if c2<=c3 and c1+c2 <=k: st=st.replace("a","c") st=st.replace("b","c") elif c2>c3 and c1+c3<=k: st=st.replace("a","b") st=st.replace("c","b") else: print("K is Wrong, for given input") elif c1 <= c3: st=st.replace("a","c") st=st.replace("b","c") else: st=st.replace("b","a") st=st.replace("c","a") print("Final String :",st)
true
eccaf13f1f46e435b9547ecffe26c55e63108852
atseng202/ic_problems
/queues_and_stacks/queue_with_two_stacks/queue_two_stacks.py
1,371
4.125
4
class Stack(object): def __init__(self): # """Initialize an empty stack""" self.items = [] def push(self, item): # """Push a new item onto the stack""" self.items.append(item) def pop(self): # """Remove and return the last item""" # If the stack is empty, return None # (it would also be reasonable to throw an exception) if not self.items: return None return self.items.pop() def peek(self): # """Return the last item without removing it""" if not self.items: return None return self.items[-1] class QueueTwoStacks(object): # Implement the enqueue and dequeue methods def __init__(self): # Enqueue and dequeue using two stacks self.push_stack = Stack() self.pop_stack = Stack() def enqueue(self, item): # if the push stack has any items, then enqueue onto it # if self.push_stack.peek(): self.push_stack.push(item) def dequeue(self): if not self.push_stack.peek() and not self.pop_stack.peek(): raise ValueError("Cannot dequeue from empty queue") if self.pop_stack.peek(): first_item = self.pop_stack.pop() return first_item else: # nothing in the pop_stack so we need to look into push stack if not self.push_stack.peek(): return None while self.push_stack.peek(): item_to_move = self.push_stack.pop() self.pop_stack.push(item_to_move) return self.pop_stack.pop()
true