blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
47abb2cb7a63f713e2e3e6ef9f501cbaf080bfc0
12reach/PlayWithPython
/classes/fish.py
2,156
4.78125
5
#!/usr/bin/python3 # this is fish class and we will have some base classes from it class fishClass: pass class ChildFish(fishClass): print("Hi I am a child fish and I came from troubled water.") fan1 = ChildFish() print(fan1) # the output looks like thsi Hi I am Salman Khan and I am a fish from troubled w...
true
e8857f1f96a62700814b618a58e77c0a284b02c3
jzferreira/algorithms
/algorithms/sort/sorts.py
1,416
4.15625
4
from algorithms.helpers import generate_random_list def bubble_sort(elems: list) -> list: size_elems = len(elems) for i in range(size_elems - 1): for j in range(size_elems - i - 1): if (elems[j] > elems[j+1]): # troca elems[j], elems[j + 1] = elems[j + 1], e...
false
0f7c3256ea06e9ebc2ce49911531b2ded494fdc8
genesisazor/homework
/Chapter6/question3.py
408
4.25
4
def day_num(day_name): """takes a day name and returns a number 0-6""" if day_name == "Sunday": return 0 elif day_name == "Monday": return 1 elif day_name == "Tuesday": return 2 elif day_name == "Wednesday": return 3 elif day_name == "Thursday": return 4 ...
true
36b7883049cca2cb6cbeb6eb35f5ebf4bd6cabda
ddmin/CodeSnippets
/PY/Playground/strip.py
466
4.21875
4
import re def strip(string, chr = '\s'): """ Implementation of Python's Strip Method. Parameters: string (String): Target string. chr (String): Character(s) to strip. Defaults to whitespace character. Returns: String: A string with the ch...
true
1e4468fbb0a6bbcd95737b3edfc77e7c51299e55
yasir-web/pythonprogs
/recursion.py
202
4.25
4
#wap to find the factorial of given number using recurssion def fact(n): if n==0 or n==1: return 1 else: return n*fact(n-1) x=int(input("Enter the number: ")) f=fact(x) print(f)
true
c65d07396bfd58be933ca0edc17e9cbb02920471
yasir-web/pythonprogs
/hierarchial.py
503
4.46875
4
#WAP to demonstrate concept of hierarchial Inheritence class figure: def setvalue(self,s): self.s=s class square(figure): def area(self): return self.s*self.s class cube(figure): def volume(self): return self.s*self.s*self.s #Now we test the class sq=square() cu=cube() side=int(input...
true
3a238c088626cbea712db233924a841d90a616d2
Z3DDev/DatabaseManagement
/Assignment2/assign2.py
2,459
4.21875
4
# Zach Jagoda # Student ID: 2274813 # Student Email: jagod101@mail.chapman.edu # CPSC408 Database Management # Assignment 2: SQLite Lab import sqlite3 conn = sqlite3.connect('studentdb.db') c = conn.cursor() loop = 1 while loop == 1: print("Please Select An Option") text = input("1. Display All Stude...
true
7bbff704ba253fb8419225cf47ba7be3b17c15bb
nayyanmujadiya/ML-Python-Handson
/src/pandas/dict_to_pd.py
982
4.21875
4
import pandas as pd #dict is given sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000} obj3 = pd.Series(sdata) print(obj3) ''' When you are only passing a dict, the index in the resulting Series will have the dict’s keys in sorted order. You can override this by passing the dict keys in the order yo...
true
728c03ca26f01391b06c7ffed4708ff07bd9c2a1
nayyanmujadiya/ML-Python-Handson
/src/basic_index_np.py
688
4.34375
4
import numpy as np arr = np.arange(10) print(arr) print(arr[5]) print(arr[5:8]) # assign scalar to slice arr[5:8] = 12 print(arr) ''' An important first distinction from Python’s built-in lists is that array slices are views on the original array. This means that the data is not copied, and any modifications to the v...
true
64c894b1c64a64cfd791de76e4e17e99abda7750
nayyanmujadiya/ML-Python-Handson
/src/ml/baseball_mult_reg.py
2,785
4.125
4
#Step 1: Import libraries import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split ''' data source: https://college.cengage.com/mathematics/brase/understandable_...
true
c0fe2894662d81ae0bd815acee999bdc4b2684ed
rtduany/personal-development
/Insert.py
459
4.5625
5
# Dash Insert # Using python, have the function DashInsert(str) insert dashes ('-') between each two odd numbers in string. # For example: if str is 454793 the output should be 4547-9-3. Don't count zero as an odd number. def DashInsert(str): #first lets iterate thru the function for i in str: #turn the string to i...
true
139561d8c1b225843bee56fd00dd2e356894b021
macknilan/Cuaderno
/Python/ejemplos_ejercicios/caja_negra_testing.py
1,567
4.28125
4
import unittest def suma(num_1, num_2): return num_1 + num_2 class CajaNegraTest(unittest.TestCase): """Las pruebas de caja negra se basan en la especificación de la función o el programa, aquí debemos probas sus inputs y validar los outputs. Se llama caja negra por que no necesitamos saber necesar...
false
09c8ec2a5c0dc092337fa7337f399533d0f3cf7a
macknilan/Cuaderno
/Python/Code_examples/05_iterators/iterator_basics.py
1,581
4.34375
4
from dataclasses import dataclass @dataclass class Item: name: str weight: float def main() -> None: inventory = [ Item("laptop", 1.5), Item("phone", 0.5), Item("book", 1.0), Item("camera", 1.0), Item("headphones", 0.5), Item("charger", 0.5), ] i...
true
9a5fbf2c455e1e64e9e11bd6e56dba8ddef1c98a
macknilan/Cuaderno
/Python/ejemplos_ejercicios/palindromo.py
870
4.21875
4
# -*- coding: utf-8 -*- """palindromo.py""" def palindrome2(word): reversed_word = word[::-1] if reversed_word == word: return True return False def palindrome(word): reversed_letters = [] for letter in word: reversed_letters.insert(0, letter) reversed_word = "".join(reve...
false
edb0b8978dbc60c27acd9f164f0a763c1c953cd5
macknilan/Cuaderno
/Python/ejemplos_ejercicios/poo_abstract_base_classes_ejem_01.py
818
4.15625
4
# abstract base classes import abc class Vehicle(abc.ABC): """ Declaracion de la clase abstracta """ @abc.abstractmethod def go(self): pass @abc.abstractmethod def stop(self): pass class Car(Vehicle): """ Clase heredada de -Vehicle- ""...
false
41068a9aa46eb97b3cee209cef947c9f52538a54
harut0601/youtube-videos
/video2/problem3.py
459
4.25
4
temperature = int(input("The outside temperature: ")) unit = input("(C)elsius or (F)ahrenheit: ") if unit.upper() == "C": final_temperature = (temperature * 1.8 + 32) elif unit.upper() == "F": final_temperature = ((temperature - 32) * 5/9) else: print("Please try again!") final_temperature = "Not defin...
true
7ef4b9293d5060777f8d3a4b424c025e7d10180f
rajilaxmi/python
/functions/6.cases.py
450
4.34375
4
# to coount the number of uppercase and lowercase alphabet in a string def counting(str1): d={"upper":0,"lower":0} for c in str1: if c.isupper(): d["upper"]+=1 elif c.islower(): d["lower"]+=1 else: pass print "Number of uppercase alphabets: %d"%d["upper"] print "Number of lowercase alphabets: %d"%d["...
true
daa01efd4345099884bf2c7b6722ef029759ad8f
Alex760164/home_work
/home_work_30/home_work_30.py
1,226
4.28125
4
""" Имеется строка вида: AABABBAABBBAB. Необходимо написать функцию которая заменит буквы A на B, и B, соответственно, на A. Замену можно производить ТОЛЬКО используя функцию replace(). В результате применения функции к исходной строке, функция должна вернуть строку: BBABAABBAAABA Использовать циклы и оператор IF запре...
false
c7da4dd6f9fcf37b7189247eee9e0ceffd4903af
Sashagrande/Faculty-of-AI
/Lesson_1/task_3.py
224
4.125
4
n = input('Введите число ') a = (n, n * 2, n * 3) # для отображения "n + nn + nnn в ответе nn = int((n * 2)) nnn = int(n * 3) n = int(n) print(a[0], '+', a[1], '+', a[2], '=', n + nn + nnn)
false
a27469903e1dd03705ad938807acbfac708fe8c8
halasdhowre/TTA-halasdhowre
/HLT 3.py
2,237
4.15625
4
#################################Home Learning Task 3 #Q1 #Write a program that allows you to enter 4 numbers and stores them in a file called “Numbers” #• 3 #• 45 #• 83 #• 21 #Have a go at ‘w’ ‘r’ ‘a’ file_1 = open("GitHub/TTA-halasdhowre/Submitted HLT/Numbers.txt", "r") print(file_1.read()) file_1.close...
true
86f49db5f9e996f883c843ed8457b49dfd679963
KavitaPatidar/100DaysPythonCode_BeginnerLevel
/HangMan.py
869
4.1875
4
import random from design import word_list, logo, stages print(logo) word= random.choice(word_list) print(word) display=[] for letter in word: # or display+= "_" display.append("_") # print(display) guess_continue= True lives=6 while guess_continue: guess= input("guess a letter: ").lower() if guess...
true
50aaa7b8ea7b522fa3bdf039ac413149a0798500
choisoonsin/python3
/design_pattern/decorators/classmethod.py
697
4.375
4
class Person: population = 0 def __init__(self, name, age): self.name = name self.age = age Person.population += 1 @classmethod def get_population(cls): return cls.population if __name__ == '__main__': """ In this example, we define a Person class with a p...
true
6b84eabc00ee49c5a3334f182865ac48ed1d015e
JingYiTeo/2019_ALevel_CP_Notes
/Sorting/Bubble Sort (Not Optimized).py
714
4.21875
4
def bubble_sort(A): #assume not sorted swapped = True #while swapped: as long as its not swapped while swapped: swapped = False #for loop: iterate through all the elements from index 1 to end for i in range(1, len(A)): #if the previous element > elem...
true
95270ce3b015709f114eb1fda9eac6dbad6394a2
JingYiTeo/2019_ALevel_CP_Notes
/Searching/Binary Search.py
926
4.34375
4
#binary search needs the data/array/list to be sorted before it can search. def binary_search(elements, target, low, high): #define the middle item index mid = (high + low) // 2 if low > high: # not found return -1 #target is exactly in the middle of array elif elements[mid] == ...
true
f8809724342461be3a1269d8bc275ed4e1fa82c9
srusher/Python-for-Data-Science-and-Machine-Learning
/4. Pandas/6_Pandas_GroupBy.py
861
4.25
4
import numpy as np import pandas as pd from numpy.random import randn np.random.seed(101) # think of the GroupBy function in Pandas as the GroupBy clause in SQL ## In SQL: typically used for aggregate functions and returns values for each distinct row # Create dataframe data = {'Company':['GOOG','GOOG'...
true
15fe34a8bf17cad25a3d2c9af5d34abb2f23d96a
abhi8893/Intensive-python
/exercises/get_initials.py
757
4.15625
4
# Write a program that takes a full name, prints the initials of the first, # middle, and last name. If the middle name is “NA”, then the program # should print only the initials of the first and the last name. def get_initials(name): """ Return initials of first, last and middle name. If the middle na...
true
315d4db0cfcf49ba4a8ea2f389a91df1cf48d257
abhi8893/Intensive-python
/exercises/3D_to_2D_lists.py
1,097
4.5
4
''' Define a function that takes a 3-D list and converts it to a 2-D list in-place. ''' def get_2D(lst): """ Convert the list to 2-D in-place. my_list = [[['item1','item2']],[['item3', 'item4']]] >>> get_2D(my_list) [['item1', 'item2'], ['item3', 'item4']] """ lst = lst.copy() ...
true
df49417c2647d7e197a6965086c38432c65b69b3
abhi8893/Intensive-python
/exercises/conv_to_unqouted_str.py
791
4.125
4
# Convert a string such that it is not surrounded by quotes. def unquoted_str(s: str): '''Converts a string into an unquoted string''' # TODO: use regex # NOTE: Not requiring an s argument, as it seems cleaner # and also unneccesary if function is just for # internal consumption. ...
true
794ab61657f537357dcc1791d3bd1151d781e0ab
abhi8893/Intensive-python
/exercises/first_vowel_in_each_word.py
566
4.125
4
def find_first_vowel(S: str) -> str: """ Return the first vowel in each word of a string. >>> find_first_vowel("The sky's the limit") 'e, e, i' """ vowels = ['a', 'e', 'i', 'o', 'u'] words = S.split(' ') res = [] for w in words: for l in w: if l in vowel...
false
b9b2511443d106aaf24b70eacd9a46936ad55375
DRMPN/PythonCode
/CS50/ProblemSet6/dna/dna.py
2,496
4.15625
4
# program that identifies a person based on their DNA import sys import csv def main(): # correct usage check if len(sys.argv) != 3: sys.exit("Usage: python dna.py data.csv sequence.txt") # list of dictionaries database = [] # read people's dna from a database with open(sys.argv[1])...
true
f7f0310b9d3e118087b5695466303ba02e9057c7
CCG-Magno/Tutoriales_Python
/looping_sample.py
1,245
4.15625
4
def while_loop_example(): print("This is a while loop example...\n") i=0 while i < 5: print(f"[{i}] Hello world!") print() return def for_loop_example(): print('This is a for loop example...\n') for i in range(5): print(f"[{i}] Hello World!") print() return def loo...
false
e8493faf5241aba6e1e41f37fafc1588ab1647f1
leon541/Tom
/a-List.py
607
4.4375
4
def printList(list): print("----") for i in list: print(i) print("----") foods = ["apple","banana","pie","pear"] print(foods[2]) print("----") for x in foods: print(x) print("--append apple--") foods.append("apple") for x in foods: print(x) print("--remove pie--") foods.remove("pie") ...
false
58c4b69005958b9e0045fe641743d35de724104d
Hassan-Farid/PyTech-Review
/Python Intermediate/Sequences and Iterables/Naming Slices.py
2,775
4.28125
4
''' Assume that we want to extract a certain slice from a particular long list ''' #Suppose we are provided a large list with lots and lots of numbers and you want to get the sum of a particular bunch #We can take a random list of numbers using the random.randint() method and then sum the specified slices #Normally w...
true
74ca3e8d21e709ac9128421aaed93259e8081059
Hassan-Farid/PyTech-Review
/Python Intermediate/Sequences and Iterables/Implementing Priority Queue.py
1,794
4.375
4
''' Assume you want to implement a priority queue that sorts items in a queue based on their priority ''' #A priority queue is an ADT similar to a queue which functions the same way as a queue (FIFO order) but pops/deques elements based on priority #We will now create a class PriorityQueue and use another class Marks...
true
de812795776b9ea6083669adb85e0002bb8d7e27
Hassan-Farid/PyTech-Review
/Python Intermediate/Sequences and Iterables/Sorting List of Dictionaries using Common Key.py
1,298
4.40625
4
''' Assume you want to sort a list of dictionaries with one or more of its keys ''' #Suppose an institute conducts a test based on Maths and English marks and assigns positions to students based on their marks in these two subjects #Suppose we are provided a list containing the json data for the students and the marks...
true
fac8e73dca7850bef6a22dfc2794756083c10686
Hassan-Farid/PyTech-Review
/Python Basics/Iteration Statements/NestedLooping.py
1,713
4.5625
5
''' Sometimes a single loop is not enough for the application we have to peform, thus, we need to use loops within loops This use of loops within loops is known as Nested Looping and is quite used in application development ''' #Using nested looping to find a palindrome text = "level" isPalindrome = False for ...
true
237de905fac906dea8f4fd0439a4ebe71e79ab9c
Hassan-Farid/PyTech-Review
/Python Intermediate/Text Processing/String Matching using WildCard Patterns.py
1,777
4.25
4
''' Assume you want to match text using commonly used Unix wildcard characters ''' #Suppose a company has a list of different file formats and they want to obtain only the ones with .csv in the end #We can use the Unix wildcard pattern with the list of files using the fnmatch module #fnmatch provides functionaliti...
true
499bc6dc2a5430049a5002fd54df3afb4fbbfc95
DemonsHacker/learntf
/python/mo_fan/01_python3/02_if_else.py
219
4.21875
4
x = 1 y = 2 z = 3 if x<y: print('x is less than y') else: print('y is less than x') if x<y and y<z: print('x is less than y,and y is less than z') x = 2 y = 2 z = 0 if x == y: print("x is equal to y")
false
a7792b1a3a562cd2acca963f99822b16d0de629f
aggressiveapple5/problemSet0
/ps0.py
2,118
4.1875
4
#0 def is_even(number): ''' Takes user input and returns True if number is even and False if odd''' while number > 1: number -= 2 if number == 1: even = False else: even = True return(even) #1 def number_digits(number): '''Takes a non-negative number as input and returns the number of digits in the number'...
true
9687dd20d0579cb75056693ad133d32fded15488
rahulgupta020/bscit-practical
/4c.py
271
4.15625
4
#Write a Python program to clone or copy a list #Method1 original_list=[1,2,3,4,5] print("Original List = ",original_list) new_list=list(original_list) print("New List = ",new_list) print() #Method og=[6,7,8,9,10] print("OG = ",og) copy=og.copy() print("COPY = ",copy)
true
2351a19868108f4b61bd32fcf805f16ae0b6ae8e
eranandagarwal/callbacks
/more_callback.py
1,909
4.28125
4
import time def slow_calculation(cb = None): res = 0 for i in range(5): res += i * i time.sleep(1) if cb: cb(i) return res # what if we do not define a function for callback, instead use lambda for same slow_calculation(lambda num: print (f"Yay !! we hav...
true
ccee0cfb15b744983325e9557b73dfc55f99f63e
group6bse1/BSE-2021
/src/chapter3/exercise2.py
749
4.28125
4
#handling any errors that might occur during execution if user input is wrong try: # accepting Hours from user which is an integer hours = float(input('Please enter hours: ')) # accepting rate per hour from the user which is float value- rate = float(input('please enter rate :')) if hours > 40: ...
true
37613fa2186eaa07a55b0fbf99bf7164165fe78c
group6bse1/BSE-2021
/src/chapter2/excercise5.py
341
4.40625
4
# x is the temperature in degrees celsius to be input x = float(input('Enter temperature in \N{DEGREE SIGN}C :')) #y is the temperature in fahranheit # formula for computing the conversion y = (9/5)*x+32 print("Converting...", x, "\N{DEGREE SIGN}C to Fahrenheit") print("Temperature is: ", y, "\N{DEGREE SIGN}F") #prin...
true
a5a47ec2a87e4db6d6e284b99f6ae38ae5634d29
group6bse1/BSE-2021
/src/chapter3/exercise1.py
465
4.28125
4
#accepting Hours from user which is an integer hours = float(input('Please enter hours: ')) #accepting rate per hour from the user which is float value- rate = float(input('please enter rate :')) if hours > 40: #calculating the gross pay if hours worked are more than 40 pay = hours * (1.5 * rate) else: #calculati...
true
31e06eb0baf27a658a4637eff8fd38c5878d0d28
ariana124/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/6-print_sorted_dictionary.py
277
4.1875
4
#!/usr/bin/python3 """ Module that contains the function print_sorted_dictionary """ def print_sorted_dictionary(a_dictionary): """ prints a dictionary by ordered keys """ for key in sorted(a_dictionary.keys()): print("{}: {}".format(key, a_dictionary[key]))
true
ca3516edbf5c86ed923c27a7f870f43da53dc6f0
ariana124/holbertonschool-higher_level_programming
/0x03-python-data_structures/10-divisible_by_2.py
432
4.375
4
#!/usr/bin/python3 """ Module containing the function divisible_by_2 """ def divisible_by_2(my_list=[]): """ returns a new list with True or False, depending on whether the integer at the same position in the original list is a multiple of 2 """ new_list = [] for number in my_list: if number %...
true
4d2ee71bb0efbec3cdab08b8d4f04f88dad574d6
arya-hemanshu/algorithms
/merge_sort.py
1,387
4.375
4
""" A python implementation of merge sort, complexity of merge sort is O(NlogN) Args: unsorted array of numbers or letters Output: sorted array of number or letters How to use: python merge_sort.py <space seperated numbers or letters> """ def merge_sort(list_to_sort): if len(list_to_sort) == 1: ...
true
6465a846fcbb8d5f07f0e54f2a6069b0d0603e15
arthurDz/algorithm-studies
/leetcode/binary_tree_paths.py
670
4.125
4
# Given a binary tree, return all root-to-leaf paths. # Note: A leaf is a node with no children. # Example: # Input: # 1 # / \ # 2 3 # \ # 5 # Output: ["1->2->5", "1->3"] # Explanation: All root-to-leaf paths are: 1->2->5, 1->3 def binaryTreePaths(self, root): if not root: return def pa...
true
a0a67d39beea8a413918c846ebc0c188f8797a6c
arthurDz/algorithm-studies
/linkedin/binary_tree_upside_down.py
1,247
4.21875
4
# Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root. # Example: # Input: [1,2,3,4,5] # 1 # / \ #...
true
94ab33ed9269014316effea13fc61a468cbac5bb
arthurDz/algorithm-studies
/leetcode/valid_palindrome.py
502
4.1875
4
# Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. # Note: For the purpose of this problem, we define empty string as valid palindrome. # Input: "A man, a plan, a canal: Panama" # Output: true def isPalindrome(s): if s == "": return True s...
true
454abe0ec9c3efc65f263290f62d498ad6311a83
arthurDz/algorithm-studies
/leetcode/number_of_operations_to_make_network_connected.py
2,209
4.15625
4
# There are n computers numbered from 0 to n-1 connected by ethernet cables connections forming a network where connections[i] = [a, b] represents a connection between computers a and b. Any computer can reach any other computer directly or indirectly through the network. # Given an initial computer network connection...
true
204096f4c74c5445b2d154f8d086102530108a9d
arthurDz/algorithm-studies
/leetcode/display_table_of_food_orders_in_a_restaurant.py
2,957
4.46875
4
# Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders. # Return the restaura...
true
01232d78e27044360a9bc8d0cb3c3a8f158266f6
arthurDz/algorithm-studies
/linkedin/print_binary_tree.py
2,633
4.28125
4
# Print a binary tree in an m*n 2D string array following these rules: # The row number m should be equal to the height of the given binary tree. # The column number n should always be an odd number. # The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The colu...
true
f65a9d54eb9db6eb1b51e4b4732f3dcad8d65e34
arthurDz/algorithm-studies
/CtCl/Bit Manipulation/conversion.py
741
4.28125
4
# Conversion: Write a function to determine the number of bits you would need to flip to convert integer A to integer B. # EXAMPLE # Input: 29 (or: 11101), 15 (or: (1111) Output: 2 def conversion(num1, num2): count = 0 while num1 and num2: if (num1 & 1) ^ (num2 & 1) == 1: count += 1 ...
true
0778a363d71d0d111be0d516ca5368f76a439f32
arthurDz/algorithm-studies
/leetcode/path_with_minimum_effort.py
2,138
4.21875
4
# You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can mov...
true
bd332ff87b40738895782ee99864ea8b7142ed71
arthurDz/algorithm-studies
/amazon/most_common.py
2,449
4.21875
4
# Amazon is partnering with the linguistics department at a local university to analyze important works of English literature and identify patterns in word usage across different eras. To ensure a cleaner output, the linguistics department has provided a list of commonly used words (e.g., "an", "the", etc.) to exclude ...
true
a4b5e62a31da15b84ddef1a9fa93ceae17f41d45
arthurDz/algorithm-studies
/leetcode/subtree_of_another_tree.py
1,395
4.28125
4
# Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. # Example 1: # Given tree s: # 3 # ...
true
5e8dd2b8d5369f05f43d508e96517d7eea2cfede
arthurDz/algorithm-studies
/leetcode/N-ary_tree_level_order_traversal.py
872
4.1875
4
# Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). # For example, given a 3-ary tree: # We should return its level order traversal: # [ # [1], # [3,2,4], # [5,6] # ] # Note: # The depth of the tree is at most 1000. # The ...
true
6493d4b06546bc81380bb48ed82e1e01b791044c
arthurDz/algorithm-studies
/leetcode/reverse_string.py
617
4.25
4
# Reverse String # Write a function that reverses a string. The input string is given as an array of characters char[]. # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. def reverse_string(str1): i = 0 j = len(str1) - 1 while i...
true
e337a457a6c871894ffe9afa713297dc1c44fc3f
arthurDz/algorithm-studies
/leetcode/sort_colors.py
1,486
4.1875
4
# Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. # Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. # Note: You are not suppose to use the...
true
de1508b94a92598f03f91b60797d12fcf0d4edca
arthurDz/algorithm-studies
/leetcode/intersection_of_two_arrays_2.py
1,022
4.15625
4
# Given two arrays, write a function to compute their intersection. # Example 1: # Input: nums1 = [1,2,2,1], nums2 = [2,2] # Output: [2,2] # Example 2: # Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] # Output: [4,9] # Note: # Each element in the result should appear as many times as it shows in both arrays. # The res...
true
1cc2990421174b6a7161da1fbe745a8d3c73ca25
arthurDz/algorithm-studies
/bloomberg/insertion_sort_list.py
2,481
4.34375
4
# Sort a linked list using insertion sort. # A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. # With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list # Algorithm of Insertion Sort:...
true
0e6a395dff87b5199a26b8594f6920d6c3265f99
arthurDz/algorithm-studies
/linkedin/find_leaves_of_binary_tree.py
978
4.25
4
# Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty. # Example: # Input: [1,2,3,4,5] # 1 # / \ # 2 3 # / \ # 4 5 # Output: [[4,5,3],[2],[1]] # Explanation: # 1. Removing t...
true
fd27e4a692f2fa5a901f68b255bcca58bf830d36
arthurDz/algorithm-studies
/CtCl/Bit Manipulation/binary_to_string.py
572
4.28125
4
# Binary to String: Given a real number between 8 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR:' def printBinary(num): if num <= 0 or num >= 1: return "ERROR" init = '0.' ...
true
80624c401ab0cbc7c815b486db5f341432a97c71
arthurDz/algorithm-studies
/leetcode/largest_multiple_of_three.py
2,126
4.25
4
# Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. # Since the answer may not fit in an integer data type, return the answer as a string. # If there is no answer return an empty string. # Example 1: # Input: digits =...
true
462d331a410f7020f847e42ca27e4799f5041c34
arthurDz/algorithm-studies
/amazon/solve_the_equation.py
1,698
4.15625
4
# Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient. # If there is no solution for the equation, return "No solution". # If there are infinite solutions for the equation, return "Infinite solutions". # ...
true
16aa4d50a4366e29bddf4f01626e3db25fbd352d
adargut/CompetitiveProgramming
/BinaryTrees/Trie/trie.py
1,327
4.125
4
class Trie(object): def __init__(self): """ Represents root node. """ self.sons = {} self.val = None self.mark = False # means a word ends there def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: No...
true
f7451bae519ecb3dcb8a39c5b024bed4bee80f3f
clarizamayo/JupyterNotebooks
/Class Material/Week-07/script.py
1,847
4.21875
4
# from random import randint # class GuessingGame: # """ # max_guess = 3 # guesses = 0 # """ # def __init__(self): # self.max_guess = 3 # self.guesses = 0 # self.random_number = randint(1,3) # @staticmethod # def welcome_message(): # print("Welc...
true
90afb3429e48cb3102abd07693897319ba2a644f
singularitea/python-programming-exercises
/question_002.py
401
4.40625
4
# Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: # 8 # Then, the output should be: # 40320 print('Enter your factorial:') print('') f = input() fa = 1 if f == 0...
true
09aa834efc0a24c6edffa4bbd2b93305a3ce7e93
GiulianoSoria/CS50x
/pset6/sentimental/caesar/caesar.py
1,609
4.34375
4
from cs50 import get_string import sys # Converts into an integer the value entered as a key in the command-line k = int(sys.argv[1]) # Checks if the key is greater than zero if k > 0: # Prompts the user to enter the text that wants ciphered s = get_string("plaintext: ") print("ciphertext: ", end="") ...
true
76631622928186aff0efeb14c7b3f07175406a86
Michellecp/Python
/python_teste/meuprograma.py
2,301
4.21875
4
''' Módulo que contém a classe Entrevista Essa classe sera utilizada para instanciar e guardar cada Entrevista feita pelo programa, mais as entrevistas guardadas em disco. Os dados dessa instancia serão usados para fazer estatisticas. ''' from datetime import date class Entrevista(): '''Classe Entrevista''' ...
false
c6e27c4d4212035ac6a3161db72021e4443515ab
TheNoobProgrammer22/Birthday-Recorder
/main.py
718
4.34375
4
dict = {} while True: print("------------Birthday App----------") print("1.Show Birthday") print("2.Add to Birthday List") print("3.Exit") choice = int(input("Enter the choice")) if choice == 1: if len(dict.keys())==0: print("Nothing to show") else: ...
true
62b242b7c7a76663b380b7c8e29930db58c12149
Muhammed-Moinuddin/Python1
/beginner.py
2,679
4.25
4
a = int(input("Please enter first number: ")) b = int(input("Please enter Second number: ")) if a > b : print('{0} is the largest'.format(a)) else : print('{0} is the largest'.format(b)) #First input Positive or negative if a > 0 : print('{0} is Positive'.format(a)) else : print('{0} is Negative'.format(a)) #First...
true
47c1ef429d4b92e975304a5140678a7a7bea0bac
k18a/algorithms
/classical_algorithms/sort_insertion.py
1,718
4.5
4
""" insertion sort """ def insertion_sort(array, verbose=False): # define verboseprint function verboseprint = print if verbose else lambda *a, **k: None verboseprint('array to be sorted is {}'.format(array)) # iterate over unsorted array, first element is always sorted for unsorted_index, unsorted_...
true
7d3c4d3a9c5384f83bdb3468d686ec4731de7758
k18a/algorithms
/classical_algorithms/sort_radix.py
2,224
4.21875
4
"""" radix sort """ from sort_counting import counting_sort def radix_sort(array, verbose = False): # get array maximum maximum = max(array) # initialize exponent exponent = 1 # check if exponent is greater than max while exponent < maximum: # count sort array for the given exponent ...
true
917637e7e8823fbcf0d920386dd405dbed14843a
delta94/Code_signal-
/Arcade/Intro/Smooth Sailing/commonCharacterCount.py
498
4.3125
4
"""" Given two strings, find the number of common characters between them. Example For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3. Strings have 3 common characters - 2 "a"s and 1 "c". """" def commonCharacterCount(s1, s2): count = 0 for ch1 in s1 : line = s2...
true
26b8671c5e2844257179cf441f1152ac658d3d33
delta94/Code_signal-
/Arcade/Intro/Dark Wilderness/digitDegree.py
676
4.25
4
""" Let's define digit degree of some positive integer as the number of times we need to replace this number with the sum of its digits until we get to a one digit number. Given an integer, find its digit degree. Example For n = 5, the output should be digitDegree(n) = 0; For n = 100, the output should be digitDegre...
true
09c38e6dd37874bf0abaaec9b37c8cf37cc9c56c
delta94/Code_signal-
/Arcade/Intro/Dark Wilderness/bishopAndPawn.py
659
4.21875
4
""" Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move. The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move: https://codesignal.s3...
true
81b52cb363dea20d99e8fcf563ef763b8510df13
delta94/Code_signal-
/Arcade/Intro/Erruption of light/mac48Address.py
1,239
4.71875
5
""" A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment. The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens...
true
31d79443971ae591803b9bdefe61e8dc8c6fc129
delta94/Code_signal-
/Arcade/The core/Intro Gates/3. LargestNumber.py
325
4.15625
4
""" Given an integer n, return the largest number that contains exactly n digits. Example For n = 2, the output should be largestNumber(n) = 99. """ def largestNumber(n): p = 0 for i in range(n): if i != n-1: p += 9*(10**(n-i-1)) if i == n-1: p +=9 return p ...
true
1789d3e8b1376870bfe428e08381b26ce1b8fb21
nervig/Starting_Out_With_Python
/Chapter_2_programming_tasks/task_7.py
323
4.21875
4
#!/usr/bin/python covered_destination = float(input("Enter the covered destination: ")) fuel_consumption_in_liters = float(input("Enter the fuel consumption in liters: ")) fuel_consumption =float(fuel_consumption_in_liters / covered_destination) print("The fuel consumption of your car equals {}".format(fuel_consumption...
true
c596d5d929c58dc817516001ab4d759fd670b4ab
nervig/Starting_Out_With_Python
/Chapter_5_programming_tasks/task_1.py
280
4.125
4
def main(): distance = float(input("Enter a distance in kilometer: ")) distance_in_mile = kilometer_to_mile(distance) print("The distance in miles equals %f" % float(format(distance_in_mile, '.2f'))) def kilometer_to_mile(number): return number * 0.6214 main()
false
75d9f72c5c9b9a6108ba02b6fc63e6ef047058aa
nervig/Starting_Out_With_Python
/Chapter_6_programming_tasks/record_students_list.py
759
4.25
4
# creating a file and adding some records def main(): # create a variable for manage of cycle the_flag = 'y' # open the students.txt file in adding mode adding_students = open("students.txt", "a") while the_flag == 'y' or the_flag == 'Y': print("Enter an information are students about: ") ...
true
4e3c43805358f8cd12750a3ceb93535032198f90
DarishkaAMS/Py_Bootcamp_Task-COAX_Tryout
/question1_reversed_string.py
494
4.21875
4
#direct reversing s = "string" print(s[::-1]) #using length and slicing s = "string" reversed_s = s[len(s)::-1] print (reversed_s) #using function call s = "string" def reversing_function(x): return x[::-1] print(reversing_function(s)) #using join and reversed s = "string" s_reversed=''.join(reversed(s)) pri...
true
13c7e0cb44617fb8603a0bf69323009f1f69bc39
kanhaichun/ICS4U
/hhh/Alice/area caculation.py
2,177
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 15 13:27:35 2018 Program:Area Caculation purpose: (1) Find the area under y = sin(x) from x=0 to x = PI. (2) Find the area under y = 2^x from x = 1 to x = 10 (3) Find the area under a curve of your choice on a range of your choice. @author: haichunka...
true
221a34394fc4b1e0b84c55ba7ce76f2796a3d57c
kanhaichun/ICS4U
/Toxicbug/Tony/area calculator.py
1,482
4.25
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 16 02:25:04 2018 @author: 11256 """ #Name: Tony #Date: January 15, 2018 #Program Title: Area Calculator #Program Function: This program calcuates the area under curves (mathematical functions) from math import * #Variables: x = 0.0 #This is the starting x va...
true
5d4b9f87dc3c6f40d962c569eb6bc5cd2c77ddca
kanhaichun/ICS4U
/hhh/Angel/assignment9.py
2,969
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 5 12:40:11 2018 @author: hailankan (1) Create two functions: prime1(n) and prime2(n) that take a number that represents the set of integers from which to find prime numbers. For example, n=1000 specifies that the function will look for primes up to...
true
48bbcc29f747463ca19a87de64d90f71f8791d63
kanhaichun/ICS4U
/hhh/Angel/assignment4.py
1,540
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '''Name: Angel Kan Date: January 15, 2018 Program Title: Area Calculator Program Function: This program calcuates the area under curves (mathematical functions)''' from math import * #Variables: a = 0.0 #This is the starting x value b = pi #This is the ending x value n = ...
true
5daf8a269117a751e02d890c590b5c91bed7ec89
kanhaichun/ICS4U
/Shutupandbounce/Aurora/aurora2.py
1,062
4.125
4
ucn#(a)assignment2 """ Write a program that does the following: (a) Let the user input two numbers. (b) Convert the numbers to integers (c) Print the sum, difference, product and quotient of the numbers. (d) Repeat (b) and (c) for floating point (e) Convert the numbers to strings. (f) Output the four results as strings...
true
a064f2589130b5f59dd4cc65cc7283e5d8ad6cfa
kanhaichun/ICS4U
/hhh/Mark/assignment9.py
1,993
4.1875
4
# -*- coding: utf-8 -*- """ Name: Song, Jiwei (Mark) Date: 2018-02-06 Program Title: Benchmarking Algorithms Purpose: (1) Create two functions: prime1(n) and prime2(n) that take a number that represents the set of integers from which to find prime numbers. For example, n=1000 specifies that the function will look for ...
true
f091b967c81053bbe74c5c97bf464a8d25db7a38
kanhaichun/ICS4U
/FRC/intro.py
813
4.125
4
#This file is to introduce the basics of Python. from math import * from random import * #a and b are integer variables a = 5 b = 6 #numeric variables like integers can be used in #arithmetic expressions print(a+b) print(a-b) print(a*b) print(a/b) print(sin(a/b)+cos(b*a)) print(sqrt(b)) print(b**a) #friends is a tex...
true
31f54338963c78716d330fa64f177b69e02077da
kanhaichun/ICS4U
/hhh/Chris/Assignment 12.py
1,525
4.34375
4
# -*- coding: utf-8 -*- """ Assignment 12 - Recursive Algorithms - Towers of Hanoi Coding convention: (a) lower case file name (b) Name, Date, Title, Purpose in multiline comment at the beginning (c) mixedCase variable names (1) Create a class with functions for three recursive algorithms. Include factorials...
true
fb7b68c1f50ff3c5dfb13828c78920f607ef0852
kanhaichun/ICS4U
/Ivy232/Lily/A6Jan19.py
1,909
4.125
4
''' Assignment 6 - Program in a Class Coding convention: (a) assignment6 (b) Lily, Jan.18th 2018, Title, Purpose in multiline comment at the beginning (c) mixedCase variable names Option A - Make a more complete quiz program using a class structure (a) Have the program ask for the user's name. (b) Record the result...
true
6e5fc847fa9f80fb1634a70803b7df650d930d93
kanhaichun/ICS4U
/Toxicbug/Jeffrey/assignment1Jeffrey.py
428
4.25
4
""" Author: Jeffrey Date: 10th January 2018 Title: division Function: Loop through 1000 numbers, and find the numbers that are divisible by 3 or 19. """ #loop from 0 to 1000: for number in range(0,1000): if number%3 == 0: #find the number that is divisible by 3 print(number, "is divisible by 3.") elif...
true
890607721b60fc8994c44f9719116c96ca1d6def
mail2vels/VelsPythonCode
/2ndlargenumber.py
1,045
4.5625
5
print ''' 1. Write a program to implement a method which takes a list as an argument and returns second largest number. read from standard input and write to standard output. ''' print "Option 1" print "=========" print "To find Out Second Largest Number Using Array Sort" print '-----------------------------------...
true
1e116bc82ab891199eba6a54aead90d5fbc383ff
parkjuj/E02a-Control-Structures
/main10.py
2,213
4.28125
4
#!/usr/bin/env python3 import sys, random assert sys.version_info >= (3,7), "This script requires at least Python 3.7" print('Greetings!') # prints greetings! colors = ['red','orange','yellow','green','blue','violet','purple'] # defines what colors are play_again = '' # defines what the play_again variable is best_c...
true
97a2447fd0651a89a16a57a352c71bfe6e2cb56d
Swathi-Swaminathan/Swathi-Swaminathan
/allprograms/uppercase for first and last letter in a string.py
227
4.25
4
#Python program to display the first and last letter in a string in capital letters a=input("Enter the String:") a1=a.title() w=a1.split() r="" for i in w: r=r+i[:-1]+i[-1].upper()+" " print("New string:",r[:-1])
false
dbcf0f68a0fb99dd1ef6c1e4a96551b79d06a9d3
MaryemHaytham/AITasks
/task4.py
390
4.21875
4
#task4 num1 = float(input("Enter your first number : ")) num2 = float(input("Enter your second number : ")) operator = input("please Enter your operator : ") if operator == "+": print (num1 + num2) elif operator == "-": print (num1 - num2) elif operator == "/": print (num1 / num2) elif operator == "*": ...
false
2125a79698aa524b6fb99b27de5dcaad490d8667
LeoDemon/pythonlab
/PythonNow/src/Person.py
1,867
4.71875
5
# filename: Persion.py # learning python class class Person: '''Represents a person''' population = 0 def __init__(self, name): '''Initializes the person's data''' self.name = name print 'Initializing %s...' % self.name # When this person is created...
true
bbe1256760868f9de36b8bd7c1e4ab0f5622051b
lperri/CTCI-Practice-Problems
/chVI_bigO/examples/ex_10.py
983
4.375
4
# check if a number is prime by checking for divisibility on numbers less than it. # only need to go up to SQRT(n) because if n is divisble by a number greater than its SQRT, # then it is divisible by something smaller than it. from math import sqrt def is_prime(n: int) -> bool: ''' Use while loop ''' x = 2 ...
true