blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
75c6b0414fa68565cf96be70507f89172ca59e42
ILA-J/Ch.03_Input_Output
/3.0_Jedi_Training.py
1,544
4.5
4
# Sign your name: Lalrinpuia Hmar # In all the short programs below, do a good job communicating with your end user! # 1.) Write a program that asks someone for their name and then prints a greeting that uses their name. name = input("What's your name?") print("Hey", name, "have a good day") # 2. Write a program where a user enters a base and height and you print the area of a triangle. base_Triangle = int(input("What is the base of the triangle: ")) height_Triangle = int(input("What is the height of the triangle: ")) area_Triangle = (base_Triangle*height_Triangle)/2 print("The area of the triangle is:", area_Triangle) # 3. Write a line of code that will ask the user for the radius of a circle and then prints the circumference. radius = int(input("Enter the radius of the circle: ")) circumference = radius*2 print("The circumference of the circle is:", circumference) # 4. Ask a user for an integer and then print the square root. inteGER = int(input("Enter an")) squareRoot = sqrt(inteGER) print("The square root of the integer is:", squareRoot) '''So I searched and found out that you have to do "import math" first.''' # 5. Good Star Wars joke: "May the mass times acceleration be with you!" because F=ma. # Ask the user for mass and acceleration and then print out the Force on one line and "Get it?" on the next. print("May the mass times acceleration be with you!") mass = float(input("Enter mass: ")) acceleration = float(input("Enter acceleration: ")) force = mass*acceleration print("The force is", force) print("Get it?")
true
b65fbddb8a6b4ecaffb48c552ef772733620bd15
pauldedward/100-Days-of-Code
/Day 4/rockPapSi.py
1,203
4.15625
4
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' gameChoices = [rock, paper, scissors] userChoice = int(input("Enter your choice: 1. Rock, 2. Paper, 3. Scissors\n")) compChoice = random.randint(1, 3) if userChoice == compChoice: winner = "nobody" elif userChoice > compChoice: if (userChoice - compChoice) == 1: winner = "player" else: winner = "computer" elif compChoice > userChoice: if (compChoice - userChoice) == 1: winner = "computer" else: winner = "player" if userChoice >= 1 and userChoice <= 3: print("\nComputer chose :\n") print(gameChoices[compChoice - 1]) print("\nYou chose :\n") print(gameChoices[userChoice - 1]) if winner == "nobody": print("\nIt's a tie!") elif winner == "player": print("\nYou won!") elif winner == "computer": print("\nYou lost!") else: print("\nInvalid choice!")
false
e8773df8db3c1dba765b7673c600dc0687cc8388
Raghibshams456/Python_building_blocks
/Numpy_worked_examples/037_numpy_enumerate.py
558
4.125
4
""" What is the equivalent of enumerate for numpy arrays """ import numpy as np Z = np.arange(9).reshape(3,3) for index, value in np.ndenumerate(Z): print(index, value) for index in np.ndindex(Z.shape): print(index, Z[index]) """ PS C:\Users\SP\Desktop\DiveintoData\Numpy> python .\037_numpy_enumerate.py (0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) 3 (1, 1) 4 (1, 2) 5 (2, 0) 6 (2, 1) 7 (2, 2) 8 (0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) 3 (1, 1) 4 (1, 2) 5 (2, 0) 6 (2, 1) 7 (2, 2) 8 PS C:\Users\SP\Desktop\DiveintoData\Numpy> """
false
dd53151f7e019382d9be4866ed0698179381b87a
zzboss/learn
/python/practice/reverseString.py
230
4.375
4
# reverse a character string. ep: 'hello world' -> 'world hello' def reverseString(s): arr = s.split(' ') arr.reverse() return ' '.join(arr) print(reverseString('hello world')) print(reverseString('1 2 3 4 5 6 7'))
false
18a4a0d7f7a98d075b686c46d0d711d955c3fdc8
t0ri-make-school-coursework/cracking-the-coding-interview
/trees-and-graphs/list_of_depths.py
1,417
4.28125
4
from minimal_tree import min_tree from Node import LinkedListNode, TreeNode from LinkedList import LinkedList # 4.3 # List of Depths # Given a binary tree, design an algorithm which creates a linked list of all the # nodes at each depth (eg you have a tree with depth D, you'll have D linked lists) # loop through depths # at each depth, create a linked list # for each node in depth # append a node to the linked list def find_depth(node): # base cases # if tree has no nodes if node is None: return 0 # if root has no children if node.left is None and node.right is None: return 1 # tree has many nodes else: # recursively find the depth of branches of tree left_depth = find_depth(node.left) + 1 right_depth = find_depth(node.right) + 1 # return the larger depth if left_depth > right_depth: return left_depth else: return right_depth def list_depths(node, linked_lists=None, depth=None): # if empty tree passed in if node is None: return list() # or None # if no depth yet if depth is None: depth = find_depth(root) # if no lists yet if linked_lists is None: linked_lists = [LinkedList()] * depth if __name__ == "__main__": root = min_tree([1,2,3,4,5,6,7,8,9,10,11,12]) print(find_depth(root)) list_depths(root)
true
545a1568b689332d2c547ca6a35525196fd78c34
Dsbaule/INE5452
/Simulado 01 (Novo)/BucketSort/__main__.py
1,161
4.34375
4
""" Autor: Daniel de Souza Baulé (16200639) Disciplina: INE5452 - Topicos Especiais em Algoritmos II Atividade: Primeiro simulado - Questoes extra-URI Pontos resolvidos: 1. 1 simbolo; 2. k símbolos; e 3. qualquer quantidade de símbolos Devido a utilização da linguagem python, o número de caracteres da entrada não afeta a execução do código, mas devido ao enunciado, foi adicionada uma validação adicional da entrada, levantando uma exceção no caso de entrada invalida. """ from BucketSort.src.BucketSort import bucket_sort def main(): # Get input n, k = input().split() input_list = input().split() # Check if input is correct length if len(input_list) != int(n): raise Exception("Invalid input") # Check if input is valid if k != 'x': k = int(k) for element in input_list: if len(element) != k: raise Exception("Invalid input") # Sort input sorted_list = bucket_sort(input_list) # Format output output = "" for element in sorted_list: output += str(element) + " " output = output[:-1] # Print print(output) main()
false
b9bf1276904bf873bc35baa6d255766d7d2b6264
atharva07/python-files
/concat_matrix.py
599
4.15625
4
# two matrix of size M and N M = 2 N = 2 def mergeMatrix(A,B): C = [[0 for j in range(2*N)] for i in range(M)] # merge two matrices for i in range(M): for j in range(N): # to store the elements of matrix A C[i][j] = A[i][j] # to store the elements of matrix B C[i][j+N] = B[i][j] for i in range(M): for j in range(2 * N): print(C[i][j], end = ' ') print() # Driver code if __name__ == '__main__': A = [[1,2],[3,4]] B = [[5,6],[7,8]] mergeMatrix(A,B)
false
a9bfe1ef788b21c4dc4d2b33a3eb3dec2e08e7fb
atharva07/python-files
/Numbers.py
883
4.28125
4
print(2) # the basic of numbers # print(3 + 5) # addition in numbers # print(4 * 5 + 6) # fisrt multiply then add the result with 6 # print(4 * (5 + 6)) # now add the 5 and 6 then multiply # my_num = 5 print(str(my_num) + " is my favourite number") # use of functions in math # my_num = 44 print(abs(my_num)) # this functn is an absolute value # print(pow(4,5)) # this is a power function print(max(4, 7)) # tells which is bigger number print(min(6, 8)) # tells which is smaller number print(round(5.1)) # rounds up to 5 with decimal being less than 5 print(round(5.7)) # rounds up to 6 with decimal being greater than 5 from math import * # this will import bunch of different math functions my_num = 55 print(floor(3.6)) # this function will chop off decimal point print(ceil(3.7)) # this will return the complete number print(sqrt(44)) # returns the square root of number
true
fd170f76440b0169407e2ab8364021359611eca2
atharva07/python-files
/If-statement.py
552
4.1875
4
is_male = True if is_male: print("You are awesome") else: print("You are beautiful") # making it little complex is_captain = True is_worthy = False if is_captain or is_worthy: # OR condition is applied print("You are captain america") else: print("you are just an ordinary man") if is_captain and is_worthy: # AND condition is applied print("You are captain america") elif is_captain and not(is_worthy): # not function negates the parameter print("You are half captain") else: print("You are just an ordinary man")
true
1b045ea6cd2f0aa0f2ee4a93a8cdab4bd4b740b0
wimarbueno/python3-course
/course/functions/functions/functions.py
1,012
4.28125
4
# consider identation def nothing(): pass # the string is called, "docstring" def my_function(param1, param2): """This functions print params""" print param1 print param2 my_function('Hello', "World") # to indicate the params my_function(param2 = "World", param1="Hello") # To Assign default values def myPrinter(text, times = 1): print text * times myPrinter("Hi") myPrinter("Hi", 6) # To defie multiple params def my_multiple(param1, param2, *others): for val in others: print val my_multiple(1,2) my_multiple(1,2,3) my_multiple(1,2,3,4) # to return a value def sum(x, y): return x + y print sum(2,3) # we can pass return multiple values # but the true is that python create a tuple an return just a single tuple def f(x, y): return x * 2, y *2 a, b = f(2,3) print a print b # integers are inmutable def addOneToNum(num): num = num + 1 print('Value inside function: ', num) return num = 5 addOneToNum(num) print('Value outside function: ', num)
true
5b843d88bf439a3b96bfd7b7e7edbec32de6800c
fipl-hse/2019-2-level-labs
/lab_1/main.py
2,352
4.15625
4
""" Labour work #1 Count frequencies dictionary by the given arbitrary text """ def calculate_frequences(text: str) -> dict: """ Calculates number of times each word appears in the text """ frequencies = {} new_text = '' if text is None: return frequencies if not isinstance(text, str): text = str(text) for symbol in text: if symbol.isalpha() or symbol == ' ': new_text += symbol new_text = new_text.lower() words = new_text.split() for key in words: key = key.lower() if key in frequencies: value = frequencies[key] frequencies[key] = value + 1 else: frequencies[key] = 1 return frequencies def filter_stop_words(frequencies: dict, stop_words: tuple) -> dict: """ Removes all stop words from the given frequencies dictionary """ if frequencies is None: frequencies = {} return frequencies for word in list(frequencies): if not isinstance(word, str): del frequencies[word] if not isinstance(stop_words, tuple): return frequencies for word in stop_words: if not isinstance(word, str): continue if frequencies.get(word) is not None: del frequencies[word] return frequencies def get_top_n(frequencies: dict, top_n: int) -> tuple: """ Takes first N popular words :param """ if not isinstance(top_n, int): frequencies = () return frequencies if top_n < 0: top_n = 0 elif top_n > len(frequencies): top_n = len(frequencies) top_words = sorted(frequencies, key=lambda x: int(frequencies[x]), reverse=True) best = tuple(top_words[:top_n]) return best def read_from_file(path_to_file: str, lines_limit: int) -> str: """ Read text from file """ file = open(path_to_file) counter = 0 text = '' if file is None: return text for line in file: text += line counter += 1 if counter == lines_limit: break file.close() return text def write_to_file(path_to_file: str, content: tuple): """ Creates new file """ file = open(path_to_file, 'w') for i in content: file.write(i) file.write('\n') file.close()
true
c3399773b1858e4faca2d1f215ff9fbdae6c0134
kazanture/leetcode_tdd
/leetcode_tdd/zig_zag_conversion.py
925
4.125
4
""" https://leetcode.com/problems/zigzag-conversion/submissions/ The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); """ class ZigZagConversion: def convert(self, input_str, num_rows): row = 0 inc = 1 res = [""] * num_rows for i in range(len(input_str)): if row == num_rows - 1: inc = -1 if row == 0: inc = 1 res[row] += input_str[i] if num_rows > 1: row += inc res_str = "" for row in res: res_str += row return res_str
true
a0a6aa455842e11ae2d9b9126d1999ba71d2b8f8
stanleychow/madlibs
/mad_libs.py
1,116
4.25
4
adj_list = [] adj_1 = input(str("Type an adjective: ")) adj_2 = input(str("Type another adjective: ")) adj_3 = input(str("Another Adjective! ")) adj_list.append(adj_1) adj_list.append(adj_2) adj_list.append(adj_3) noun_list = [] noun_1 = input(str("Type a noun: ")) noun_2 = input(str("Type another noun: ")) noun_3 = input(str("Another noun: ")) noun_4 = input(str("A fourth noun!")) noun_5 = input(str("Noun!")) noun_list.append(noun_1) noun_list.append(noun_2) noun_list.append(noun_3) noun_list.append(noun_4) noun_list.append(noun_5) verb_list = [] verb = input(str("Type a verb: ")) verb_2 = input(str("And a Final Verb!")) verb_list.append(verb) verb_list.append(verb_2) Result = "There was once a " + noun_list[0] + " and their pet " + adj_list[0] + " " + noun_list[1] + ". They woke up one morning to find out a " + adj_list[1] + " " + noun_list[2] + " had " + verb_list[0] + " all over their " + noun_list[3] + ". In response, they took out their trusty " + adj_list[2] + " " + noun_list[4] + " 3000 to " + verb_list[1] + " it up!" print(Result) print(Result) print(Result) print(Result)
false
d1e269aeb3fb308ad35c7aafff644648bb418c86
Prashant-Bharaj/A-December-of-Algorithms
/December-04/python_nivethitharajendran_4fibanocci.py.py
352
4.25
4
#getting a number from the user n=int(input("Enter the nth number:")) #function definition def fibo(num): if num ==0: return 0 elif num==1: return 1 else: #calling recursively return fibo(num-1)+fibo(num-2) #function call x=fibo(n) #displaying the output print("The",n,"th element is ",x)
true
938864c21ad2e268585d88a5c75c0b0d66a7faac
Prashant-Bharaj/A-December-of-Algorithms
/December-12/py_imhphari.py
891
4.125
4
class Node: def __init__(self, data): self.data= data self.next= None class LinkedList: def __init__(self): self.head=None def reverse(self): prev=None current=self.head while(current is not None): next=current.next current.next=prev prev=current current=next self.head=prev def push(self,new_data): new_node=Node(new_data) new_node.next=self.head self.head=new_node def printList(self): temp=self.head while(temp): print(temp.data) temp=temp.next llist = LinkedList() llist.push(889) llist.push(23) llist.push(34) llist.push(20) llist.push(10) print ("Given Linked List") llist.printList() llist.reverse() print ("\nReversed Linked List") llist.printList()
true
5908d9cfdadde2a35e23718151ddb3e6f997f129
mykhamill/Projects-Solutions
/solutions/fib.py
773
4.53125
5
# Generate the Fibonacci sequence up to term N from sys import argv def fib(m, n = None, cache = None): if n is None: i = 2 else: i = n if cache is None: cache = (0, 1) if i > 0: i -= 2 while i > 0: cache = (cache[1], sum(cache)) i -= 1 while m >= 0: n_1 = sum(cache) print n, n_1, cache if i == 0: print i += 1 cache = (cache[1], n_1) m -= 1 n += 1 def main(): if len(argv) == 2: fib(int(argv[1])) elif len(argv) == 3: fib(int(argv[1]), int(argv[2])) else: print """Usage: python fib.py <M> [<N>] Where <M> is the number of terms to show in the fibonacci sequence Where <N> is the first term to start showing from""" return if __name__ == "__main__": main()
true
53149d88b19452c9a37d3e836355277253df2727
HarshadGare/Python-Programming
/Control Statements/03 For Loop.py
332
4.21875
4
for x in range(5): # range(stop) print(x) for x in range(4, 9): # range(start, stop) print(x) for x in range(1, 15, 2): # range(start, stop, step) print(x) for a in [2, 4, 3, 7, 8]: print(a) # for Loop with Else part for x in range(5): # range(stop) print(x) else: print("Value of x is Exceed")
false
e593e56d1a1b4d53dec06686bf65948e73cf83bb
mca-pradeep/python
/arrays.py
1,050
4.34375
4
#Array is the special variable which can hold more than one value at a time #Python has no built in support for arrays. Python lists are used for this purpose instead arr = [1,3,5,7, 'test', 'test1'] print(arr) print('---------------') print('Finding Length') print(len(arr)) print('---------------') print('remove all elements from array we use "clear" function') arr.clear() print(arr) print('---------------') print('Add an element in the end of the array we use "append" function') arr.append(2) print(arr) print('---------------') print('to return a copy of a list we use "copy" function') arr1 = arr.copy() print(arr1) print('---------------') print('to return a number of elements with specified value we use "count" function') arr1 = arr.count(2) print(arr1) print('---------------') print('Iterating Arrays') for elem in arr: print(elem) print('---------------') print('Sorting Arrays') #Sort function can be used only on the numeric indexed array numericArray = [2,88,23,5,77,33,46,24]; numericArray.sort() print(numericArray)
true
64886698b575819bc3ed87e95c9e8d80bf6c2b1a
387358/python-test
/decorator/log_decorator.py
1,482
4.21875
4
#! /usr/bin/python def logged1(func): def with_logging(*args, **kwargs): print 'func: ' + func.__name__ + ' was called' return func(*args, **kwargs) return with_logging @logged1 def f(x): print 'into f(x)' return x*x ''' above decorated func is equal to def f(x): print 'into f(x)' return x*x f = logged1(f) ''' print 'f(3)' print f(3) print def logged2(func): print 'func: ' + func.__name__ + ' was called' return func @logged2 def f2(x): print 'into f2(x)' return x*x print 'f2(3)' print f2(3) print f2(3) print f2(3) print ''' decorator function was called when the module load, not when the function was called. Thus you must warpper another function to return just like logged1, and then the wrapper function will be called every time when the wrappered function was called. Otherwise, the decorator will be called only once no matter how many times the wrappered functino was calleds, just like logged2 ''' def logged3(func): print 'input func: ' + func.__name__ def p(*args, **kwargs): print 'logged2 was called - args:', args, 'kwargs:', kwargs return p @logged3 def f3(x): print 'into f3(x)' return x*x print 'f3 call list' print f3(3, 4, a=5) print f3(3, 4, a=6) print f3(3, 4, a=7) ''' So, in the end, what the decorator acturally doing? just override the original function as the decorator function and put the original function as the arguement: f3 = logged3(f3) '''
true
8d815508fbd77ce5b53fe8a040828b67bd94ed1f
RafaRomero8/My-First-curso-in-phyton
/cadenas_platzi.py
630
4.25
4
"""nombre = input("¿cuál es tu nombre?") print(nombre.upper()) nombre2 = input("¿cuál es tu nombre?") print(nombre2.capitalize()) nombre3 = input("¿cuál es tu nombre?") print(nombre3.strip()) nombre3 = input("¿cuál es tu nombre?") print(nombre3.lower()) """ """ nombre4 = input("¿cuál es tu nombre?") print(nombre4.replace('a','o')) nombre3 = input("¿cuál es tu nombre?") print(nombre3[2]) nombre3 = input("¿cuál es tu nombre?") print(len(nombre3)) """ nombre="Rafael" print(nombre[0:3]) print(nombre[0:5:2]) print(nombre[::-1]) nombre3 = input("¿cuál es tu nombre real?") print(len(nombre3))
false
b5dee728085c62ddb5895a03fab5aecda26b88a0
deepcharles/datacamp-assignment-pandas
/pandas_questions.py
2,609
4.125
4
"""Plotting referendum results in pandas. In short, we want to make beautiful map to report results of a referendum. In some way, we would like to depict results with something similar to the maps that you can find here: https://github.com/x-datascience-datacamp/datacamp-assignment-pandas/blob/main/example_map.png To do that, you will load the data as pandas.DataFrame, merge the info and aggregate them by regions and finally plot them on a map using `geopandas`. """ import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt def load_data(): """Load data from the CSV files referundum/regions/departments.""" referendum = pd.DataFrame({}) regions = pd.DataFrame({}) departments = pd.DataFrame({}) return referendum, regions, departments def merge_regions_and_departments(regions, departments): """Merge regions and departments in one DataFrame. The columns in the final DataFrame should be: ['code_reg', 'name_reg', 'code_dep', 'name_dep'] """ return pd.DataFrame({}) def merge_referendum_and_areas(referendum, regions_and_departments): """Merge referendum and regions_and_departments in one DataFrame. You can drop the lines relative to DOM-TOM-COM departments, and the french living abroad. """ return pd.DataFrame({}) def compute_referendum_result_by_regions(referendum_and_areas): """Return a table with the absolute count for each region. The return DataFrame should be indexed by `code_reg` and have columns: ['name_reg', 'Registered', 'Abstentions', 'Null', 'Choice A', 'Choice B'] """ return pd.DataFrame({}) def plot_referendum_map(referendum_result_by_regions): """Plot a map with the results from the referendum. * Load the geographic data with geopandas from `regions.geojson`. * Merge these info into `referendum_result_by_regions`. * Use the method `GeoDataFrame.plot` to display the result map. The results should display the rate of 'Choice A' over all expressed ballots. * Return a gpd.GeoDataFrame with a column 'ratio' containing the results. """ return gpd.GeoDataFrame({}) if __name__ == "__main__": referendum, df_reg, df_dep = load_data() regions_and_departments = merge_regions_and_departments( df_reg, df_dep ) referendum_and_areas = merge_referendum_and_areas( referendum, regions_and_departments ) referendum_results = compute_referendum_result_by_regions( referendum_and_areas ) print(referendum_results) plot_referendum_map(referendum_results) plt.show()
true
b6b8885bd92f07cc5b18af35ed0339e2e0db155b
akahrsp/Acadview_MMU
/Examples/prime.py
295
4.125
4
def get_number() : return int(raw_input("Enter a no to check it is prime or not ")) num = get_number() i = 1 a = 0 while (i <= num): if num % i == 0 : a += 1 i += 1 if a == 2 : print "%d is a prime number" % (num) else : print "%d is a non prime number " % (num)
false
9779a4698fab521669bf040de6515ac81fb75fea
Nordlxnder/Beispiele
/Auswertetools Index und co/Beispiel index von Elementen in einer Liste.py
904
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- a=[2,3,5,7,3,4,2,3,2,3,3,33333,"test",2] print("\nverwendete Liste:\t",a,"\n") # gibt die Position des ersten Auftretens des Elements in der Liste zurück b=a.index(3) print("Position des ersten Auftreten in der Liste:\t",b) # gibt den Index aller Positionen des Elements in der Liste an c=[index for index, v in enumerate(a) if v == 2] print("Positionen des Elements in der Liste: \t",c) # gibt dden Index aller Positionen des Elements in der Liste an d=[index for index, v in enumerate(a) if v == "test"] e=[index for index, v in enumerate(a) if v == "xyz"] print("Position des Element in der Liste:\t",d, "\tRückgabewert des Elements das nicht in der Liste ist:\t", e) # Vergleich der Elemente in der Liste #f= [i for i,wert in a: if wert >= 3] for wert in a: if wert >= 3: print(wert) #print(f) if __name__ == "__main__": pass
false
8562aa1729a642b17bb7850dcb2c889c0f3f4985
MelodyChu/Juni-Python-Practice
/insertion_sort copy.py
1,953
4.125
4
"""We begin by assuming that a list with one item (position 00) is already sorted. On each pass, one for each item 1 through n−1n−1, the current item is checked against those in the already sorted sublist. As we look back into ' the already sorted sublist, we shift those items that are greater to the right. When we reach a smaller item or the end of the sublist, the current item can be inserted. Figure 5 shows the fifth pass in detail. At this point in the algorithm, a sorted sublist of five items consisting of 17, 26, 54, 77, and 93 exists. We want to insert 31 back into the already sorted items. The first comparison against 93 causes 93 to be shifted to the right. 77 and 54 are also shifted. When the item 26 is encountered, the shifting process stops and 31 is placed in the open position. Now we have a sorted sublist of six items.""" a = [4,3,6,1] def insertion(a): # finallist = [] # container for the final list if needed interim = a[0] for i in range(1,len(a)): # run outerloop len(a)-1 times position = i print (a) while a[position]< a[position-1] and position > 0: # look at #'s up until i; make sure sorted print (position) interim = a[position-1] a[position-1] = a[position] a[position] = interim position -= 1 print (a) return a print (insertion(a)) """ 1st run: i = 1 position = 1 a[1] = 3; a[0] = 4 interim = 4 a[0] = 4 a[1] = 3 position = i-1 --> hm.. 2nd run: i = 2 position = 2 a[2] = 6 a[1] = 4 while loop doesn't execute since placement is correct 3rd run: i = 3 position = 3 a[3] = 1 a[2] = 6 while loop executes interim = 6 a[3] = 6 a[2] = 1 [3,4,1,6] (keeps going) # 1st loop: [3,4,6,1,9,10,5] swap 3 & 4 # 2nd loop: [3,4,6,1,9,10,5] 4 & 6 stay same # 3rd loop: [3,4,1,6,9,10,5] 1 needs to go to front of list # as long as a[i] - next # right outside sublist - is greater than a[j]; it can stay put
true
c8c3ac9560cc12840c45f90da5302f52ee9ac550
MelodyChu/Juni-Python-Practice
/dictionaries2.py
1,440
4.28125
4
# function that takes in a list of numbers and return a list of numbers that occurs most frequently # [1,1,2,2,3,3,4] return [1,2,3] def frequency(numbers): result = {} #use a dictionary variable = 0 for i in numbers: # think about how to store it as a data type; does it need a variable? if i not in result: result[i] = 1 else: result[i] += 1 # now for every number, we have counts of each number for x in result: # x is the key if result[x] > variable: #if the value of x is > than variable variable = result[x] #then the variable = the value, which becomes the new benchmark return result else: def multiply(numbers): # figure out highest number result = 0 new = 0 for c in numbers: if c > result: result = c for d in numbers: if d > new and d != result: new = d print (new, result) return new * result return result numbers = # {1:2, 2:2, 3:2, 4:1} # need to use pairs of data; ID's are numbers and values are how many times they appear # How many letters does it take to spell out the numbers from one to ninety nine? Don't count any spaces or hyphens. # Hint: you'll need to use a dictionary.
true
694dd67e903f7c08379d124eece6a51b171f6a32
jchan221/CIS2348_HW_1
/CIS2348_HW_1.py
936
4.4375
4
# Joshua Chan # 1588459 # Birthday Calculator current_day = int(input('What is the calendar day?')) current_month = int(input('What is the current month?')) current_year = int(input('What is the current year?')) # The three prompts above will collect the current date birth_day = int(input('What day is your birthday?')) birth_month = int(input('What month is your birthday?')) birth_year = int(input('What year were you born?')) # The three prompts above will collect the user's birthday user_age = current_year - birth_year if current_month > birth_month: print('You are', user_age, 'years old.') if current_month < birth_month: print('You are', user_age - 1, 'years old.') # Above will calculate the user's age if current_day == birth_day and current_month == birth_month: print('Happy Birthday!') print('You are', user_age, 'years old.') # Above will check if the current date is the user's birthday
true
07376ae9a68370f688e273382c2dc70f2c8e20b2
AnkitMishra19007/DS-Algo
/Searching/Binary Search/BinarySearch.py
974
4.375
4
#below is a function that iteratively performs binary search def binarySearch(arr,left,right,find): #calculating mid pointer mid= (left+right)//2 #if we found the value then just return the index if(arr[mid]==find): return mid #if the below condition occurs that means the value not found if(left==right): return -1 #if the element we are looking for is on left side if(arr[mid]>find): return binarySearch(arr,left,mid,find) #if the element that we are looking for is on the right side if(arr[mid]<find): return binarySearch(arr,mid+1,right,find) n= int(input("Enter the length of array- ")) print("Enter the values of array separated by space") #taking input from user in a single line arr= list(map(int,input().split())) find= int(input("Enter the value to search- ")) i= binarySearch(arr,0,n-1,find) if(i==-1): print("Value not found") else: print("%d was found at index %d"%(find,i))
true
a58fe8e0972658f679b4a0892427d20f4fda79a7
hannaht37/Truong_story
/evenOrOdd.py
396
4.375
4
number = int(input("Please enter a number: ")) if(number%2 == 0): print("The number you entered, " + str(number) + ", is even!") elif(number%2 == 1): print("The number you entered, " + str(number) + ", is odd.") decimal = float(input("Please enter an integer please: ")) if(decimal%2 == 0): print("You have an even number.") elif(decimal%2 == 1): print("You have an odd number.")
true
229ed74334d97ad232fcc0804203b216b3e6af44
Mschlies/00a-Practice-Expressions
/04_area_rectangle.py
732
4.28125
4
# Compute the area of a rectangle, given its width and height. # The area of a rectangle is wh, where w and h are the lengths # of its sides. Note that the multiplication operation is not # shown explicitly in this formula. This is standard practice # in mathematics, but not in programming. Write a Python statement # that calculates and prints the area in square inches of a # rectangle with sides of length 4 and 7 inches. ################################################### # Rectangle area formula # Student should enter statement on the next line. ################################################### # Expected output # Student should look at the following comments and compare to printed output. #28
true
b189ecc9cb26f14ebebaeee5ddd05ac9d9ca4376
SaltHunter/CP1404_Practicals_2020
/prac_02/exceptions.py
885
4.34375
4
""" CP1404/CP5632 - Practical Answer the following questions: 1. When will a ValueError occur? 2. When will a ZeroDivisionError occur? 3. Could you change the code to avoid the possibility of a ZeroDivisionError? """ try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) # Code Here is solution to Question 3. while denominator == 0: print("Please input a valid denominator:") denominator = int(input("Enter the denominator: ")) fraction = numerator / denominator print(fraction) except ValueError: print("Numerator and denominator must be valid numbers!") except ZeroDivisionError: print("Cannot divide by zero!") print("Finished.") # 1. Value Error occurs when you put anything which is not a integer # 2. ZeroDivisionError occurs when you put zero in the denominator # 3. Yes, you can
true
083c4285c91d40ca7641df8343e97192058a686b
SemihDurmus/Python_Helper
/2_Codes/Assignment_7_Comfortable_Words.py
861
4.21875
4
# Assignment_7_Comfortable_Words """ Task : Find out if the given word is "comfortable words" in relation to the ten-finger keyboard use. A comfortable word is a word which you can type always alternating the hand you type with (assuming you type using a Q-keyboard and use of the ten-fingers standard). The word will always be a string consisting of only letters from a to z. Write a program to returns True if it's a comfortable word or False otherwise. """ left_letters = set("qazwsxedcrfvtgb") right_letters = set("yhnujmikolp") given_str = input("Enter a word: ") given_str_set = set(given_str) left_check = bool(given_str_set - left_letters) right_check = bool(given_str_set - right_letters) check = left_check and right_check print(check * f"\"{given_str}\" is a comfortable word") print((not check) * f"\"{given_str}\" is not a comfortable word")
true
0e41edbad5f423baa14a673eea6030cbcab74dcc
SemihDurmus/Python_Helper
/2_Codes/Assignment_2_Covid_19_Possibility.py
926
4.21875
4
# Assignment_2_Covid_19_Possibility """ Task : Estimating the risk of death from coronavirus. Consider the following questions in terms of True/False regarding someone else. Are you a cigarette addict older than 75 years old? Variable → age Do you have a severe chronic disease? Variable → chronic Is your immune system too weak? Variable → immune Set a logical algorithm using boolean logic operators (and/or) and the given variables in order to give us True (there is a risk of death) or False (there is not a risk of death) as a result. """ print("Estimating the risk of death from coronavirus.") age = False print("You are over 75 :", age) chronic = False print("You have chronic diseases :", chronic) immune = False print("Your immune system is weak:", immune, "\n") risk = age or chronic or immune print(risk * "You have high risk of death") print((not risk) * "You are not in danger")
true
d88b67bba27bc94eeb35c9478ebfd9627d36d553
Aksid83/crckng_cdng_ntrvw
/factorial_with_recursion.py
257
4.4375
4
""" Calculate factorial of the given number using recursion """ def factorial_recursion(num): if num < 0: return -1 elif num == 0: return 1 else: return num * factorial_recursion(num - 1) print factorial_recursion(6)
true
d595b75b703f329d87dd40c068631e43a88f1b56
khushi3030/Master-PyAlgo
/Topic Wise Questions with Solutions/Array/Longest_Consecutive_Subsequence.py
1,248
4.125
4
""" Given an array of positive integers. Find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order. """ def LargeSubseq(A): # Create a set to remove the duplicacy S = set(A) # initialize result by 1 maxlength = 1 # Iterate over each element for i in A: # Check the previous element `i-1` exist in the set or not if (i - 1) not in S: # `len` stores the length of subsequence, starting with the current element len = 1 # checking the element subsequence while (i + len) in S: len += 1 # update result with the length of current consecutive subsequence maxlength = max(maxlength, len) return maxlength #Driver Code if __name__ == '__main__': arr=list(map(int,input("Enter the numbers: ").split())) print("The length of the maximum consecutive subsequence is:",LargeSubseq(arr)) ''' Sample Input: Enter the numbers: 6 4 7 9 1 3 2 4 Sample Output: The length of the maximum consecutive subsequence is: 4 Time complexity= O(n) Space complexity=O(n) '''
true
b61bbac8451374a2539983c0dd842a1c005abe12
khushi3030/Master-PyAlgo
/Topic Wise Questions with Solutions/Linked List/reverse_of_ll_recursive.py
1,835
4.4375
4
""" The Program is to reverse a linked list using recursion """ class Node: #node creation def __init__(self, data): self.data = data self.next = None class linkedlist: #intially node head is pointing to null def __init__(self): self.head = None def _reverse(self, previous, current): #recursive call if current is None: #if present node is null then head will point to previous node self.head = previous else: self._reverse(current, current.next) #else it will call the function again and again until it reaches the termination condition current.next = previous def reverse(self): self._reverse(None, self.head) def insert(self, data): #pushing the data back inito linked list new_node = Node(data) new_node.next = self.head self.head = new_node def LLprint(self): #print the list current = self.head reverselist = [] while current: reverselist.append(current.data) #appending the value to the list from backside current = current.next return reverselist LL = linkedlist() print("Enter the size of ll: ") n = int(input()) print("Enter the values of of Linked List: ") for i in range(0,n): LL.insert(input()) print("The original Linked List is:") print(LL.LLprint()) print("The reverse Linked List using iterative approach:") LL.reverse() print(LL.LLprint()) """ enter n value = 3 enter values = 0 1 2 original ll = 0 1 2 reversed = 2 1 0 enter n value = 5 enter values = 10 32 12 34 56 original ll = 10 32 12 34 56 reversed = 56 34 12 32 10 """
true
6d93e6004586628e4ee20329184bad55c282237d
khushi3030/Master-PyAlgo
/String/Word_Score.py
1,663
4.1875
4
''' Aim: The score of a single word is 2 if the word contains an even number of vowels. Otherwise, the score of this word is 1. The score for the whole list of words is the sum of scores of all words in the list. The aim is to output this score for the entered string. ''' # function to check for vowels def is_vowel(letter): return letter in ['a', 'e', 'i', 'o', 'u'] # function to calculate score of the string def score_words(words): # initializing the score to 0 score = 0 for word in words: # initializing the number of vowels to 0 num_vowels = 0 for letter in word: # if found a vowel, increment the counter if is_vowel(letter): num_vowels += 1 # if the total number of vowels is even, then score should increment by 2 if num_vowels % 2 == 0: score += 2 # if the total number of vowels is odd, then score should increment by 1 else: score +=1 # printing out the final score return score # getting the total word count of the string as input n = int(input()) # splitting the string into words words = input().split() # calling function to compute the score print(score_words(words)) ''' COMPLEXITY: Time Complexity -> O(N^2) Space Complexity -> O(N) Sample Input: 3 all the best Sample Output: 3 Explanation: Total number of words --> all, the, best [3] vowel count in 'all' --> 1, hence, score = 1 vowel count in 'the' --> 1, hence, score = 1 vowel count in 'best' --> 1, hence, score = 1 Total score = 1 + 1 + 1 = 3. '''
true
d4153e59967bd769928cb12087c51cfcc28fab2e
jlrobbins/class-work
/gradecom.py
875
4.25
4
def computegrade (fruit): if fruit < 0: return('Oops! That number was too small. I need something between 0.0 and 1.0, please.') elif fruit > 1: return('Oops! That number was too big. I need something between 0.0 and 1.0, please.') elif fruit == 1: return ('Your letter grade is: A') elif fruit >= 0.9: return ('Your letter grade is: A') elif fruit >= 0.8: return ('Your letter grade is: B') elif fruit >= 0.7: return ('Your letter grade is: C') elif fruit >= 0.6: return ('Your letter grade is: D') elif fruit < 0.6: return ('Your letter grade is: F') try: numb = float(input('Enter a number between 0.0 and 1.0 to receive a letter grade: ')) grade = computegrade(numb) print(grade) except: print("I can't convert that, friend. Are you sure you typed a number?")
true
573f9abbef5b681e73206a4ca0d063667f9cab81
jlrobbins/class-work
/paydif.py
266
4.15625
4
hours = float(input('Enter Hours: ')) rate = float(input('Enter Rate: ')) overtime = rate * 1.5 if hours > 40.0: hours2 = hours - 40.0 pay = ((hours - hours2) * rate) + (hours2 * overtime) print('Pay:',pay) else: pay = hours * rate print('Pay:',pay)
true
5aa0a90c7a08bbec9a86be01ebe67336c81f0b7e
marcelofabiangutierrez88/cursoPython
/ejercicio13_raizcuadradaCubica.py
430
4.1875
4
#Realizar un algoritmos que lea un número y que muestre su raíz cuadrada y su raíz cúbica. Python3 no tiene ninguna función predefinida que permita calcular la raíz cúbica, ¿Cómo se puede calcular? import math def raiz(): num = int(input("Ingrese numero: ")) raizCua = math.sqrt(num) raizCub = (num)**1/3 print("La raiz cuadrada es: ",raizCua, "La raiz cubica es: ",raizCub) def main(): raiz() main()
false
ece7d8f33b05a2112b732c54fac44ec300d49b13
guti7/DifficultPython
/ex20.py
907
4.1875
4
# Exercise 20: Functions and Files # Using functions and files together. from sys import argv script, input_file = argv # unpacking # print the contents of the file def print_all(file): print file.read() # put cursor back at the start of the file def rewind(file): file.seek(0) # print a line from the current cursor position def print_a_line(line_count, file): print line_count, file.readline() current_file = open(input_file) print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines from start of file:" current_line = 1 print_a_line(current_line, current_file) # increase the current line count to be in sync with file position. current_line += 1 print_a_line(current_line, current_file) current_line += 1 # current_line + 1 print_a_line(current_line, current_file)
true
1341796bb376c35f450da6323a3632161095a64e
csteachian/Brampton-1
/LinkedLists.py
798
4.125
4
class node: def __init__(self): self.data = None # contains the data self.pointer = None # contains the reference to the next node class linked_list: def __init__(self): self.cur_node = None # cur meaning current def add_node(self, data): # add nodes to linked list new_node = node() # create a new node new_node.data = data new_node.pointer = self.cur_node # link the new node to the 'previous' node. self.cur_node = new_node # set the current node to the new one. def list_print(self): # prints out nodes node = self.cur_node # cant point to ll! while node: print(node.data) node = node.pointer ll = linked_list() ll.add_node(1) ll.add_node(2) ll.add_node(3) ll.list_print()
true
bae14c0ae2ac15ed2b7e34690c3b7dafc00a4036
divya-kustagi/python-stanford-cip
/assignments/assignment2/nimm.py
1,627
4.59375
5
""" File: nimm.py ------------------------- Nimm is an ancient game of strategy that where Players alternate taking stones until there are zero left. The game of Nimm goes as follows: 1. The game starts with a pile of 20 stones between the players 2. The two players alternate turns 3. On a given turn, a player may take either 1 or 2 stone from the center pile 4. The two players continue until the center pile has run out of stones. The last player to take a stone loses. """ TOTAL_STONES = 20 NUM_PLAYERS = 2 def main(): game_of_nimm() def input_is_invalid(user_input, num_of_stones): if (num_of_stones == 1) and (user_input == 2): print("Not enough stones to remove!") return True elif (user_input == 1) or (user_input == 2): return False else: return True def game_of_nimm(): print("Welcome to the game of Nimm!") num_of_stones = TOTAL_STONES player_turn = 1 print("There are " + str(num_of_stones) + " stones left") while num_of_stones > 0: user_input = int(input("Player " + str(player_turn) + " would you like to remove 1 or 2 stones? ")) while input_is_invalid(user_input, num_of_stones): user_input = int(input("Please enter 1 or 2: ")) num_of_stones -= user_input player_turn = (player_turn % NUM_PLAYERS) + 1 if num_of_stones !=0: print("\nThere are " + str(num_of_stones) + " stones left") print("\nPlayer " + str(player_turn) + " wins!") # This provided line is required at the end of a Python file # to call the main() function. if __name__ == '__main__': main()
true
1ca356d1262de4b4434ff1d53abbd290664b441b
divya-kustagi/python-stanford-cip
/assignments/assignment2/hailstones.py
1,106
4.625
5
""" File: hailstones.py ------------------- This program reads in a number from the user and then displays the Hailstone sequence for that number. The problem can be expressed as follows: * Pick some positive integer and call it n. * If n is even, divide it by two. * If n is odd, multiply it by three and add one. * Continue this process until n is equal to one. """ def main(): hailstones() def hailstones(): iterations = 0 num_input = int(input("Enter a number: ")) while num_input != 1: iterations += 1 if num_input % 2 == 0: next_num = int(num_input / 2) print(str(num_input) + " is even, so I take half: " + str(next_num)) num_input = int(next_num) else: next_num = 3*num_input + 1 print(str(num_input) + " is odd, so I make 3n + 1: " + str(next_num)) num_input = int(next_num) print("The process took " + str(iterations) + " steps to reach 1") # This provided line is required at the end of a Python file # to call the main() function. if __name__ == '__main__': main()
true
ca259b4ad0aadf96054ab221e50d3e471f6b175d
divya-kustagi/python-stanford-cip
/diagnostic/ramp_climbing_karel_v2.py
1,151
4.25
4
""" ramp_climbing_karel.py A program that makes Karel-the robot draw a diagonal line across the world, with a slope of 'slope_y/slope_x' """ from karel.stanfordkarel import * def main(): draw_diagonal() def draw_diagonal(): """ Function for Karel to draw diagonal line of slope 1/2 across any world y/x = 1/2 """ slope_x = 2 slope_y = 1 while left_is_clear() and front_is_clear(): draw_line(slope_x, slope_y) def draw_line(x, y): """ Karel climbs one step Pre-condition : Karel is facing East in the position of a point/beeper. Post-condition : Karel has climbed a step(on line with slope 1/2) and is still facing East, in position of next point/beeper. """ put_beeper() for i in range(x): if front_is_clear(): move() turn_left() for i in range(y): if front_is_clear(): move() turn_right() # There is no need to edit code beyond this point def turn_right(): for i in range(3): turn_left() def turn_around(): for i in range(2): turn_left() if __name__ == "__main__": run_karel_program()
true
35498e7426acd2a5ab337b2f3399c318829d88c1
Ranadip-Das/FunWithTurtle
/spiralhelix.py
289
4.4375
4
# Python program to draw Spiral Helix pattern using Turtle programming. import turtle window = turtle.Screen() turtle.speed(2) turtle.bgcolor('Black') for i in range(120): turtle.pencolor('Blue') turtle.circle(5*i) turtle.circle(-5*i) turtle.left(i) turtle.exitonclick()
true
4d07019e2c247986a7f8e3aa5aa3aa241ac10800
AdrianPratama/AdrianSuharto_ITP2017_Exercise5
/Exercise5-6.py
1,481
4.125
4
def calculator(num,format,operator): if num: output = num[0] if operator == "+" or operator == "addition" or operator == "": for i in num[1:]: output += i elif operator == "-" or operator == "subtraction": for i in num[1:]: output -= i elif operator == "*" or operator == "multiplication": for i in num[1:]: output *= i elif operator == "/" or operator == "division": for i in num[1:]: output /= i if format == "integer": return print(int(output//1)) elif format == "float": return print(float(output)) elif format == "": return print(output) else: print("Unknown format!") else: raise Exception("No input detected!") def check(numbers): list = [] if numbers == "": return list elif len(numbers) == 1: list.append(int(numbers)) return list elif "," in numbers: numbers = numbers.split(",") for i in numbers: if "." in i: list.append(float(i)) elif "." not in i: list.append(int(i)) return list numbers = input("Your list of number please (Example: 1,2,3,4,5) :") num = check(numbers) operator = input("Please input the operator:") format = input("Please input the format:") calculator(num,format,operator)
false
0a345474c0bc7e96e49501cf52e4f5f42f156fa1
vanillaike/python-fizzbuzz
/fizzbuzz/calculator.py
358
4.15625
4
''' This module performs the fizzbuzz calculation for a given number ''' def calculate_fizzbuzz(number): ''' Given a number return the fizzbuzz value ''' value = '' if number % 3 == 0: value += 'fizz' if number % 5 == 0: value += 'buzz' if number == 0 or value == '': value = str(number) return value
true
a634d5115d38cded8cd44161584cba5da09afea1
satsumas/Euler
/prob1.py
496
4.46875
4
#!/usr/bin/python """ 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 mult_sum(n): for a in range(n): if a % 3 == 0 or a % 5 == 0: multiples.append(a) multiples = [] print "Multiples of 3 or 5 less than " + str(n) + "are: " + str(multiples) print "Their sum is: " + str(sum(multiples)) mult_sum(1000)
true
f11319854a0e56d9b0d4ffd9db5373859c4e7ecb
hello7s/IE709
/Decorators.py
2,058
4.1875
4
@decorator def functions(arg): return "value" def function(arg): return "value" function = decorator(function) # this passes the function to the decorator, and reassigns it to the functions def repeater(old_function): def new_function(*args, **kwds): # See learnpython.org/page/Multiple%20Function%20Arguments for how *args and **kwds works old_function(*args, **kwds) # we run the old function old_function(*args, **kwds) # we do it twice return new_function # we have to return the new_function, or it wouldn't reassign it to the value >>> @repeater def multiply(num1, num2): print(num1 * num2) >>> multiply(2, 3) 6 6def double_out(old_function): def new_function(*args, **kwds): return 2 * old_function(*args, **kwds) # modify the return value return new_function def double_Ii(old_function): def new_function(arg): # only works if the old function has one argument return old_function(arg * 2) # modify the argument passed return new_function def check(old_function): def new_function(arg): if arg < 0: raise (ValueError, "Negative Argument") # This causes an error, which is better than it doing the wrong thing old_function(arg) return new_function def multiply(multiplier): def multiply_generator(old_function): def new_function(*args, **kwds): return multiplier * old_function(*args, **kwds) return new_function return multiply_generator # it returns the new generator # Usage @multiply(3) # multiply is not a generator, but multiply(3) is def return_num(num): return num # Now return_num is decorated and reassigned into itself return_num(5) # should return 15 def type_check(correct_type): #put code here @type_check(int) def times2(num): return num*2 print(times2(2)) times2('Not A Number') @type_check(str) def first_letter(word): return word[0] print(first_letter('Hello World')) first_letter(['Not', 'A', 'String'])
true
f6ff640aec343ca10723dcda4ff37b914087d27e
dlz215/hello_sqlite_python
/sqlite/db_context_manager_error_handling.py
1,454
4.15625
4
""" sqlite3 context manager and try-except error handling """ import sqlite3 database = 'phone_db.sqlite' def create_table(): try: with sqlite3.connect(database) as conn: conn.execute('create table phones (brand text, version int)') except sqlite3.Error as e: print(f'error creating table because {e}') finally: conn.close() def add_test_data(): try: with sqlite3.connect(database) as conn: conn.execute('insert into phones values ("Android", 5)') conn.execute('insert into phones values ("iPhone", 6)') except sqlite3.Error: print('Error adding rows') finally: conn.close() def print_all_data(): # Execute a query. Do not need a context manager, as no changes are being made to the db try: conn = sqlite3.connect(database) for row in conn.execute('select * from phones'): print(row) except sqlite3.Error as e: print(f'Error selecting data from phones table because {e}') finally: conn.close() def delete_table(): try: with sqlite3.connect(database) as conn: conn.execute('drop table phones') except sqlite3.Error as e: print(f'Error deleting phones table because {e}') finally: conn.close() def main(): create_table() add_test_data() print_all_data() delete_table() if __name__ == '__main__': main()
true
e48faa8f890e34de1462546f50729912bb1a9cc0
dlz215/hello_sqlite_python
/sqlite/insert_with_param.py
791
4.34375
4
import sqlite3 conn = sqlite3.connect('my_first_db.db') # Creates or opens database file # Create a table if not exists... conn.execute('create table if not exists phones (brand text, version int)') # Ask user for information for a new phone brand = input('Enter brand of phone: ') version = int(input('Enter version of phone (as an integer): ')) # Parameters. Use a ? as a placeholder for data that will be filled in # Provide data as a second argument to .execute, as a tuple of values conn.execute('insert into phones values (?, ?)', (brand, version)) conn.commit() # Ask the database to save changes # Fetch and display all data. Results stored in the cursor object cur = conn.execute('select * from phones') for row in cur: print(row) conn.close() # TODO error handling!
true
bcab1c739b480880f508e207ca50983f08c74b6d
dlz215/hello_sqlite_python
/sqlite/hello_db.py
691
4.40625
4
import sqlite3 # Creates or opens connection to db file conn = sqlite3.connect('first_db.sqlite') # Create a table conn.execute('create table if not exists phones (brand text, version integer)') # Add some data conn.execute('insert into phones values ("Android", 5)') conn.execute('insert into phones values ("iPhone", 6)') conn.commit() # Finalize updates # Execute a query. execute() returns a cursor # Can use the cursor in a loop to read each row in turn for row in conn.execute('select * from phones'): print(row) conn.execute('drop table phones') # Delete table conn.commit() # Ask the database to save changes - don't forget! conn.close() # And close connection.
true
a582580bf78ae9efebdc7f4c86e73938e8559680
TaurusCanis/ace_it
/ace_it_test_prep/static/scripts/test_question_scripts/math_questions/Test_1/math_2/math_T1_S2_Q9.py
1,909
4.21875
4
import random trap_mass = random.randint(125,175) mouse_mass = random.randint(3,6) answer = trap_mass - (mouse_mass * 28) - 1 question = f"<p>The mass required to set off a mouse trap is {trap_mass} grams. Of the following, what is the largest mass of cheese, in grams, that a {mouse_mass}-ounce mouse could carry and <u>not</u> set off the trap? (1 ounce = 28 grams)</p>\n" options = [ { "option": answer, "correct": True }, { "option": answer + 1, "correct": False }, { "option": "28", "correct": False }, { "option": mouse_mass * 28, "correct": False }, { "option": trap_mass - (mouse_mass * 25), "correct": False } ] random.shuffle(options) print(question) letter_index = 65 for option in options: print(chr(letter_index) + ": " + str(option["option"])) letter_index += 1 user_response = input("Choose an answer option: ") if options[ord(user_response.upper()[0]) - 65]["correct"]: print("CORRECT!") else: print("INCORRECT!") print(answer) # "distractor_rationale_response_level":[ # "You used the conversion rate as the maximum mass of cheese, but the conversion rate is only used to determine the mass of the mouse in grams.", # "A mouse weighing 4 ounces has a mass of 112 grams, since 4&nbsp;× 28 = 112. Since 157&nbsp;– 112 = 45, the cheese must weigh less than 45 grams for the trap to not be be set off. The largest given mass that is less than 45 grams is 44 grams.", # "You solved the equation 157&nbsp;–&nbsp;<em>x&nbsp;</em>= 112, but overlooked that the solution represents the minimum mass of cheese that would set off the trap.", # "You may have multiplied 4 by 25 instead of 28 to find the mass of the mouse in grams, but that mass is 128 grams.", # "You identified the mass of the mouse in grams, rather than the maximum mass of the cheese that will not set off the trap." # ]
true
025d54adeaf5912dc4ba569760bdb230535d3f91
terpator/study
/Перегрузка операторов/domashka_1.py
1,806
4.4375
4
""" Создайте класс «Прямоугольник», у которого присутствуют два поля (ширина и высота). Реализуйте метод сравнения прямоугольников по площади. Также реализуйте методы сложения прямоугольников (площадь суммарного прямоугольника должна быть равна сумме площадей прямоугольников, которые вы складываете). Реализуйте методы умножения прямоугольника на число n (это должно увеличить площадь базового прямоугольника в n раз). """ import numbers class Rectangle: def __init__(self, width, height): self.width = width self.height = height self.s = self.width * self.height def __eq__(self, other): return self.s == other.s def __gt__(self, other): return self.s > other.s def __add__(self, other): self.s = self.s + other.s return self def __str__(self): return "Rectangle[width = {}, height = {}]".format(self.width, self.height) def __mul__(self, n): if isinstance(n, numbers.Real): self.s = self.s * n return self else: return NotImplemented rec_1 = Rectangle(2, 3) rec_2 = Rectangle(4, 5) print("rec_1 < rec_2 ", rec_1 < rec_2) rec_3 = rec_1 + rec_2 print("Площадь нового прямоугольника (+) равна", rec_3.s) rec_3 = rec_1 * 4 print("Площадь нового прямоугольника (*4) равна", rec_3.s)
false
40f6cd3a98d40574823232f98245135f151d8def
terpator/study
/Условные операторы/dop_domashka_1.py
664
4.25
4
""" Есть круг с центром в начале координат и радиусом 4. Пользователь вводит с клавиатуры координаты точки x и y. Написать программу, которая определит, лежит ли эта точка внутри круга или нет. """ import math x = int(input("Введите координату X =")) y = int(input("Введите координату Y =")) r = 4 if math.sqrt(x ** 2 + y ** 2) < r: print("Точка лежит внутри круга") else: print("Точка не лежит внутри круга")
false
89999258644654428bba68bb818ed54f58fda0f8
terpator/study
/Списки/dop_domashka_2.py
522
4.4375
4
""" Написать код для зеркального переворота списка [7,2,9,4] -> [4,9,2,7]. Список может быть произвольной длины. (При выполнении задания использовать дополнительный список нельзя). """ import random mylist = [] for i in range(6): mylist.append(random.randint(1,9)) print(mylist) print() print("Зеркальная версия списка:") print(mylist[::-1])
false
1ebc1534d3831f04033660397845f02e81a7c320
terpator/study
/Функции как полноправные объекты/domashka_8_2.py
1,376
4.46875
4
""" Используя функцию замыкания реализуйте такой прием программирования как Мемоизация - https://en.wikipedia.org/wiki/Memoization Используйте полученный механизм для ускорения функции рекурсивного вычисления n — го члена ряда Фибоначчи. Сравните скорость выполнения с просто рекурсивным подходом. """ import time def fibonacci_mem(n): cache = {0:0,1:1} def fib(n): if n in cache: return cache[n] cache[n] = fib(n-1) + fib(n-2) return cache[n] return fib def fibonacci(n): if n == 0: return 0 if n in [1, 2]: return 1 return fibonacci(n - 1) + fibonacci(n - 2) print() print("Мемоизация в действии (n=30)") print() start = time.time() f=fibonacci_mem(30) for i in range(30): print(f(i), end = " ") end = time.time() print() print("Заняла: ", end - start, "секунд") print() print() print("Обычная рекурсия (n=30)") print() start = time.time() for i in range(30): print(fibonacci(i), end = " ") end = time.time() print() print("Заняла: ", end - start, "секунд")
false
09a60043573eae4c5654957b5a0ddd175c3026ec
terpator/study
/Функции. Часть 1/domashka_4.py
947
4.21875
4
""" Напишите функцию, которая реализует линейный поиск элемента в списке целых чисел. Если такой элемент в списке есть, то верните его индекс, если нет, то верните число «-1». """ import random def findnum(somelist, n): numindex = -1 for element in somelist: if element == n: numindex = somelist.index(n) return numindex somelist = [] for i in range(10): somelist.append(random.randint(1,100)) print(somelist) n = int(input("Введите число для поиска: ")) numindex = findnum(somelist, n) if numindex != -1: print("Число находится на позиции {num} индекса".format(num = numindex)) else: print("Такого числа в списке нет! {num}".format(num = numindex))
false
0b13510b0931f0394fb0d33d71d723586000ffa5
Tang8560/Geeks
/Algorithms/1.Searching and Sorting/01.Linear_Search/Linear_Search.py
1,563
4.3125
4
# Linear Search # Difficulty Level : Basic # Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[]. """ Examples : Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170} x = 110; Output : 6 Element x is present at index 6 Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170} x = 175; Output : -1 Element x is not present in arr[]. """ # The time complexity of the above algorithm is "O(n)". # Linear search is rarely used practically because other search algorithms # such as the binary search algorithm and hash tables allow significantly # faster-searching comparison to Linear search. def Linear_search(arr, x): for _ in arr: if x == _: idx = arr.index(_) return idx return -1 idx = Linear_search([10, 20, 80, 30, 60, 50, 110, 100, 130, 170], 175) print(idx) # Improve Linear Search Worst-Case Complexity (如何降低複雜度) # if element Found at last O(n) to O(1) # if element Not found O(n) to O(n/2) def Linear_serach_improve(arr, x): LEFT = 0 RIGHT = len(arr) -1 LENGTH = len(arr) POSITION = -1 for _ in range(LENGTH): if arr[LEFT] == x : POSITION = LEFT return POSITION if arr[RIGHT] == x : POSITION = RIGHT return POSITION LEFT += 1 RIGHT -= 1 return POSITION idx = Linear_serach_improve([10, 20, 80, 30, 60, 50, 110, 100, 130, 170], 100) print(idx)
true
0d195d9d4ca4abadd5b2f8439cc068c8f4e78693
Zaneta6/Module_04
/Calculator.py
1,002
4.25
4
# Calculation() function provides a simple tool for basic calculation. # Operator allows to choose a requested operation - additing, subtracting, multiplying and dividing - based on selected index (1-4). # The "a" and "b" parameters indicate the subjects of the operation (integers). import sys import logging logging.basicConfig(level=logging.DEBUG) def calculation(operator, a, b): result = 0 if operator == 1: result = result + (a + b) elif operator == 2: result = result + (a - b) elif operator == 3: result = result + (a * b) elif operator == 4: result = result + (a/b) else: print("Error. Incorrect operator index.") exit(1) return result if __name__ == "__main__": operator = int(input("Select operation type: (1 - addition, 2 - subtraction, 3 - multiplication, 4 - division) ")) a = int(input("Select the first number: ")) b = int(input("Select the second number: ")) calculation_result = calculation(operator, a, b) print(calculation_result)
true
0fe189615a931bd51482951a95364926b28e5c0c
apapadoi/Numerical-Analysis-Projects
/Second Project/Exercise6/trapezoid.py
1,626
4.25
4
def trapezoid_integrate(f, a, b, N, points): """ Computes the integral value from a to b for function f using Trapezoid method. Parameters ---------- f : callable The integrating function a,b : float The min and max value of the integrating interval N : int Number of partitions. points : ndarray The partition points Returns ------- return_value : float The value of the integral from a to b of the function f """ total_sum = 0 total_sum += f(points[0]) + f(points[N]) first_sum = 0.0 for i in range(1, N): first_sum += f([points[i]]) first_sum *= 2 total_sum += float(first_sum) interval_length = b - a denominator = 2 * N return (interval_length / denominator) * total_sum def trapezoid_error_bound(a, b, N, M): """ Computes the theoretical error bound when calculating an integral using Trapezoid method. Parameters ---------- a,b : float The min and max value of the integrating interval N : int Number of partitions. M : float The value of local max on [a,b] of the <b>absolute</b> 2nd derivative of function f used in Trapezoid integration Returns ------- return_value : float The value of theoretical error bound when calculating an integral using Trapezoid method """ interval_length = b - a denominator = 12 * (N ** 2) return ((interval_length**3)/denominator)*M
true
af59a08e7396e851052c2a8dcaf31d7d6140b463
ParthShirolawala/PythonAssignments
/Assignment2/Question-5.py
274
4.25
4
#multiplying everything by 3 and output the result import copy numbers = [1,2,4,6,7,8] def multiplyNumbers(): number = copy.deepcopy(numbers) newnumber = [] for i in number: newnumber.append(i*5) print newnumber print numbers multiplyNumbers()
true
4b88b2949f0f8f734de81d4fcdbb9b02672623c5
xiaonanln/myleetcode-python
/src/380. Insert Delete GetRandom O(1).py
1,165
4.21875
4
import random class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.index = {} self.vals = [] def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool """ if val in self.index: # already exists return False self.vals.append(val) self.index[val] = len(self.vals) - 1 return True def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. :type val: int :rtype: bool """ idx = self.index.pop(val, None) if idx is None: return False if idx == len(self.vals) - 1: self.vals.pop() else: lastval = self.vals[idx] = self.vals.pop() self.index[lastval] = idx return True def getRandom(self): """ Get a random element from the set. :rtype: int """ return random.choice(self.vals) # Your RandomizedSet object will be instantiated and called as such: obj = RandomizedSet() print obj.insert(1) print obj.insert(2) print obj.insert(3) print obj.insert(4) print obj.remove(3) print obj.getRandom()
true
f646e518f6d81da0b4f32e60c78dd60f335fae71
claudiadadamo/random
/phone_number.py
1,653
4.40625
4
#!/usr/bin/env python2.7 import random from data_structures import queue """ Silly command line thing that will randomly generate phone numbers that the user must confirm if correct or not. This implementation uses a queue to append a random number and basically shift the numbers over by one. For example: Original number: 1234567890 Is this your number? no 2345678905 etc, etc The idea came from reading about people working on building the dumbest way to enter your phone number on a website (you can see it here: http://www.dailydot.com/lol/stupid-phone-number-entry-field-challenge/) """ VALID_RESPONSES = ('y', 'n') class PhoneNumber(object): def __init__(self): self.number = queue.IterableQueue() def generate(self): """ Generate the random number. If it is the first time, generate 10 random integers for the starting phone number. """ if self.number.size() == 0: for i in xrange(0, 10): num = random.randint(0, 9) self.number.enqueue(num) self.number.dequeue() rand_num = random.randint(0, 9) self.number.enqueue(rand_num) return ''.join([str(i) for i in self.number]) if __name__ == '__main__': base_number = PhoneNumber() answer = "n" while answer == "n": number = base_number.generate() print "is your number {}? y or n".format(number) answer = raw_input() if answer == 'y': print "WAHOO! " else: print "that is not a valid response. valid responses are " \ "{}".format(', '.join((VALID_RESPONSES)))
true
508c924c5fcbcb0963ecfae832b97f8a58853fde
adarrohn/codeeval
/tests/tests_easy/test_easy_oneeleven.py
1,133
4.125
4
import unittest from easy.challenge_num_oneeleven import return_longest_word class LongestWordTest(unittest.TestCase): """ Return the longest word in the line, if multiple return the first """ def setUp(self): pass def test_case_all_different(self): """ All words are of different lengths """ self.assertEquals(return_longest_word('One Five Eleven A Seven'), 'Eleven') def test_case_all_same(self): """ All words are of the same length """ self.assertEquals(return_longest_word('One Two Six'), 'One') def test_case_multiple_same(self): """ More than one word has the same length, but not all of them and equal """ self.assertEquals(return_longest_word('One Niner Two Six Seven'), 'Niner') def test_case_one_word(self): """ Only contains a single word """ self.assertEquals(return_longest_word('One'), 'One') if __name__ == '__main__': unittest.main()
true
808efddb964ada8296c4c344f11d32477de7a82e
benbendaisy/CommunicationCodes
/python_module/examples/411_Minimum_Unique_Word_Abbreviation.py
2,619
4.65625
5
import re from collections import defaultdict from typing import List class Solution: """ A string can be abbreviated by replacing any number of non-adjacent substrings with their lengths. For example, a string such as "substitution" could be abbreviated as (but not limited to): "s10n" ("s ubstitutio n") "sub4u4" ("sub stit u tion") "12" ("substitution") "su3i1u2on" ("su bst i t u ti on") "substitution" (no substrings replaced) Note that "s55n" ("s ubsti tutio n") is not a valid abbreviation of "substitution" because the replaced substrings are adjacent. The length of an abbreviation is the number of letters that were not replaced plus the number of substrings that were replaced. For example, the abbreviation "s10n" has a length of 3 (2 letters + 1 substring) and "su3i1u2on" has a length of 9 (6 letters + 3 substrings). Given a target string target and an array of strings dictionary, return an abbreviation of target with the shortest possible length such that it is not an abbreviation of any string in dictionary. If there are multiple shortest abbreviations, return any of them. Example 1: Input: target = "apple", dictionary = ["blade"] Output: "a4" Explanation: The shortest abbreviation of "apple" is "5", but this is also an abbreviation of "blade". The next shortest abbreviations are "a4" and "4e". "4e" is an abbreviation of blade while "a4" is not. Hence, return "a4". Example 2: Input: target = "apple", dictionary = ["blade","plain","amber"] Output: "1p3" Explanation: "5" is an abbreviation of both "apple" but also every word in the dictionary. "a4" is an abbreviation of "apple" but also "amber". "4e" is an abbreviation of "apple" but also "blade". "1p3", "2p2", and "3l1" are the next shortest abbreviations of "apple". Since none of them are abbreviations of words in the dictionary, returning any of them is correct. """ def minAbbreviation(self, target: str, dictionary: List[str]) -> str: m = len(target) diffs = {sum(2**i for i, c in enumerate(word) if target[i] != c) for word in dictionary if len(word) == m} if not diffs: return str(m) bits = max((i for i in range(2**m) if all(d & i for d in diffs)), key=lambda bits: sum((bits >> i) & 3 == 0 for i in range(m-1))) s = ''.join(target[i] if bits & 2**i else '#' for i in range(m)) return re.sub('#+', lambda m: str(len(m.group())), s)
true
ee46ae946c592b5718e7141fd43e9b53cbcf94ec
benbendaisy/CommunicationCodes
/python_module/examples/424_Longest_Repeating_Character_Replacement.py
1,751
4.125
4
class Solution: """ You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations. Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4. """ def characterReplacement(self, s: str, k: int) -> int: def is_window_valid(start, end, count): return end + 1 - start - count <= k all_letters = set(s) max_length = 0 # iterate over each unique letter for letter in all_letters: start, cnt = 0, 0 # initialize a sliding window for each unique letter for end in range(len(s)): if s[end] == letter: # if the letter matches, increase the count cnt += 1 # bring start forward until the window is valid again while not is_window_valid(start, end, cnt): if s[start] == letter: # if the letter matches, decrease the count cnt -= 1 start += 1 # at this point the window is valid, update max_length max_length = max(max_length, end + 1 - start) return max_length
true
cfca2d38b44ddbe3a3dd21628e15ead6b3105c88
benbendaisy/CommunicationCodes
/python_module/examples/413_Arithmetic_Slices.py
1,800
4.1875
4
from typing import List class Solution: """ An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences. Given an integer array nums, return the number of arithmetic subarrays of nums. A subarray is a contiguous subsequence of the array. Example 1: Input: nums = [1,2,3,4] Output: 3 Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. Example 2: Input: nums = [1] Output: 0 """ def numberOfArithmeticSlices1(self, nums: List[int]) -> int: cnt = 0 m = len(nums) for i in range(m - 2): dx = nums[i + 1] - nums[i] for j in range(i + 2, m): if nums[j] - nums[j - 1] == dx: cnt += 1 else: break return cnt def numberOfArithmeticSlices2(self, nums: List[int]) -> int: self.x = 0 def slices(idx): if idx < 2: return 0 ap = 0 if nums[idx] - nums[idx - 1] == nums[idx - 1] - nums[idx - 2]: ap = 1 + slices(idx - 1) else: slices(idx - 1) self.x += ap return ap slices(len(nums) - 1) return self.x def numberOfArithmeticSlices(self, nums: List[int]) -> int: m = len(nums) dp = [0] * m sums = 0 for i in range(2, m): if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]: dp[i] = 1 + dp[i - 1] sums += dp[i] return sums
true
679df26783c30db12885101108dc85339dcb61d6
benbendaisy/CommunicationCodes
/python_module/examples/1091_Shortest_Path_in_Binary_Matrix.py
2,133
4.15625
4
import collections from typing import List class Solution: """ Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that: All the visited cells of the path are 0. All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner). The length of a clear path is the number of visited cells of this path. Example 1: Input: grid = [[0,1],[1,0]] Output: 2 Example 2: Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4 Example 3: Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1 Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1 """ def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: if not grid: return -1 row, col = len(grid) - 1, len(grid[0]) - 1 directions = [ (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1) ] def getNeighbors(r: int, c: int): for idx, idy in directions: xrow, ycol = r + idx, c + idy if not (0 <= xrow <= row and 0 <= ycol <= col): continue elif grid[xrow][ycol] != 0: continue yield (xrow, ycol) if grid[0][0] == 1 or grid[row][col] == -1: return -1 queue = collections.deque([(0, 0)]) grid[0][0] = 1 while queue: curRow, curCol = queue.popleft() distance = grid[curRow][curCol] if curRow == row and curCol == col: return distance for nextRow, nextCol in getNeighbors(curRow, curCol): grid[nextRow][nextCol] = distance + 1 queue.append((nextRow, nextCol)) return -1
true
7b8398dffd2a2ac986a8eb9f09f318ba08657414
benbendaisy/CommunicationCodes
/python_module/examples/1239_Maximum Length_of_a_Concatenated _tring_with_Unique_Characters.py
1,519
4.1875
4
from typing import List class Solution: """ You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. Return the maximum possible length of s. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: arr = ["un","iq","ue"] Output: 4 Explanation: All the valid concatenations are: - "" - "un" - "iq" - "ue" - "uniq" ("un" + "iq") - "ique" ("iq" + "ue") Maximum length is 4. Example 2: Input: arr = ["cha","r","act","ers"] Output: 6 Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). Example 3: Input: arr = ["abcdefghijklmnopqrstuvwxyz"] Output: 26 Explanation: The only string in arr has all 26 characters. """ def maxLength(self, arr: List[str]) -> int: if not arr: return 0 res = [""] maxLength = 0 for word in arr: for i in range(len(res)): concatedString = res[i] + word if len(concatedString) != len(set(concatedString)): continue maxLength = max(maxLength, len(concatedString)) res.append(concatedString) return maxLength
true
cf08e3d07b4aeaf92e4470f32906e91c56506c4d
benbendaisy/CommunicationCodes
/python_module/examples/2390_Removing_Stars_From_a_String.py
1,590
4.21875
4
class Solution: """ You are given a string s, which contains stars *. In one operation, you can: Choose a star in s. Remove the closest non-star character to its left, as well as remove the star itself. Return the string after all stars have been removed. Note: The input will be generated such that the operation is always possible. It can be shown that the resulting string will always be unique. Example 1: Input: s = "leet**cod*e" Output: "lecoe" Explanation: Performing the removals from left to right: - The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e". - The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e". - The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe". There are no more stars, so we return "lecoe". Example 2: Input: s = "erase*****" Output: "" Explanation: The entire string is removed, so we return an empty string. """ def removeStars_1(self, s: str) -> str: stack = [] i, n = 0, len(s) while i < n: if s[i] != "*": stack.append(s[i]) else: stack.pop() i += 1 return "".join(stack) def removeStars(self, s: str) -> str: stack = [] for ch in s: if ch != "*": stack.append(ch) else: stack.pop() return "".join(stack)
true
c12c818bb35748151dd939cb6f975981dda7a348
benbendaisy/CommunicationCodes
/python_module/examples/1423_Maximum_Points_You_Can_Obtain_from_Cards.py
2,257
4.59375
5
from functools import lru_cache from typing import List class Solution: """ There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have taken. Given the integer array cardPoints and the integer k, return the maximum score you can obtain. Example 1: Input: cardPoints = [1,2,3,4,5,6,1], k = 3 Output: 12 Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12. Example 2: Input: cardPoints = [2,2,2], k = 2 Output: 4 Explanation: Regardless of which two cards you take, your score will always be 4. Example 3: Input: cardPoints = [9,7,7,9,7,7,9], k = 7 Output: 55 Explanation: You have to take all the cards. Your score is the sum of points of all cards. Constraints: 1 <= cardPoints.length <= 105 1 <= cardPoints[i] <= 104 1 <= k <= cardPoints.length """ def maxScore1(self, cardPoints: List[int], k: int) -> int: @lru_cache(None) def findMaxScore(left: int, right: int, l: int): if l == 0: return 0 return max(cardPoints[left] + findMaxScore(left + 1, right, l - 1), cardPoints[right] + findMaxScore(left, right - 1, l - 1)) return findMaxScore(0, len(cardPoints) - 1, k) def maxScore(self, cardPoints: List[int], k: int) -> int: n = len(cardPoints) if n < k: return -1 totalSum = sum(cardPoints) r = n - k idx = 0 minSum = sum(cardPoints[:r]) curSum = 0 for i in range(n): curSum += cardPoints[i] if i >= r: curSum -= cardPoints[idx] minSum = min(minSum, curSum) idx += 1 return totalSum - minSum
true
250f9690338895ac21907a38523cc8c7e2b8179d
benbendaisy/CommunicationCodes
/python_module/examples/475_Heaters.py
2,637
4.3125
4
import bisect from typing import List class Solution: """ Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses. Notice that all the heaters follow your radius standard, and the warm radius will the same. Example 1: Input: houses = [1,2,3], heaters = [2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. Example 2: Input: houses = [1,2,3,4], heaters = [1,4] Output: 1 Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. Example 3: Input: houses = [1,5], heaters = [2] Output: 3 """ def findRadius1(self, houses: List[int], heaters: List[int]) -> int: houses.sort() heaters.sort() if len(heaters) == 1: return max(abs(houses[0] - heaters[0]), abs(houses[-1] - heaters[0])) max_value = -1 f, s, ind_heat = heaters[0], heaters[1], 2 for i in range(len(houses)): while houses[i] > s and ind_heat < len(heaters): f, s = s, heaters[ind_heat] ind_heat += 1 max_value = max(max_value, min(abs(houses[i] - f), abs(houses[i] - s))) return max_value def findRadius(self, houses: List[int], heaters: List[int]) -> int: houses.sort() heaters.sort() res = 0 # For each house, find the closest heater to the left and the right for house in houses: left = bisect.bisect_right(heaters, house) - 1 right = bisect.bisect_left(heaters, house) # If the house is to the left of all heaters, use the closest heater to the left if left < 0: res = max(res, heaters[0] - house) # If the house is to the right of all heaters, use the closest heater to the right elif right >= len(heaters): res = max(res, house - heaters[-1]) # If the house is between two heaters, use the closer of the two else: res = max(res, min(house - heaters[left], heaters[right] - house)) # Return the result return res
true
aa410dcae529074f87749f5a8f6c313506d3d2e6
benbendaisy/CommunicationCodes
/python_module/examples/491_Increasing_Subsequences.py
1,263
4.1875
4
from typing import List class Solution: """ Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order. The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence. Example 1: Input: nums = [4,6,7,7] Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]] Example 2: Input: nums = [4,4,3,2,1] Output: [[4,4]] Constraints: 1 <= nums.length <= 15 -100 <= nums[i] <= 100 """ def findSubsequences(self, nums: List[int]) -> List[List[int]]: if not nums: return 0 res, visited = [], set() def dfs(idx, sub, prev): if len(sub) > 1: temp = tuple(sub) if temp not in visited: res.append(sub.copy()) visited.add(temp) if idx == len(nums): return if nums[idx] >= prev: dfs(idx + 1, sub + [nums[idx]], nums[idx]) dfs(idx + 1, sub, prev) dfs(0, [], -10000) return res
true
567876c5243f5f52f7e02363df445243354d4a64
benbendaisy/CommunicationCodes
/python_module/examples/1768_Merge_Strings_Alternately.py
1,194
4.40625
4
class Solution: """ You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string. Example 1: Input: word1 = "abc", word2 = "pqr" Output: "apbqcr" Explanation: The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r Example 2: Input: word1 = "ab", word2 = "pqrs" Output: "apbqrs" Explanation: Notice that as word2 is longer, "rs" is appended to the end. word1: a b word2: p q r s merged: a p b q r s Example 3: Input: word1 = "abcd", word2 = "pq" Output: "apbqcd" Explanation: Notice that as word1 is longer, "cd" is appended to the end. word1: a b c d word2: p q merged: a p b q c d """ def mergeAlternately(self, word1: str, word2: str) -> str: words = [w1 + w2 for w1, w2 in zip(word1, word2)] min_length = min(len(word1), len(word2)) return "".join(words) + word1[min_length:] + word2[min_length:]
true
ad61e5d8cab369e0380d12fac551e8654b671a95
benbendaisy/CommunicationCodes
/python_module/examples/299_Bulls_and_Cows.py
2,291
4.125
4
from collections import defaultdict, Counter class Solution: """ You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: The number of "bulls", which are digits in the guess that are in the correct position. The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number secret and your friend's guess guess, return the hint for your friend's guess. The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits. Example 1: Input: secret = "1807", guess = "7810" Output: "1A3B" Explanation: Bulls are connected with a '|' and cows are underlined: "1807" | "7810" Example 2: Input: secret = "1123", guess = "0111" Output: "1A1B" Explanation: Bulls are connected with a '|' and cows are underlined: "1123" "1123" | or | "0111" "0111" Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. Constraints: 1 <= secret.length, guess.length <= 1000 secret.length == guess.length secret and guess consist of digits only. """ def getHint(self, secret: str, guess: str) -> str: bulls = 0 cows = 0 secretArr = [] guessArr = [] for i in range(len(secret)): if secret[i] == guess[i]: bulls += 1 else: secretArr.append(secret[i]) guessArr.append(guess[i]) charMap = Counter(secretArr) for i in range(len(guessArr)): if guessArr[i] in charMap and charMap[guessArr[i]] > 0: cows += 1 charMap[guessArr[i]] -= 1 return str(bulls) + "A" + str(cows) + "B"
true
34e1c7dff02018790eecce9c15fdb490639d32fd
benbendaisy/CommunicationCodes
/python_module/examples/1372_Longest_ZigZag_Path_in_a_Binary_Tree.py
2,152
4.5
4
# Definition for a binary tree node. from functools import lru_cache from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: """ You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Choose any node in the binary tree and a direction (right or left). If the current direction is right, move to the right child of the current node; otherwise, move to the left child. Change the direction from right to left or from left to right. Repeat the second and third steps until you can't move in the tree. Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree. Example 1: Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1] Output: 3 Explanation: Longest ZigZag path in blue nodes (right -> left -> right). Example 2: Input: root = [1,1,1,null,1,null,null,1,1,null,1] Output: 4 Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right). Example 3: Input: root = [1] Output: 0 """ def longestZigZag(self, root: Optional[TreeNode]) -> int: @lru_cache(None) def dfs(node): # For each node, it computes three values: the length of # the longest zigzag path starting from the node and going # left, the length of the longest zigzag path starting from # the node and going right, and the maximum length of zigzag # path found so far in the tree. if not node: return [-1, -1, -1] left, right = dfs(node.left), dfs(node.right) return [ left[1] + 1, # go right to pick 1 right[0] + 1, # go left to pick 0 # pick the max of left, right, previous left and previous right max(left[1] + 1, right[0] + 1, left[2], right[2]) ] return dfs(root)[-1]
true
12ed712982b2ea97b9c1317a4d894b84f0cf2508
benbendaisy/CommunicationCodes
/python_module/examples/43_Multiply_Strings.py
782
4.25
4
class Solution: """ Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" """ def multiply(self, num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" num_dict = {str(i) : i for i in range(10)} val1 = 0 for i in num1: val1 = 10 * val1 + num_dict[i] val2 = 0 for j in num2: val2 = val2 * 10 + val1 * num_dict[j] return str(val2)
true
fcf5e146bed08d8823483651f8efbbea438623ce
benbendaisy/CommunicationCodes
/python_module/examples/222_Count_Complete_Tree_Nodes.py
1,389
4.15625
4
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: """ Given the root of a complete binary tree, return the number of the nodes in the tree. According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Design an algorithm that runs in less than O(n) time complexity. Example 1: Input: root = [1,2,3,4,5,6] Output: 6 Example 2: Input: root = [] Output: 0 Example 3: Input: root = [1] Output: 1 """ def countNodes(self, root: Optional[TreeNode]) -> int: if not root: return 0 return 1 + self.countNodes(root.left) + self.countNodes(root.right) def countNodes(self, root: Optional[TreeNode]) -> int: if not root: return 0 stack = [] cnt = 0 cur = root while stack or cur: while cur: stack.append(cur) cur = cur.left cur = stack.pop().right cnt += 1 return cnt
true
54abc6283cbf41b32ee1debe709699b3c6c14ca3
benbendaisy/CommunicationCodes
/python_module/examples/2244_Minimum_Rounds_to_Complete_All_Tasks.py
1,692
4.3125
4
from collections import defaultdict from typing import List class Solution: """ You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level. Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks. Example 1: Input: tasks = [2,2,3,3,2,4,4,4,4,4] Output: 4 Explanation: To complete all the tasks, a possible plan is: - In the first round, you complete 3 tasks of difficulty level 2. - In the second round, you complete 2 tasks of difficulty level 3. - In the third round, you complete 3 tasks of difficulty level 4. - In the fourth round, you complete 2 tasks of difficulty level 4. It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4. Example 2: Input: tasks = [2,3,3] Output: -1 Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1. """ def minimumRounds(self, tasks: List[int]) -> int: freq_dict = defaultdict(int) for task in tasks: freq_dict[task] += 1 min_rounds = 0 for count in freq_dict.values(): if count == 1: return -1 elif count % 3 == 0: min_rounds += count // 3 else: min_rounds += count // 3 + 1 return min_rounds
true
cdf7ca9c6839c2e8678911188e0d52960f9eebfd
benbendaisy/CommunicationCodes
/python_module/examples/662_Maximum_Width_of_Binary_Tree.py
2,797
4.25
4
# Definition for a binary tree node. import math from collections import deque, defaultdict from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: """ Given the root of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation. It is guaranteed that the answer will in the range of a 32-bit signed integer. Example 1: Input: root = [1,3,2,5,3,null,9] Output: 4 Explanation: The maximum width exists in the third level with length 4 (5,3,null,9). Example 2: Input: root = [1,3,2,5,null,null,9,6,null,7] Output: 7 Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7). Example 3: Input: root = [1,3,2,5] Output: 2 Explanation: The maximum width exists in the second level with length 2 (3,2). """ def widthOfBinaryTree1(self, root: Optional[TreeNode]) -> int: if not root: return 0 queue = deque([(root, 0, 0)]) max_left, max_right = -math.inf, math.inf level_dict = defaultdict(lambda : (0, 0)) while queue: node, level, width = queue.popleft() if not node: continue max_left = max(level_dict[level][0], width) max_right = min(level_dict[level][1], width) level_dict[level] = (max_left, max_right) queue.append((node.left, level + 1, width + 1)) queue.append((node.right, level + 1, width - 1)) max_width = 1 for left, right in level_dict.values(): max_width = max(max_width, right - left + 1) return max_width def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: if not root: return 0 queue = deque([(root, 0)]) max_width = 0 while queue: level_length = len(queue) _, start_index = queue[0] for i in range(level_length): node, index = queue.popleft() if node.left: queue.append((node.left, 2 * index)) if node.right: queue.append((node.right, 2 * index + 1)) max_width = max(max_width, index - start_index + 1) return max_width
true
20813878fb7e6346fb1ab86e8a77a79fb1264b5b
benbendaisy/CommunicationCodes
/python_module/examples/430_Flatten_a_Multilevel_Doubly_Linked_List.py
2,896
4.28125
4
""" # Definition for a Node. """ class Node: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child class Solution: """ You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. Example 1: Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] Output: [1,2,3,7,8,11,12,9,10,4,5,6] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 2: Input: head = [1,2,null,3] Output: [1,3,2] Explanation: The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: Example 3: Input: head = [] Output: [] Explanation: There could be empty list in the input. """ def flatten1(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return head def flat_dfs(prev_node: Node, cur_node: Node): if not cur_node: return prev_node prev_node.next = cur_node cur_node.prev = prev_node # the curr.next would be tempered in the recursive function t = cur_node.next tail = flat_dfs(cur_node, cur_node.child) cur_node.child = None return flat_dfs(tail, t) prev = Node(0, None, head, None) flat_dfs(prev, head) prev.next.prev = None return prev.next def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]': if not head: return head pseudo_head = Node(0, None, head, None) prev = pseudo_head stack = [] stack.append(head) while stack: cur = stack.pop() prev.next = cur cur.prev = prev if cur.next: stack.append(cur.nemxt) if cur.child: stack.append(cur.child) cur.child = None prev = cur pseudo_head.next.prev = None return pseudo_head.next
true
8b1309373057fbd98411e5a0d78b9e699c7c501c
benbendaisy/CommunicationCodes
/python_module/examples/124_Binary_Tree_Maximum_Path_Sum.py
2,063
4.25
4
# Definition for a binary tree node. import math from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: """ A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path. Example 1: Input: root = [1,2,3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. Example 2: Input: root = [-10,9,20,null,null,15,7] Output: 42 Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. """ def maxPathSum(self, root: Optional[TreeNode]) -> int: max_sum_path = -math.inf # post order traversal of subtree rooted at `node` def gain_from_subtree(node: Optional[TreeNode]): nonlocal max_sum_path if not node: return 0 # add the gain from the left subtree. Note that if the # gain is negative, we can ignore it, or count it as 0. # This is the reason we use `max` here. gain_from_left = max(gain_from_subtree(node.left), 0) # add the gain / path sum from right subtree. 0 if negative gain_from_right = max(gain_from_subtree(node.right), 0) # if left or right gain are negative, they are counted # as 0, so this statement takes care of all four scenarios max_sum_path = max(max_sum_path, gain_from_left + gain_from_right + node.val) return max(gain_from_left + node.val, gain_from_right + node.val) gain_from_subtree(root) return max_sum_path
true
6816960be9c3f6fe0505263a03cffb74c2679b61
benbendaisy/CommunicationCodes
/python_module/examples/1035_Uncrossed_Lines.py
2,147
4.46875
4
from functools import lru_cache from typing import List class Solution: """ You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that: nums1[i] == nums2[j], and the line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return the maximum number of connecting lines we can draw in this way. Example 1: Input: nums1 = [1,4,2], nums2 = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2. Example 2: Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2] Output: 3 Example 3: Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1] Output: 2 """ def maxUncrossedLines1(self, nums1: List[int], nums2: List[int]) -> int: m, n = len(nums1), len(nums2) if m < n: nums1, nums2 = nums2, nums1 m, n = n, m dp = [0] * (n + 1) for i in range(1, m + 1): prev = 0 for j in range(1, n + 1): curr = dp[j] if nums1[i - 1] == nums2[j - 1]: dp[j] = prev + 1 else: dp[j] = max(curr, dp[j - 1]) prev = curr return dp[-1] def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: m, n = len(nums1), len(nums2) @lru_cache(None) def max_lines(i, j): if i == m or j == n: return 0 res = max(max_lines(i + 1, j), max_lines(i, j + 1)) if nums1[i] == nums2[j]: res = max(res, 1 + max_lines(i + 1, j + 1)) return res return max_lines(0, 0)
true
392c70857f66209883f4e5d15daee7e93d5bc3ba
PSarapata/ShawBasic
/ex30.py
930
4.34375
4
people = 30 cars = 40 trucks = 15 if cars > people: print("We should be driving cars!") elif cars < people: print("We should not be driving cars.") else: print("We can't decide.") if trucks > cars: print("There are too many trucks!") elif trucks < cars: print("Maybe we should take the trucks.") else: print("We still can't decide.") if people > trucks: print("Alright, let's just take the trucks.") else: print("Okay, let's stay at home.") # 1. elif to instrukcja warunkowa, która wykona się w przypadku gdy instrukcja if wyrzuciła Fałsz. Interpreter sprawdza warunek, # jeśli jest prawdą to wykona kod, jeśli nie - idzie dalej, do else (w else już nie ma warunku, to kod, który wykona się jeśli wszystkie # poprzedzające warunki to fałsz). Jeśli wiele elif-ów daje prawdę, wykonany zostanie ten, który wyrzucił prawdę jako pierwszy # (z góry na dół w skrypcie)
false
8ed81cbef9e9fcc50d26491c5d209b1db7fafaac
DivyaReddyNaredla/python_classes
/abstract_classes.py
1,211
4.25
4
"""import keyword #print(keyword.kwlist) print(type(1)) print(type([])) print(type({})) print(type(())) print(type("")) print(type(keyword)) #module is class""" #Extending properties of super calss into sub class is called as inheritance #Forcing to use same function which is defined in super class # @ is called as annotation for any method #abstract method class example """from abc import ABC,abstractmethod #ABC is abstract base class class Bankclass(ABC): @abstractmethod # we can write @ for what function we need to abstract def deposit(self,amount): pass class AndhraBank(Bankclass): def example(self): print("hi") def deposit(self,amount): print(amount) e = AndhraBank()""" from abc import ABC,abstractmethod class animal(ABC): @abstractmethod def walks(self,name): pass class monkey(animal): def walks(self,name): print(name,"Walks on four legs") class dog(animal): def walks(self,name): print("Dog is loyal pet") e = monkey() #w = input("Enter the animal name: ") e.walks('k') """f = dog() k = input("Enter your pet name: ") f.walks(k)"""
true
3b1c946c1bfcfe07ea57a9f9b1cdb2cac975c708
Hghar929/random-forest-temperature-forecast
/main.py
1,871
4.46875
4
# Tutorial from https://towardsdatascience.com/random-forest-in-python-24d0893d51c0 # features: variables # labels: y value # Pandas is used for data manipulation import pandas as pd # Use numpy to convert to arrays import numpy as np # Using Skicit-learn to split data into training and testing sets from sklearn.model_selection import train_test_split # Read in data and display first 5 rows features = pd.read_csv('temps.csv') print(features.head(5)) print('The shape of our features is: i.e. (row X cols)', features.shape) # This process tries to remote the anomanies # Descriptive statistics for each column print(features.describe()) #Another way to verify the quality of the data is to make basic plots # Data preparation # panda one-hot encode the data using the pandas get_dummies features = pd.get_dummies(features) # Display the first 5 rows of the last 12 columns # i.e. all rows and column starts from the 5th print(features.iloc[:,5:].head(5)) print('=========== Grab the y data and data for factors ============') # Labels are the values we want to predict (i.e. y value) # this returns an array of the 'actual' column labels = np.array(features['actual']) # Remove the labels from the features # axis 1 refers to the columns # we drop the column as the actual column is the y value while features means all data for the factors features= features.drop('actual', axis = 1) # Saving feature names for later use feature_list = list(features.columns) # Convert to numpy array features = np.array(features) print('=========== Separate training and testing sets ============') # Split the data into training and testing sets train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size = 0.25, random_state = 42) print(test_features, test_labels) print('=========== End of preparing data ============')
true
dbf13f1d29bc55694a92a15db4a47dea189b1c40
rathoddilip/BasicPythonPractice
/prime_number.py
235
4.125
4
number = int(input("Enter number")) prime = True for i in range(2, number): if number % i == 0: prime = False break if prime: print(f"{number} number is prime") else: print(f"{number} number is not prime")
true
595a154e87ddc617ae449edfe1a3233edf3b1af3
rathoddilip/BasicPythonPractice
/dictionary_practice.py
1,091
4.21875
4
# dictionary nothing but kay value pair myDict = {"subject": "python", "marks": [20], "teacher": "Ashish Ogale", "anotherDic": {"grade": "A+"} } print("Subject: ", myDict["subject"]) print("Teacher Name: ", myDict["teacher"]) # dictionary within dictionary print("Grade: ", myDict["anotherDic"]["grade"]) # methods print("keys: ", myDict.keys()) print("Values: ", myDict.values()) print("items: ", myDict.items()) # typecast dictionary to list print("type cast dic to list:", list(myDict.keys())) # add new value to dictionary updateDict = { "university": "pune", } myDict.update(updateDict) print("updated dictionary: ", myDict) # get particular value based on keys using get method print(myDict.get("subject")) favLang = {} stud1 = input("enter your favorite lang Dilip\n") stud2 = input("enter your favorite lang Sandip\n") stud3 = input("enter your favorite lang Arjun\n") stud4 = input("enter your favorite lang Ranjit\n") favLang["dilip"] = stud1 favLang["sandip"] = stud2 favLang["arjun"] = stud3 favLang["ranjit"] = stud4 print(favLang)
false
176a3f93d8a950342dd7bbf34bed0ade9c356dd2
ozenerdem/HackerRank
/PYTHON/Easy/sWAP cASE.py
704
4.375
4
""" You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. For Example: Www.HackerRank.com → wWW.hACKERrANK.COM Pythonist 2 → pYTHONIST 2 Sample Input 0 HackerRank.com presents "Pythonist 2". Sample Output 0 hACKERrANK.COM PRESENTS "pYTHONIST 2". """ def swap_case(s): a = list(s) for i in range(len(a)): if a[i]<= 'Z' and a[i]>= 'A': a[i] = a[i].lower() elif a[i]<='z' and a[i]>= 'a': a[i] = a[i].upper() b = "" for i in range(len(a)): b += a[i] return b if __name__ == '__main__': s = input() result = swap_case(s) print(result)
true
881f8f061c4dc2919631e7f21746a84b88bc3ea2
ryan-berkowitz/python
/Python Projects/Python Session 072821/Random_Number.py
897
4.1875
4
import random x = random.randint(1,9) i = 0 while True: user = input("Enter a guess between 1 and 9: ") if user == "exit": break try: y = int(user) except: print("Guess is not an integer. Please input another guess.") continue if y > 9: print("Guess is greater than 9. Please input another guess.") continue if y < 1: print("Guess is less than 1. Please input another guess.") continue i += 1 if y > x: print("Guess is greater than number. Guess again.") elif y < x: print("Guess is less than number. Guess again.") elif y == x: correct_message = "The number was {}. You've guessed correctly! It took you {} times." print(correct_message.format(str(y),str(i))) break else: print("Something went wrong.")
true
1abed244f1fdc0538c9a98dc6c249854f199b638
sanupanji/python
/function_exercises/function7.py
342
4.1875
4
# write a function that counts the number of times a given pattern appears in a string, including overlap # "hah", "hahahaha" --> 3 def pattern_count(ptn, strg): count = 0 while strg.find(ptn) != -1: i = strg.find(ptn) strg = strg[i+1:] count += 1 return count print(pattern_count("hah", "hahahah"))
true
04d0b861335d0af305ef6c59a3fa4aed75a20a47
sanupanji/python
/practice_w3resource/19_string_man_1.py
349
4.15625
4
''' Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged. ''' def string_man_1(st): if st[:2].lower() == "is": return st return "Is" + st print(string_man_1(input("enter the string : ")))
true
b92c50cacb403cab97f011d5ccfc4086443786c8
sanupanji/python
/OOPS/line.py
773
4.40625
4
''' fill in the line class methods to accepts coordintes as a pair of tuples and return the slope and distance of the line cor1=(3,2) cor2=(8,10) li = line(cor1,cor2) li.distance() li.slope() distance = sqrt((x2-x1)**2 + (y2-y1)**2) slope = (y2-y1)/(x2-x1) ''' from math import sqrt class line(): def __init__(self, cor1, cor2): '''self.x1 = cor1[0] self.y1 = cor1[1] self.x2 = cor2[0] self.y2 = cor2[1] ''' self.x1, self.y1 = cor1 self.x2, self.y2 = cor2 def distance(self): return sqrt((self.x2-self.x1)**2 + (self.y2-self.y1)**2) def slope(self): return (self.y2-self.y1)/(self.x2-self.x1) cor1 = (1, 9) cor2 = (9, 1) li = line(cor1, cor2) print(li.distance()) print(li.slope())
false
9575350130c5b3ab537803d810c046b1476ce15a
sanupanji/python
/practice_w3resource/17_range_1.py
321
4.125
4
''' Write a Python program to test whether a number is within 100 of 1000 or 2000. ''' def range_100(i): if abs(2000-i) <=100 or abs(1000-i) <=100: return f"{i} is within 100 of 1000 or 2000" return f"{i} is not within 100 of 1000 or 2000" print(range_100(int(input("enter the number: "))))
true
7a69dca389f3c11d5510094853957c57c87015ef
mafarah1/Debt-Visualizer
/Back-End.py
1,230
4.21875
4
import numpy as np #not used yet from matplotlib import pyplot as plt #plot the histogram #get more accurate salaries for better output major_dic= {"Communication": 45, "Business": 50, "STEM": 65, "Education ": 45, "MD":250, "MBA": 100, "Liberal Arts": 40, "Law" : 95} #Major Inforation #3 var... salary, debt, interst rate, year of graduation (depending on what the user puts in) #Histogram name = the key in dictionary #var which equal salary to major * increase #var which equal to debt * intreset ages = [10,20]# sample bin_edges = [0,10,20,30,40,50,60,70,80,90,100] plt.hist(ages, bins = 5, edgecolor ='black') plt.show() #x=years #y= money ''' def compute_histogram(self, image): """Computes the histogram of the input image takes as input: image: a grey scale image returns a histogram as a list""" hist = [0] * 256 X, Y = image.shape for x in range(X): for y in range(Y): hist[int(image[x, y])] += 1 return hist ''' # Make calculations for Charts.js # Total Debt = (Loan Amount * Interest Rate) + Loan Amount # How much does a student need to pay monthly? (the amount that covers the interest and principle)
true
97a431a9e9982489b04893a0881b834aa021027a
miiaramo/IntroductionToDataScience
/week2/exercise2.py
2,378
4.15625
4
import pandas as pd data = pd.read_csv('cleaned_data.csv') # First consider each feature variable in turn. For categorical variables, # find out the most frequent value, i.e., the mode. For numerical variables, # calculate the median value. mode_survived = data['Survived'].mode() print(mode_survived) mode_pclass = data['Pclass'].mode() print(mode_pclass) mode_sex = data['Sex'].mode() print(mode_sex) mode_embarked = data['Embarked'].mode() print(mode_embarked) mode_deck = data['Deck'].mode() print(mode_deck) mean_age = data['Age'].mean() print(mean_age) mean_sibsp = data['SibSp'].mean() print(mean_sibsp) mean_parch = data['Parch'].mean() print(mean_parch) # Combining the modes of the categorical variables, and the medians of the numerical # variables, construct an imaginary “average survivor” on board of the ship. # Also following the same procedure for using subsets of the passengers, # construct the the “average non-survivor”. # Now study the distributions of the variables in the two groups. # How well do the average cases represent the respective groups? # Can you find actual passengers that are very similar to the representative # of their own group (survivor/non- survivor)? Can you find passengers # that are very similar to the representative of the other group? # To give a more complete picture of the two groups, provide graphical # displays of the distribution of the variables in each group whenever # appropriate (not, e.g., on the ticket number). # One step further is the analysis of pairwise and multivariate relationships # between the variables in the two groups. Try to visualize two variables # at a time using, e.g., scatter plots and use a different color # to display the survival status. # Finally, recall the preprocessing that was carried out in last week’s exercises. # Can you say something about the effect of the choices that were made, # in particular, to use the mode or the mean to impute missing values, # instead of, for example, ignoring passengers with missing data? # 1. Since a lot of the passengers are missin data, I'd say ignoring those passengers # completely is not such a good idea (too little data). # 2. Only a small number of the passengers have info about the Cabin # (and thus the Deck) so I'd think it might be wiser to ignore the Cabin data.
true
9fedea164774065621c6b012c482e9951671ad0e
josephmorrisiii/pythonProject
/homework_two/lab_eight_one_zero.py
405
4.125
4
#Joseph Morris #1840300 def is_string_a_palindrome(user_string): new_string = user_string.replace(" ", "") if new_string == new_string[::-1]: print(user_string, "is a palindrome") else: print(user_string, "is not a palindrome") # Press the green button in the gutter to run the script. if __name__ == '__main__': user_string = str(input()) is_string_a_palindrome(user_string)
true
5ad84dd05506eb258699b0fcc596887b139c827b
AvanindraC/Python
/pig_latin.py
432
4.125
4
#Program to convert english to piglatin and vice verca def piglatin(data): a = str(data) a = a.lower() a = a + a[0]+'ay' a = list(a) a.remove(a[0]) a = ''.join(a) print(a) def english(data): a = data.lower() for i in range(1, 3): a = a[:-1] a = a[len(a)-1]+a[0:len(a)-1] print(a) piglatin("Hello_World") #output : ello_worldhay english("ello_worldhay") #output : Hello_World
false
ba4f1ce84993f2bb924fbfe2fd450da1508e7104
AvanindraC/Python
/conditionals 4.py
436
4.5
4
# Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged def string_conditional(string): if string.startswith('is'): print(string) else: # return 'Is' + string print('Is ' + string) string = str(input("Enter a sentence: ")).lower() res = string_conditional(string) print(res)
true