blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
8ba0151c763118c00a44ce643a4bd7f878f221fc
adam-weiler/Object-Oriented-Programming-Cat
/exercise2.py
2,490
4.125
4
class Cat(): #A Cat class. def __init__(self, name, preferred_food, meal_time): #Every Cat has attributes name, preferred_food, and meal_time. self.name = name self.preferred_food = preferred_food self.meal_time = meal_time def __str__(self): #Returns a meaningful string that describes ...
true
18fb93e24a538bbefc012acb783ff5ce549cefe3
efaro2014/Dojo-Assignments
/python_stack/python/oop/zoo.py
2,745
4.34375
4
# Start by creating an Animal class, and then at least 3 specific animal classes that inherit from Animal. # (Maybe lions and tigers and bears, oh my!) Each animal should at least have a name, an age, a health level, and happiness level. # The Animal class should have a display_info method that shows the animal's name,...
true
79a10afec2f3f60e085c8971fa218a4bc3e8d804
kirtleyk/608-mod4
/playing-craps.py
2,113
4.3125
4
""" File 2 - playing-craps.py (Sections 4.4, 4.5) In this file, we will use random functions to simulate chance events (rolling a pair of six-sided dice). Following the example provided in Section 4.4 "Rolling a Six-Sided Die 6,000,000 Times", create a simulation that rolls two dice 6 million times. Hint: On line 15, ...
true
bdf302241efcb85c6122a249d86320eea3b24595
colinkelleher/Python_Recursion
/Python_Recursion/Recursive_BinarySearch.py
1,009
4.28125
4
''' BinarySearchR(l ) Write a recursive version of the binary search algorithm that accepts a list. A template of the iterative version has been provided on Moodle. You can hardcode the list and the search term as in this template. Test with several inputs. Refer to the class notes to see how this search algorithm wor...
true
a6547353321718e64206c15165be538c2e84ab17
kickbean/LeetCode
/LC/LC_palinNum.py
1,200
4.3125
4
''' Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You could also try reversing an integer. However, if you have solved the pro...
true
be774f6a159367b8b26853906fa63e0bf6e9a0fd
kickbean/LeetCode
/LC/LC_searchInsertPosition.py
991
4.15625
4
''' Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 -> 2 [1,3,5,6], 2 -> 1 [1,3,5,6], 7 -> 4 [1,3,5,6], 0 -> 0 Created on Feb 1, 2...
true
cb8dfb385929adb1f76e43d98939e69e4b69b6d4
kickbean/LeetCode
/LC/LC_anagrams.py
1,011
4.15625
4
''' Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case. Created on Jan 12, 2014 @author: Songfan ''' ''' thoughts: hashtable where the key is the tuple (keyword, keyword occurance times)) time: O(n*k), n is the number of word in string list, k is the ...
true
1e8b4475a4373c23e94c56935582e063b5f53668
kickbean/LeetCode
/LC/LC_pathSum.py
1,731
4.15625
4
''' Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \...
true
0c94259d28d5ed9b708c43751697c2c74bb0185e
kickbean/LeetCode
/LC/LC_wordSearch.py
2,078
4.125
4
''' Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [ ["ABCE"], ["SF...
true
811a5335066542d111942f8c2261e92e55f3187d
Nancy027/ds
/Lesson4c.py
269
4.28125
4
# Loops - Repeating a task n-times # There are 2 types: while, for, do- while # WHILE LOOP x = 1 # starting, initialize while x <= 10: print('Its Looping', x) # any task ot be repeated 100000 times is put here x = x + 1 # every loop add 1 to x
true
67beb7e5a1989d9136b1c0ae7be87368ced6317f
dvega920/Module-Eight-Zybooks
/8.6.1:Defining_a_class_constructor.py
1,208
4.40625
4
# defines a PhonePlan object class PhonePlan: # init PhonePlan object with default params num_mins and num_messages def __init__(self, num_mins=0, num_messages=0): self.num_mins = num_mins # default param assigned to self.num_mins self.num_messages = num_messages # default param assigned to se...
true
4f789d8d989ed7396d8d528ad343e29205a81dd3
RianSama/sleepcalculator
/sleepcalculator.py
1,112
4.25
4
# Import modules import datetime # Have user define variables age = int(input("How many years old are you? ")) wake = int(input("At what hour would you like to wake? ")) lastmeal = int(input("How many hours ago did you last eat? ")) lastusage = int(input("How many hours ago did you last use a electronic device? ")) l...
true
7c89e10da1805c948e66c233479e62c201418c76
allensam88/Intro-Python-I
/src/14_cal.py
2,145
4.59375
5
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py [month] [year]` and does the following: - If the user doesn't specify any input, your program should ...
true
490d0a85e678aa00698f7283ad24cba6c2591e77
DSC-Aiktc/Hands-on-workshop-on-Opencv-and-python
/First Day/Loops and Condtion/exhandel.py
640
4.25
4
#EXCEPTION VS ERROR EXPLANATION #EXCEPTION EXAMPLE 1 a = 7 b = 0 print(a/b) #EXCEPTION EXAMPLE 2 print(c) ##TRY-EXCEPT #BY KNOWING THE EXCEPTION (PARTICULAR) #EXAMPLE 1 a = 7 b = 0 try: print(a/b) except ZeroDivisionError : print("CANNOT DIVIDE WITH ZERO!") #EXAMPLE 2 try: print(c) except NameError: print("VA...
true
70d4487ee67f99a4f8565fe0c2ecb69f86c3cb58
DSC-Aiktc/Hands-on-workshop-on-Opencv-and-python
/First Day/File Handling/filecw.py
2,562
4.6875
5
#THIS IS PROGRAM TO CREATE OR WRITE IN EXISTING FILE ''' To write to an existing file, you must add a parameter to the open() function: "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content To create a new file in Python, use the open() method, with one of the fo...
true
0291f6011de035ad44898aebfd710d540c3c6ff6
manisha-jaiswal/Python-program-example
/problem2.py
353
4.1875
4
#write a program who take input from user , when the input is >100 then print congratulation you give the number greater than 100 while(True): inp=int(input("Enter a number \n")) if inp>100: print("Congrats you have entered a number greater than 100 \n") break else: print("T...
true
386715d627293de01865b174085baabfcf1a99a6
mks-learning/intro-to-python
/savings.py
2,008
4.125
4
class Account: def __init__(self, acctNumber, balance): self.acctNumber = acctNumber self.balance = balance def __str__(self): retStr = "For account: " + str(self.acctNumber) + '\n' retStr += "the balance is " + str(self.balance) return retStr def deposit(self, amou...
true
34905f0b44ca1f16172660d38b2afa14594f39fe
mks-learning/intro-to-python
/factorial.py
320
4.34375
4
# create a function to calculate factorials def fact(number): product = 1 for i in range(1, number + 1): product *= i return product print('Please enter a number you would like the factorial of?') factnum = int(input()) print('The factorial of ' + str(factnum) + ' is ' + str(fact(factnum)) + '.')
true
fbf1063d433e72de73360cd325e2dec6d59c29cc
NihaalWagadia/LeetCode-Diary
/maxThreeNumbers.py
1,564
4.625
5
""" A script that requests three values from the user and then prints the maximum of the three values by calling your maxOfThree()* function. * The built-in Python function max() is not used. author: Fatih IZGI date: 13-Feb-2020 version: python 3.6.9 """ def maxOfThree(values: list) -> float: ...
true
2a700b16b9f2055d5d70fb66760883e1883c15de
jcom619/whiteboard-wednesday-greetings
/solution1.py
2,187
4.53125
5
# # The Problem You'll Be Interviewing Someone On # Make a `solution.py` that solves the following problem: given a string representing a language (we'll plan for "english", "spanish", and "french"), print out a greeting for that language (in this case: "Hello!" and "Hola!" and "Bonjour!"). # # Basic Run-Through ...
true
be3d2af2b9a05ec57d6a60432aff34ba1649ce98
vinodharani/PiToTheNthDigit
/finding_pi.py
218
4.25
4
import math def calculate_pi(num): return round(math.pi, num) try: num = int(input("Enter the N-th digit of Pi you want to know: ")) print(calculate_pi(num)) except ValueError: print("Invalid input")
true
2d960553d5a84154a10dcddf0149755853edc0e8
maftuhlutfi/pemrograman-visual-ti-uny
/Modul 5/5.1.11.7.py
226
4.15625
4
def isPalindrome(str): str = str.replace(" ", "") str = str.lower() rev = str[::-1] return "It's a palindrome" if str == rev else "It's not a palindrome" str = input("Enter text: ") print(isPalindrome(str))
true
dd159f24ed00c2ac22087654a68eefca8b8f2ca5
sneedlr/class_assignments
/HW2.py
1,868
4.40625
4
#AAAAAAAAAA #assign the values to a list values=[44, 64, 88, 53, 89] #assign the length of the list to a variable number=len(values) #assign the formula of the average to a variable using the list average=sum(values)/number #display the results print("the average of", number,"given numbers is: ", average) #ass...
true
b861ddd66302f94ec64d4b45eb0e791f7114eef8
joelcolucci/algorithm-toolbox
/week4/sorting/sorting.py
2,518
4.15625
4
# Uses python2 import sys import random # BAD # When we do this j could very well be # a repeated element! This means we swap # the same element to the end of array! # We now have to find a way to deal with # shifting matching elements # Flop j to k + 1 # If j is equal to pivot we are fine # If j is greater than p...
true
e1ac637f31ee8676443a94bd3878b2a6972959bd
dwivedys/intermediate-python-course
/sorter.py
396
4.15625
4
'''A Simple Sorting Program - sorts in ascending order testing comment by adding another line''' my_list = [1,3,2,9,7,22] l = len(my_list) for i in range(0, l): for j in range(i+1, l): if my_list[j] >= my_list[i]: continue else: swap_var = my_list[i] my_list[i] ...
true
5f5ec640db43258a0de453324e48fcf95618bf11
chubaezeks/Program-Arcade-Games
/Recursion.py
726
4.40625
4
# Controlling recursion levels def f(level): # print the level we are at print ("Recursion call, level", level) # If we haven't reached level ten... if level < 10: # Call this function again # And add another one to the level f(level + 1) # Start the recursive calls at level 1 f(1) #Non...
true
42fc2373ca1ed54db5eef05bc1aaf7c1ee2ca63a
ebinnicker/Programs
/Python/country_capital.py
1,378
4.34375
4
import csv import random #this portion of the code reads teh Country_capital.csv file and creates a list of capitals and list of countries file = open('Country_capital.csv') rows = csv.DictReader(file) capital = [] country = [] for r in rows: ca = r['Capital city'] capital.append(ca) co = r['Country'] ...
true
9984dcf52c07843266d941287b17565479173b9f
Dipali02/omniwish
/test1.py
812
4.15625
4
# Given an array and an integer K, find the maximum for each and every contiguous subarray of size k. # Algorithm: # 1)Create a nested loop, the outer loop from starting index to n – k th elements. The inner loop will run for k iterations. # 2)Create a variable to store the maximum of k elements traversed by the i...
true
c71eec305e0884ece1316cc405e7f4945d31f58a
MohamedSalahApdElzaher/Code_100_Python_Projects
/Intermediate Projects/main.py
1,051
4.1875
4
from turtle import Turtle, Screen import random screen = Screen() is_on = False screen.setup(width=500, height=400) user_predict = screen.textinput(title="Make Your Predict!",prompt="Which turtle will win the race ? Enter a color..") colors = ["red", "yellow", "orange", "blue", "green", "purple"] y_positions...
true
d21a5e9c6d372012b903f109f569d3df70ac5d4c
pragya16/AssignmentPython
/program9.py
361
4.1875
4
# Question 9: Define a function max_of_three() that takes three numbers as arguments and returns the largest of them def Largest(a,b,c): max = a if(b> max)and (b>c): max = b elif (c > max): max=c return max print Largest(1,6,13) ''' output: [root@...
true
0fa85bd378547f94de77405be61f80a577d63de2
LeoKuhorev/data-structures-and-algorithms
/challenges/queue_with_stacks/queue_with_stacks.py
1,318
4.21875
4
from data_structures.stacks_and_queues.stacks_and_queues import Stack class PseudoQueue: """Queue that uses two stacks""" def __init__(self): """Method initializer """ self.add = Stack() self.remove = Stack() def __len__(self): return len(self.add) + len(self.remo...
true
f3c3410c466f818e39013093fb5e22cc8e2f8a3f
ben-whitten/ICS3U-Unit-5-03-Python
/mark.py
2,703
4.3125
4
#!/usr/bin/env python3 # Created by: Ben Whitten # Created on: November 2019 # This is a program which converts your mark from number to percent. # This allows me to do things with the text. class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[9...
true
49d8c442c0a572a50f546de4325005960cf16094
sidmaskey13/python_assignments
/F13.py
299
4.21875
4
givenString = input('Enter string: ') def reverse_string(given_string): split_tuples = given_string.strip('[]') into_tuple_list = list(eval(split_tuples)) sorted_list = sorted(into_tuple_list, key=lambda x: x[-1]) return sorted_list print(reverse_string(givenString))
true
3a416af0aa447c3e345c0b9da5abc381f72e0159
IamSumitKumar/MLPractical26May-ScikitDatasets-
/ques2.py
2,496
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn import datasets # Write a program using Scikit Learn that utilizes Logistic regression to build a classification # model using all the four features to ...
true
49908d30cb93b18a630ffe1ed95db59bd7d73efc
xdc7/100DaysOfCode
/python/01/ch_07.py
2,411
4.53125
5
""" Write a function named displayInventory that would take any possible inventory and display it like the following #You are creating a fantasy video game. The data structure to model the player's inventory will be a dictionary where the keys are string values # #describing the item in the inventory and the value is...
true
6633b0ccaea9f600f67257c133bc746654694b32
xdc7/100DaysOfCode
/python/01/ch_11.py
1,694
4.53125
5
""" Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate.(Hint: The Fibonnaci seqence is a sequence of numbers where the next...
true
09029e4b0db0ae44db02b05648e484a59a2fbcc1
joshiprashanthd/algorithms
/graph_theory/shortest_path_DAG.py
919
4.15625
4
""" A useful application of Topological Sort is to find shortest path the having minimum weight to all the other nodes in the graph. """ import math from typing import Dict, Any from graph_theory.ds.graph import Graph from graph_theory.topoogical_sort import TopologicalSort class DAGShortestPath: def __init__(s...
true
007e316b493af1c32ea314513d21040fca0bc7e3
ds19-V/python_task
/Task_11.py
583
4.25
4
# merged list of tuples from 2 lists a = [1, 3, 5, 7, 9] b = [2, 4, 6, 8, 10] c = zip(a, b) print(f"The merged list is {tuple(c)}") # using zip, merge & range together a = range(1, 8) b = [11, 22, 33, 44, 55, 66, 77, 88] c = zip(a, b) print(f"The result is {tuple(c)}") # sort the list a = [100, 3637, 455...
true
25b531a3416a4468402eee332086a33cc4bec4c8
gbartomeo/lab_14_all_parts
/cake.py
569
4.25
4
""" cake.py ===== Write a program that asks for cake and handles a yes, no, or anything other than yes or no. It will say different things depending on the user's answer. Here's an example: Do you want cake? > yes Here, have some cake. Do you want cake? > no No cake for you. Do you want cake? > blearghhh I do not ...
true
edb2e9add839323772228d32b06d9143bd03c493
rishidhamija/pythoniffie
/highcard.py
1,614
4.1875
4
#!/usr/bin/python ###Written by Larry Walters larwal.dev### ###High card game### from time import sleep from random import randint, seed seed_value = randint(1,99) seed(seed_value) def computers_card(): comp_card = randint(1,13) return comp_card def players_card(): player_card = randint(1,13) return...
true
0c98196498a85d5f70a856e074d9c1397a4d62e0
nwilson314/python-datastructures
/Queues/LinkedListTail.py
1,398
4.28125
4
from LinkedList import LinkedList from Node import Node class LinkedListTail(LinkedList): ''' Implementation of a Linked List with a tail pointer. ''' def __init__(self): super().__init__() self.tail = None def push_front(self, val): ''' Adds val to the front of the linked list. ''' node = Node(val)...
true
08d36094e596c87bb2ea9f95b30e224fdbf811e5
oleksandriegorov/sorting_algorythms
/bubblesort.py
837
4.21875
4
#!/usr/bin/env python3 import os # Bubble Sort algorythm implementation # with 2 enhancements: # 1. Do not try sorted part during next traversal # 2. Exit if array is already sorted # Idea 1: compare bubble up and bubble down traversals # Idea 1.1: print number of swaps for bubble up/bubble down # Idea 1.2: arbitrary...
true
83ddf067f8b2b940f3f5822adf957a3ac181117d
kezzayuno/summerTutoringSolutions
/rockPaperScissorsVer1.py
659
4.375
4
import random choiceWinDict = {'rock': 'scissors', 'paper': 'rock', 'scissors': 'paper'} # value is what they win against computerChoice = random.choice(list(choiceWinDict.keys())) choice = input("Pick Rock, Paper, or Scissors > ") while choice.lower() not in choiceWinDict.keys(): choice = input("That is not a ...
true
c23cbfc824361321aa9f47cad00dce1cac84cb7b
K-Rdlbrgr/hackerrank
/String Manipulation/Sherlock and the Valid String/sherlockstring_solution.py
1,499
4.15625
4
# First we import defaultdict from collections from collections import defaultdict def isValid(s): # Using the Counter function to count all appearances of every character within the string count = Counter(s) # Counting the frequencies of all the appearances within the string freq = Counter(count.valu...
true
c9b73254d3a81b4bd087320b960d8d761d65fa74
TateAbhijeet/project_euler
/mylib.py
740
4.125
4
def fibonacci(limit): result = [] a, b = 0, 1 while a < limit: a, b = b, a + b result.append(a) return result def fibonacci_generator(limit): a, b = 0, 1 while a < limit: a, b = b, a + b yield a def get_primes(count=10, limit=0): primes = [2, 3] num = ...
true
6dda6ae16af3ff226b659071f10f7fb9446660ce
Milad-A-IT/python-co
/lab3.py
2,376
4.4375
4
#=========iteration labs from slides================ #Q1 #for i in range(5): # print(i) #i = 0 #while i<8: #print(i) #i = i + 1 #i += 1 #Q2 #x = 0 #while(x < 100): # x+=2 # print(x) #Q3 #If n is odd, print Weird #If n is even and in the inclusive range of 2 to 5, print Not Weird #If n is even and ...
true
22ea9c59a0da1feffae582480a566b5df316a897
farhanpro/Python_Workshop
/Comparision/Comparision.py
249
4.15625
4
age = int(input("Enter you age to place your Vote : ")) if age >= 18: print("You are Eligible to place your vote. ") elif age <= 18: print("You are Not Eligible to place your vote. ") #elif age < 0 : # print("Negative number inserted.")
true
f37354e489aa3061f9cfe1091c1ab240d37370ad
farhanpro/Python_Workshop
/Numpy/indexingandslicing2D.py
443
4.1875
4
import numpy as np x = np.arange(25).reshape(5,5) print(x) print(x[3,2])#Will print the element which is in 3rd row and 2nd position starting from 0 print(x[2:5,1:4])#Slicing will print elements which are in 2ndrow till 5throw and 2ndcolum and 5colum print(x[0:3,0:3])#will print elements which are in 0row till 2ndrow ...
true
827a4237d67f6366a98ce940d2d3c2dbabf90eb9
ShubhangiDabral13/Data_Structure
/Trees/01).Tree_insert.py
1,549
4.15625
4
""" Insertion of a value A new value is always inserted at leaf. We start searching a value from root till we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node. 100 100 / \ Insert 40 / \ 20 ...
true
d26c6d4eb76c5716209a6e7d907def0546ab3b1b
ShubhangiDabral13/Data_Structure
/Bit Manipulation/03).Power Of Two Or Not/03).PowerOfTwo.py
695
4.5625
5
""" iven a positive integer, write a function to find if it is a power of two or not. Note:- A number which is a power of two will always have one as set bit. """ #Function to count the number of set bits of an integer in binary form. def count_bits(n): count = 0 while(n): count += n & 1 ...
true
112758d2d47d65817afaa8c196580150d91c127f
ShubhangiDabral13/Data_Structure
/Competitive-coding-and-DS-Krish-Naik/Competitive-Coding-02.py
678
4.1875
4
""" Given digit = 7,bits = 3 output = 111 Given digit = 7,bits = 4 output = 0111 Given digit = 7,bits = 2 ouput = error """ digit = int(input("Enter the digit")) bits = int(input("Enter the number of bits")) #bin is an inbuilt function to convert decimal to binary #binaryForm=bin(digit)[2:] #Function to generate bin...
true
79bd1fae6f4316f7c532975c66af0a68e71df6e0
ShubhangiDabral13/Data_Structure
/Linked List/Linked_List_Delete_For_Given_Value.py
2,080
4.1875
4
""" Given a value, delete the first occurrence of this value in linked list. To delete a node from linked list, we need to do following steps. 1) Find previous node of the node to be deleted. 2) Change the next of previous node to the next of given node . 3) Free memory for the node to be deleted. """ class N...
true
5c832d48580c25296e69bca947595caf6c7f0ef9
ShubhangiDabral13/Data_Structure
/Trees/02).Tree_search_value.py
1,500
4.21875
4
#class that represents an individual node in a BST class Node: def __init__(self,value): self.right = None self.left = None self.value = value #function to insert a new node with the given value def insert(root ,node): if root is None: root = node else: i...
true
fa2b7deee3d6c8e7f95314b642b58c947b01d723
stgleb/problems
/python/array/array_shift.py
1,216
4.4375
4
""" A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times...
true
22ccc6c7cae397e9893393ddcf053a613211a999
stgleb/problems
/python/tree/root_to_leaf.py
645
4.125
4
from python.tree.node import Node def root_to_leaf(root, parent): root.parent = parent if root.left is None and root.right is None: result = [root.value] while parent: result.append(parent.value) parent = parent.parent print result if root.left is not No...
true
1ff98ce5b5c9e52315bda03c6088bafd80cc3569
bssrdf/pyleet
/M/MinimumSpeedtoArriveonTime.py
2,988
4.15625
4
''' -Medium- *Binary Search* You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of th...
true
4af5c9536871147e666b5de8134c235ae580b476
bssrdf/pyleet
/S/SmallestStringWithSwaps.py
2,137
4.125
4
''' -Medium- You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexicographically smallest string that s can be cha...
true
cbab784943b4e6308bd46fdab1f22f25c38335b8
bssrdf/pyleet
/P/PrintWordsVertically.py
1,291
4.1875
4
''' -Medium- Given a string s. Return all the words vertically in the same order in which they appear in s. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one wor...
true
548bd0c95c9774f2920849080ee3229c9b8cf9ad
bssrdf/pyleet
/C/CheckCompletenessofaBinaryTree.py
2,907
4.15625
4
''' -Medium- Given the root of a binary tree, determine if it is a complete binary tree. In a complete binary tree, every level, except possibly the last, is completely filled, 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. Example...
true
3f3d3eea940559b8cf34406bf9a85b59dbcec623
bssrdf/pyleet
/R/RemovingStarsFromaString.py
1,309
4.28125
4
''' -Medium- 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 alway...
true
ed10ef5fae28bcec31141eea918f7fd030a40bea
bssrdf/pyleet
/L/LargestNumberAfterMutatingSubstring.py
2,043
4.375
4
''' -Medium- *Greedy* You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d]. You may choose to mutate a single substring of num. To mutate a substring, re...
true
dcd6ddea73fdd1cf6435600e415f46e1a94ce20e
bssrdf/pyleet
/S/SumofImbalanceNumbersofAllSubarrays.py
2,643
4.125
4
''' -Hard- The imbalance number of a 0-indexed integer array arr of length n is defined as the number of indices in sarr = sorted(arr) such that: 0 <= i < n - 1, and sarr[i+1] - sarr[i] > 1 Here, sorted(arr) is the function that returns the sorted version of arr. Given a 0-indexed integer array nums, return the sum...
true
f07dd83f70b920fae3867973a3d107bc023e643a
bssrdf/pyleet
/L/LinkedListinBinaryTree.py
2,434
4.1875
4
''' -Medium- *DFS* *Recursion* Given a binary tree root and a linked list with head as the first node. Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False. In this context downward path means a path that star...
true
42d08c4ede39fd4ebfe8c8c9f308f26a6e0754a5
bssrdf/pyleet
/S/SentenceScreenFitting.py
2,294
4.125
4
''' -Medium- Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. Note: A word cannot be split into two lines. The order of words in the sentence must remain unchanged. Two consecutive words in a line must be separate...
true
ad0d27e392f0368fbf41bf4a4c80c9d7d7917a9c
bssrdf/pyleet
/M/MaximumSubarray.py
1,509
4.125
4
''' -Easy- *Two Passes* *DP* *Kadane's Algorithm* Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. ''' import sys class Solution(object): def...
true
1b51c5b72485689834841c0f79e3551bee5c46ff
bssrdf/pyleet
/R/ReduceArraySizetoTheHalf.py
1,887
4.25
4
''' -Medium- *Sort* *Greedy* Given an array arr. You can choose a set of integers and remove all the occurrences of these integers in the array. Return the minimum size of the set so that at least half of the integers of the array are removed. Example 1: Input: arr = [3,3,3,3,5,5,5,2,2,7] Output: 2 Explanatio...
true
0e94a63bb9902648b8b6b1e4dad35015cbd2e2d6
bssrdf/pyleet
/M/MaximumXORAfterOperations.py
1,885
4.125
4
''' -Medium- You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x). Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation. Return the maximum possible bitwise XOR of al...
true
f046162bffb6715cc89d3ca0e86d26c6bc7b719c
bssrdf/pyleet
/S/ShuffleAnArray.py
2,048
4.21875
4
''' -Medium- Given an integer array nums, design an algorithm to randomly shuffle the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the integer array nums. int[] reset() Resets the array to its original configuration and returns it. int[] shuffle() Returns a random shuffling o...
true
77862f56126d76e246326ad2e13e430ac13a5ffd
bssrdf/pyleet
/B/BinaryTreeUpsideDown.py
1,751
4.125
4
''' -Medium- 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. 样例 Example1 Input: {1,2,3,4,5} Output...
true
1c5c8a397e4edd56301b2414bcd26b721e8e744e
bssrdf/pyleet
/M/MaximumBuildingHeight.py
2,867
4.15625
4
''' -Hard- *Math* You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n. However, there are city restrictions on the heights of the new buildings: The height of each building must be a non-negative integer. The height of the first building must be 0. The...
true
25e993873c70d6e22cdf9f0db5f5480a0086c35c
bssrdf/pyleet
/R/ReorderedPowerof2.py
1,078
4.125
4
''' -Medium- Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero. Return true if and only if we can do this in a way such that the resulting number is a power of 2. Example 1: Input: 1 Output: true Example 2: Input: 10 ...
true
773d42058fae9aae00d86b717ff8aa5ac5296465
bssrdf/pyleet
/C/CountPrefixesofaGivenString.py
1,254
4.15625
4
''' -Easy- You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters. Return the number of strings in words that are a prefix of s. A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of character...
true
58da33017fd50ed4fba1b70336248cc1b804437b
bssrdf/pyleet
/M/MinimumNumberofFlipstoMaketheBinaryStringAlternating.py
2,529
4.53125
5
''' -Medium- *Sliding Window* Minimum Number of Flips to Make the Binary String Alternating You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove the character at the start of the string s and append it to the end of the string. Type-2: P...
true
d2643c9e0e325323dd687d1af94e7a422da14d4c
bssrdf/pyleet
/C/ComplexNumberMultiplication.py
1,219
4.25
4
''' -Medium- A complex number can be represented as a string on the form "real+imaginaryi" where: real is the real part and is an integer in the range [-100, 100]. imaginary is the imaginary part and is an integer in the range [-100, 100]. i2 == -1. Given two complex numbers num1 and num2 as strings, return a string...
true
b7665c098776bdc0c28384d29714e24f7ccdd42f
bssrdf/pyleet
/S/SwapForLongestRepeatedCharacterSubstring.py
2,370
4.25
4
''' -Medium- *Sliding Window* Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters. Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a...
true
af0b3a0375750e524f60cb7a9e5a7efa46b97cf2
bssrdf/pyleet
/M/MinimizedMaximumofProductsDistributedtoAnyStore.py
2,724
4.125
4
''' -Medium- *Binary Search* You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type. You need to distribute all p...
true
d50b86f7bc198dc08788662906e4ffc9e9d3c61c
bssrdf/pyleet
/D/DiameterofBinaryTree.py
1,788
4.25
4
''' Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. ''' ans = 0 # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None s...
true
c474da948abc995acdf68ab2afc846b28c72f915
bssrdf/pyleet
/L/LexicographicallySmallestBeautifulString.py
1,974
4.15625
4
''' -Hard- *Palindrom* A string is beautiful if: It consists of the first k letters of the English lowercase alphabet. It does not contain any substring of length 2 or more which is a palindrome. You are given a beautiful string s of length n and a positive integer k. Return the lexicographically smallest string...
true
13440b5abbbc2bb05af2f1669bdadb8bc8d31a46
bssrdf/pyleet
/S/SumofSubsequenceWidths.py
1,273
4.34375
4
''' -Hard- *Math* *Sorting* The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7. A subsequence is a seq...
true
cfe4c12ce7ddf891b792bfd99a116c9902a9ff5f
bssrdf/pyleet
/M/MinimumNumberofFrogsCroaking.py
1,677
4.21875
4
''' -Medium- You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid "croak" ...
true
70371ea4fb61652aa1c57128a5a622e750fda790
bssrdf/pyleet
/B/BiasedCoin.py
1,203
4.28125
4
''' -Medium- This problem was asked by Square. Assume you have access to a function toss_biased() which returns 0 or 1 with a probability that's not 50-50 (but also not 0-100 or 100-0). You do not know the bias of the coin. Write a function to simulate an unbiased coin toss. ''' import random class BiasedCoin(ob...
true
583750ca208dcd12fdeb9d068ae58077f33b8c4f
bssrdf/pyleet
/M/MinCosttoConnectAllPoints.py
1,917
4.15625
4
''' -Medium- *Union Find* *Kruskal's Algorithm* *Minimum Spanning Tree* You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, wh...
true
627a542eb410facb6c0f3dea6705ae7aaf31f1e0
RavenJoo/comp1021
/Guessing game.py
605
4.34375
4
import random target = random.randint(1, 100) #Generate a random number from 1 to 100 finished = None #None = false; initial boolean control for the while loop ''' The game starts here. You guess the number that was generated at the beginning There will be prompts to tell you if the guessed number is higher or lower...
true
367fda3915bbb8b7e8afcf778013af19a9e1ecd2
tony-tomy/100daysofcode
/Python/list_sets.py
863
4.4375
4
#!python3 # List : A list is a collection which is ordered and changeable. In Python lists are written with square brackets. thislist = ['Apple','Banana','Cherry'] print(thislist) print(thislist[1]) print(thislist[-1]) thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5...
true
abd5e2a91f9595068f0f68e3db8b2bae66ba18d5
mashworth11/LearningFromData
/Learning from Data/Homework 2/coinFlip.py
2,073
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 22 14:20:08 2019 @author: markashworth """ """ Program to be used to answer the Hoeffding inequality question (Q1) and (Q2) from Homework 2 of the learning from data course """ import numpy as np class coinFlipExperiment(object): def __init__(...
true
021aacd964ac1c5b7e9157e26c509fd209b802ee
Agumonn/Python-script
/5-5.py
1,059
4.15625
4
''' Exercise 5-5: Student sorting Sorting Student objects in the list Create an Student class with the properties * name and * grade properties Then add some students into the list and sort these students using their age and grade properties. class Student: # name, grade student_list = [Student('jim', 4),Stud...
true
d3784ab06f11895a07fb316f5d916664b279ef11
Agumonn/Python-script
/4-5.py
980
4.15625
4
''' fixed minor typos 9.2 4-5) Simulate the shop queue Add new persons to the queue from the list and serve them in "shop queue": # initialize list with the values clients=['first', 'second', "third", "fourth", "fifth"] queue=[] # to do - serve a client and then remove them from the queue # add new clie...
true
40f6ba04cbed44ba859e3a45370f3428a870c755
koltpython/python-contests
/OnlineContests/1/student_description.py
1,379
4.5625
5
name = input() surname = input() major = input() year = input() # There are many ways to print with the format given in description # Hi, I'm Jane Doe. I'm studying Sociology for 3 years. # Idea 1: remove seperation and list elements as you like print('Hi, I\'m ', name, ' ', surname, '. I\'m studying ', major, ' for ...
true
864e36deaa37d5516e091beca8b7480cb23c0d5c
CFEsau/learnpython
/ex03.py
907
4.40625
4
# Print what you want to do print "I will now count my chickens:" # Find and print the number of hens print "Hens:", 25 + 30 / 6 # Find and print the number of roosters print "Roosters:", 100 - 25 * 3 % 4 # State the next task print "Now I will count the eggs:" # Calculate this expression and print the reult print 3...
true
6f02cb6349f29842a7b541b115191f15d1bd72be
Cperbony/intensivo-python
/cap4/exercise_4.py
597
4.15625
4
for value in range (1, 20): print(value) one_million = list(range(1, 10000)) print(one_million) print(min(one_million)) print(max(one_million)) print(sum(one_million)) odd_numbers = list(range(1, 20, 2)) print(odd_numbers) multiple_of_threes = list(range(3, 31, 3)) print() print("List of multiples of 3") for nu...
true
0c512083e52914c602ff6bd394d937dee9e959f4
JMCD2000/2017_learning
/jmBugs.py
2,410
4.53125
5
#! python3 # Program name: jmBugs.py # Author: Jonathan McDonald # Date last updated: 3/08/2017 # Purpose: This program takes the number of bugs collected each day and returns the total number collected. # Initialize My Variables # ##total_bugs As Int total_bugs = 0 ##bugs_today As Int ##day_counter As Int ...
true
4bde2cbebe2f85a27ada43eaee6a557c6158c619
shakti001/Python-Codes
/day2/intersection.py
492
4.28125
4
#This is list which is called mylist.. mylist=[1,3,6,78,35,55] # This is another list which is called yourlist yourlist=[12,24,35,24,88,120,155] # this is a empty list.. intersect_list=[] print("Mylist is =",mylist) print("Your List is =",yourlist) print("intersection of mylist and your list is=") #This is a for loop.....
true
911ca5ed10acc5182a0c703a5b889dd15f50ca0f
shakti001/Python-Codes
/shopping list/shopping application.py
1,739
4.5
4
# Name # This is a list.. shopping_list = [] #this is print section.. print("what should we pick up at the store ?") print("Enter 'DONE' to stop adding items,") while True: # ask for new items new_item = input("> ") # be able to quit the app if new_item == 'DONE': break # add new items...
true
a475ebcd6e1e5015452ace538866a31351918853
rajtilakls2510/PythonDataStructures
/stack.py
1,927
4.125
4
from exceptions import EmptyStackException class Stack: # This is the Stack Data Structure # TODO: Add Search Method # Storing the contents of the stack in a list __items = [] def __init__(self): self.__items=[] def push(self, *items): # Parameters: send any number of ite...
true
5c363d4974dc6ee8d7daccc98ea9dc8b810ff876
vidisha-2/python_stack
/python_fundamentals/Functions_BasicII.py
1,436
4.375
4
'''Countdown - Create a function that accepts a number as an input. Return a new array that counts down by one, from the number (as arrays 'zero'th element) down to 0 (as the last element). For example countDown(5) should return [5,4,3,2,1,0]. ''' def countdown(x): for idx in range(x,-1,-1): print(idx) countdown(5)...
true
dfdb65d7fa9d480934bcda07871bed06e3cebb32
Akashrp512/Placement-Materials-CSE
/OOPS in Python/Overloading.py
2,036
4.4375
4
""" Polymorphism : 1. DuckTyping 2. Operator Overloading 3. Method Overloading (No Method Overloading in Python ) - Can achieve using Default args or using variable length args def over(self,*args) or def over(self,a=None,b=None,c=None) 4. Method Overriding ...
true
bf9da4857b4100fea9688594e1c69f4827508e6a
greenOrangge/Caesar_Cipher
/caesar_cipher.py
1,734
4.21875
4
import string from time import sleep # abcdefghijklmnopqrstuvwxyz alphabets = string.ascii_letters # function that encrypts the message def encrypt(): text_to_encrypt = input("Enter the text you want to ENCRYPT:") print() key = int(input("Enter the encryption key: ")) encrypted_mess...
true
9d0faa6d0b8b15280cbca2176f1d14a5cdfe30c8
Rasgacode/codecool_tasks
/Cincinek/task_1.py
1,793
4.125
4
import random def choose_random_word(list_of_words): return random.choice(list_of_words) def get_input(instruction): while(True): input_ = input(instruction) if len(input_) != 1 or any(character.isdigit() for character in input_): print("Wrong input!") else: r...
true
3745f30adedea7e9bf2393f85ae024f62b76e920
AkiraKane/CityUniversity2014
/Useful_Scripts/Remove_Punctuation.py
259
4.25
4
import string list1 = ['da"!!!n', 'job??', 'dan#][ny'] def punctuationWord(x): # Remove Punctuation from Word for letter in string.punctuation: x = x.replace(letter, '') return str(x) for word in list1: print punctuationWord(word)
true
4297ef538996a882d6259bb9143cb70b6dc3d179
samant-samir/Python_Projects
/DiceRollingSimulator.py
569
4.1875
4
import math import random import time min = input("Enter minimum value for dice") max = input("Enter maximum value for dice") answer = "yes" while (answer.lower() == "yes"): print("DICE is rolling..") time.sleep(2) print ("Outcome: ") print(random.randrange(int(min), int(max))) flag = 1 while...
true