blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
73febf1c1bf6a8d35dc50afbedd76b2df8bb2da4 | RohanNankani/Computer-Fundamentals-CS50 | /Python/mad_lib_theatre.py.py | 2,357 | 4.25 | 4 | # Author: Rohan Nankani
# Date: November 11, 2020
# Name of Program: MadLibTheater
# Purpose: To create a mad lib theater game which ask user for input, store their input using list, and print the story.
# Intializing the list
grammar = []
# List of prompts that describe the category of the next word
# to be substit... | true |
17856f57c910a767dfc433a16fbe31b365e3e870 | sp3arm4n/OpenSource-Python | /assignment_01/src/p10.py | 364 | 4.46875 | 4 | # step 1. asks the user for a temperature in Fahrenheit degrees and reads the number
number = float(input("please enter Fahrenheit temperature: "))
# step 2. computes the correspodning temperature in Celsius degrees
number = (number - 32.0) * 5.0 / 9.0
# step 3. prints out the temperature in the Celsius scale.
... | true |
45497bbe4e6c706c4f79e8be82bc586cc78331e3 | DarkCodeOrg/python-learning | /list.py | 288 | 4.21875 | 4 | #!/bin/python python3
""" creating an empty list and adding elements to it"""
list = []
list.append(200)
list.append("salad")
list.append("maths")
print(list)
print("this is your initial list")
new = input("Enter something new to the list: ")
list.append(new)
print(list)
| true |
192af36327e7984ba16c57dac945182bc92de21a | 2u6z3r0/automate-boaring-stuff-with-python | /inventory.py | 1,171 | 4.1875 | 4 | #!/usr/bin/python3
#chapter 5 exercise
stuff = {'gold coin': 42, 'rope': 1}
def displayInventory(stuff):
'''
:param stuff: It takes a dictionary of item name as key and its quantity as value
:return: Nothing, but it prints all items and respective quantity and total quantity(sum of all itmes qty)
'''
... | true |
a767fd70f5fedac106f3aca0b8b48b41d38a2a8e | NATHAN76543217/BtCp_D00 | /ex03/count.py | 1,005 | 4.28125 | 4 | import string
def text_analyzer(*text):
"""
This function counts the number of upper characters,
lower characters, punctuation and spaces in a given text.
"""
if len(text) > 1:
print("ERROR")
return
if len(text) == 0 or isinstance(text[0], str) == 0:
text = []
t... | true |
cf2553bafad225366a58d08ab9a8edc6b4daa9d2 | Ayush900/django-2 | /advcbv2/basic_app/templates/basic_app/pythdjango/oops.py | 807 | 4.40625 | 4 | #class keyword is used to create your own classes in python ,just like the sets,lists,tuples etc. .these classes are also known as objects and this type of programming involving the creation of your own classes or objects is known as object oriented programming or oops....#
class football_team: #Here the ... | true |
e98ba84add2519f4c3858cef105c6e5de54f57fb | jonathangriffiths/Euler | /Page1/SumPrimesBelowN.py | 612 | 4.15625 | 4 | __author__ = 'Jono'
from GetPrimeN import isPrime
#basic method to estimate how long it will take like this
def get_sum_primes_below_n(n):
sum=2
for i in range(3, n+1, 2):
if isPrime(i):
sum+=i
return sum
print get_sum_primes_below_n(2000000)
#note: Erastosthenes seive useful for ... | true |
3dbaed02def20cc1c27d7ed07cce6be97942b78b | za-webdev/Python-practice | /score.py | 425 | 4.25 | 4 |
#function that generates ten scores between 60 and 100. Each time a score is generated,function displays what the grade is for a particular score.
def score_grade():
for x in range(1,11):
import random
x=(random.randint(60,100))
if x >60 and x<70:
z="D"
elif x>70 and x<80:
z="C"
elif x>80 and x<90:
... | true |
092b2594f9159f72119349177487a3c0ffe8ebde | kronecker08/Data-Structures-and-Algorithm----Udacity | /submit/Task4.py | 1,306 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
call_outgoing = []
call_incoming = []
fo... | true |
d3760baba77aa112d2860cbeed1ef56f378347be | iamrobinhood12345/economic-models | /base-model.py | 2,642 | 4.21875 | 4 | # Basic Flow of Money Model
import sys
MODEL_NUMBER = 1
INPUT_STRING = """
MAIN MENU:
Input amount to loan (integer).
Input 'q' to quit program.
"""
EXIT_STRING = """
Thank you, goodbye!
By Ben Shields <https://github.com/iamrobinhood12345>... | true |
a868af86d0102fe2aafd0b10782840ecad86768e | KC1988Learning/TkinterLearning | /tutorial/grid.py | 2,025 | 4.15625 | 4 | import tkinter as tk
from tkinter import ttk
from window import set_dpi_awareness
def greet():
# add strip() to remove whitespace in string
print(f"Hello {user_name.get().strip() or 'World'}! How are you?")
set_dpi_awareness()
root = tk.Tk()
root.title("Greeting App")
# configure row and column property of ... | true |
24e335ecf0a79e60026e0a3f41f5277b7ab839ef | tikitae92/Python-IS340 | /Ch4/whileCheckout2.py | 1,011 | 4.15625 | 4 | #example of sale transaction in a store
#cashier doesnt know the # of items in a cart
#input price
#add to total and display in the while loop
#starts sale transaction and ends it when no items are left
#keep track of # of items in customer shopping cart
#print total # of items
#stop when user enter -1
#if nega... | true |
fbf74dfb475b7f1d3ee5e7a247c6c40b3a615d0e | camarena2/camarena2.github.io | /secretworld.py | 800 | 4.25 | 4 |
print(" Welcome to the Secret Word Game. Guess a letter in the word, then press enter:")
from random import choice
word = choice(["table", "chair", "bottle", "plate", "parade", "coding", "teacher", "markers", "phone", "grill", "friends", "fourth", "party"])
guessed = []
while True:
out = ""
for letter in... | true |
041dbf38767b723327ebf197bba3cf02bbf10a5b | raymccarthy/codedojo | /adam/firstWork/adam.py | 461 | 4.21875 | 4 | calculator = "Calculator:"
print(calculator)
one = input("Enter a number: ")
two = input("Enter another number: ")
three = input("Would you like to add another number?: ")
if three == "yes" or three == "Yes":
thre = input("What would you like that number to be: ")
answer = float(one) + float(two) + float(thre)... | true |
a7ea7d24373085e6822da0ff924304b434ed8d52 | pasanchamikara/ec-pythontraining-s02 | /data_structures/tuples_training.py | 507 | 4.46875 | 4 | # Tuples are unchangeable once created, ordered and duplicates are allowed.
vegetable_tuple = ("cucumber", "pumkin", "tomato")
# convert his to a set and assign to vegetable_set
# get the lenght of the tuple vegetable_tuple
fruit_tuple = ("annas", )
# get the result of print(type(fruit_tuple)) with and without com... | true |
32d6e902356eeec9d4cfcab5bd4f1c8d4398dea3 | JoshuaR830/HAI | /Lab 1/Excercise 4/ex9.py | 272 | 4.28125 | 4 | words = ["This", "is", "a", "word", "list"]
print("Sorted: " + sorted(words))
print("Original: " + words)
words.sort()
print("Original: " + words)
# sorted(words) prints does not change the order of the original list
# words.sort() changes the original order of the list | true |
0fdac6ba0c12be57e9d07c067ce5be5042971876 | BurlaSaiTeja/Python-Codes | /Lists/Lists05.py | 342 | 4.21875 | 4 | """
Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).
"""
def sqval():
l=list()
for i in range(1,31):
l.append(i**2)
print(l[:5])
print(l[-5:])
sqval()
"""
Output:
[1, 4, 9, 16, 25]
[676, 72... | true |
e9ffcaced1121fa20de7c5f4df840bc8821a3c58 | anc1revv/coding_practice | /leetcode/easy/letter_capitalize.py | 490 | 4.375 | 4 | '''
Using the Python language, have the function LetterCapitalize(str) take the str
parameter being passed and capitalize the first letter of each word.
Words will be separated by only one space.
'''
def letter_capitalize(input_str):
list_words = input_str.split(" ")
for word in list_words:
for i in range(le... | true |
2b3c1bc9399793ce14fd920e8dfda39062655465 | Swastik-Saha/Python-Programs | /Recognize&Return_Repeated_Numbers_In_An_Array.py | 472 | 4.1875 | 4 | def repeated():
arr = []
length = int(raw_input("Enter the length of the array: "))
for i in range(0,length):
arr.append(int(raw_input("Enter the elements of an array: ")))
arr.sort()
count = 0
for i in range(0,length):
print "The number t... | true |
971881bad3c2980c5c2875ff07d1ac50d2a45299 | wojtekminda/Python3_Trainings | /SMG_homework/10_2_Asking_for_an_integer_number.py | 2,299 | 4.53125 | 5 | '''
Write input_int() function which asks the user to provide an integer number
and returns it (as a number, not as a string). It accepts up to 3 arguments:
1. An optional prompt (like input() built-in function).
2. An optional minimum acceptable number (there is no minimum by default).
3. An optional maximum acceptabl... | true |
09c024e3dfde0a07e652fd8bfb02357b736bc1ac | wojtekminda/Python3_Trainings | /SMG_homework/01_3_Should_I_go_out.py | 1,319 | 4.15625 | 4 | '''
A user is trying to decide whether to go out tonight.
Write a script which asks her a few yes-no questions and decides for her according to the following scheme:
[NO SCHEME]
'''
raining = input("Is it raining? ")
if raining == "yes":
netflix = input("Is the new episode on Netflix out already? ")
if netflix... | true |
2b11221a58ddff3101a95aa892b0ed5ab4997f80 | 5h3rr1ll/LearnPythonTheHardWay | /ex15.py | 1,076 | 4.375 | 4 | #importing the method argv (argument variable) from the library sys into my code
from sys import argv
"""now I defining which two arguments I want to have set while typing the
filename. So you are forced to type: python ex15.py ArgumentVariable1
ArgumentVariable2"""
script, filename = argv
#since the filename is give... | true |
a4877ed3f2bb5586e5143b85119eeb1f75efeb6c | kmjawadurrahman/python-interactive-mini-games | /guess_the_game.py | 2,176 | 4.40625 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
which_range = ""
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code... | true |
f95c90cefc62f8a1531c8a0d32ddc4e91a3dbc86 | Otumian-empire/python-oop-blaikie | /05. Advanced Features/0505.py | 604 | 4.15625 | 4 | # With context
# open file and close it
fp = open('Hello.txt', '+a')
print('I am a new text file', file=fp)
fp.close()
# We don't have to close it
with open('Hello.txt', '+a') as op:
print('I am a new line in the Hello.txt file', file=op)
# seems like not a valid python3 code
# class MyWithClass:
# def __e... | true |
566946645bd44e94bafe916c9e2f0aeadd4b1cb5 | mjayfinley/Conditions_and_Functions | /EvenOdd/EvenOdd.py | 220 | 4.3125 | 4 | numberInput = int(input("Please enter a number: "))
if numberInput == 0:
print("This number is neither odd or even.")
elif numberInput %2 == 0:
print("This number is even")
else:
print("This number is odd")
| true |
08a27190e2210d7bedda769c93c6a9d710cb474e | BarDalal/Matrices--addition-and-multiplication | /AddMinPart.py | 1,148 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Name: Bar Dalal
Class: Ya4
The program adds the common parts of two matrices.
The sum's size is as the common part's size.
"""
import numpy as np
def MinAddition(a, b):
"""
The function gets two matrices.
The function returns the sum of the common parts of the m... | true |
afa5e2e385ff2086f25c471ac148c7032980d250 | nighatm/W19A | /app.py | 1,004 | 4.1875 | 4 | import addition
import subtraction
import multiplication
import divide
print("Please choose an operation")
print("1: Addition")
print("2: Subtraction")
print("3: Multiplication")
print("4: Division")
try:
userChoice = int(input ("Enter Choice 1 or 2 or 3 or 4 : "))
except:
print ('You have ent... | true |
cfd8276cedbf35d4542948135e6c68c986d00c89 | Coadiey/Python-Projects | /Python programs/PA7.py | 2,214 | 4.15625 | 4 | # Author: Coadiey Bryan
# CLID: C00039405
# Course/Section: CMPS 150 – Section 003
# Assignment: PA7
# Date Assigned: Friday, November 17, 2017
# Date/Time Due: Wednesday, November 22, 2017 –- 11:55 pm
#Description: This program is just a simple class setup that changes the output into a string based on the input... | true |
96672006f4ee0b8ce9cb023f0f14c9a5eb385b71 | EmreTekinalp/PythonLibrary | /src/design_pattern/factory_pattern.py | 1,791 | 4.1875 | 4 | """
@author: Emre Tekinalp
@contact: e.tekinalp@icloud.com
@since: May 28th 2016
@brief: Example of the factory pattern.
Unit tests to be found under:
test/unit/test_factory_pattern.py
"""
from abc import abstractmethod
class Connection(object):
"""Connection class."""
@abstractmethod
... | true |
f9ff6527ee3c680cefc70bb37a49ba2465005b51 | kirushpeter/flask-udemy-tut | /python-level1/pypy.py | 2,426 | 4.25 | 4 | """
#numbers
print("hello world")
print(1/2)
print(2**7)
my_dogs = 2
a = 10
print(a)
a = a + a
print(a)
puppies = 6
weight = 2
total = puppies * weight
print(total)
#strings
print(len("hello"))
#indexing
mystring = "abcdefghij"
print(mystring[-1])
print(mystring[0:7:2])#start is included start stop and ... | true |
eeb0f0366684a36245718065c8858f43f70736f7 | danielstaal/project | /code/chips_exe.py | 2,117 | 4.15625 | 4 | '''
Executable file Chips & Circuits
Date: 26/05/2016
Daniel Staal
This program allows the user to choose a print, netlist, search methods and
a filename to output the result
To execute this program: python chips_exe.py
'''
import astar3D
import netlists
import time
import sys
if __name__ == "__main__":
... | true |
1f32a7062a40bc6e14c6c0f7ba17d065746feb7c | josh-perry/ProjectEuler | /problem 1.py | 439 | 4.21875 | 4 | # Problem 1: Multiples of 3 and 5
# 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 euler_1():
total = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == ... | true |
a185c1f5b1101ae320e5781d1a73548e270a6f57 | Zahidsqldba07/code-signal-solutions-GCA | /GCA/2mostFrequentDigits.py | 1,053 | 4.125 | 4 | def mostFrequentDigits(a):
#Tests
# a: [25, 2, 3, 57, 38, 41] ==> [2, 3, 5]
# a: [90, 81, 22, 36, 41, 57, 58, 97, 40, 36] ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# a: [28, 12, 48, 23, 76, 64, 65, 50, 54, 98] ==> [2, 4, 5, 6, 8]
"""
Given an array of integers a, your task is to calculate the digits that occur the mos... | true |
da574aa59126be1b3964190559c478a296f5b4a9 | Zahidsqldba07/code-signal-solutions-GCA | /arcade/intro/026-evenDigitsOnly.py | 515 | 4.1875 | 4 | def evenDigitsOnly(n):
n = [int(i) for i in str(n)]
for d in n:
if d%2 != 0:
return False
return True
"""
Check if all digits of the given integer are even.
Example
For n = 248622, the output should be
evenDigitsOnly(n) = true;
For n = 642386, the output should be
evenDigitsOnly(n) =... | true |
8d9c2d0492cfb620649087e4e007031357eee827 | Zahidsqldba07/code-signal-solutions-GCA | /GCA/2countWaysToSplit.py | 1,719 | 4.1875 | 4 | def countWaysToSplit(s):
listS= list(s)
# print (listS)
lenS = len(listS)
count = 0
for i in range(1,lenS):
for j in range(i+1, lenS):
ab = s[0:j]
bc = s[i:lenS]
ca = s[j:lenS] + s[0:i]
# print("AB is :",ab,"BC is:",bc,"CA is:",ca)
... | true |
b5224f264e6e51d57eacf32a54564688eed5c143 | Zahidsqldba07/code-signal-solutions-GCA | /arcade/intro/09-allLongestStrings.py | 1,206 | 4.125 | 4 | """
Given an array of strings, return another array containing all of its longest strings.
Example
For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be
allLongestStrings(inputArray) = ["aba", "vcd", "aba"].
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.string inputArray
A n... | true |
ac6519b87bdd7461be54798c7a74088110759986 | kampetyson/python-for-everybody | /8-Chapter/Exercise6.py | 829 | 4.3125 | 4 | '''
Rewrite the program that prompts the user for a list of
numbers and prints out the maximum and minimum of the numbers at
the end when the user enters “done”. Write the program to store the
numbers the user enters in a list and use the max() and min() functions to
compute the maximum and minimum numbers after t... | true |
b3bc71dff70c5bf4e21e0bc4e2af3f826c41406d | kampetyson/python-for-everybody | /2-Chapter/Exercise3.py | 212 | 4.15625 | 4 | # Write a program to prompt the user for hours and rate perhour to compute gross pay.
hours = int(input('Enter Hours: '))
rate = float(input('Enter Rate: '))
gross_pay = hours * rate
print('Pay:',gross_pay) | true |
789ffe90d787d656159bbefc7dfeafb7bd02a287 | kampetyson/python-for-everybody | /7-Chapter/Exercise2.py | 1,108 | 4.15625 | 4 | # Write a program to prompt for a file name, and then read
# through the file and look for lines of the form: X-DSPAM-Confidence: 0.8475
# When you encounter a line that starts with “X-DSPAM-Confidence:”
# pull apart the line to extract the floating-point number on the line.
# Count these lines and then compute the... | true |
9b3edb65b838b153430aa177b1609260908e98b4 | kampetyson/python-for-everybody | /7-Chapter/Exercise1.py | 614 | 4.40625 | 4 | # Write a program to read through a file and print the contents
# of the file (line by line) all in upper case. Executing the program will
# look as follows:
# python shout.py
# Enter a file name: mbox-short.txt
# FROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:16 2008
# RETURN-PATH: <POSTMASTER@COLLAB.SAKAIPRO... | true |
21045c28a2f3a5e004a2b42b3d6f7d04aa122e8a | usmansabir98/AI-Semester-101 | /PCC Chapter 5/5-5.py | 779 | 4.125 | 4 | # 5-5. Alien Colors #3: Turn your if-else chain from Exercise 5-4 into an if-elifelse
# chain.
# • If the alien is green, print a message that the player earned 5 points.
# • If the alien is yellow, print a message that the player earned 10 points.
# • If the alien is red, print a message that the player earned 15 poin... | true |
8f6f7f0c6308b83fa51fbdf2f2e00717f736b63e | CISVVC/test-ZackaryBair | /dice_roll/main.py | 2,080 | 4.28125 | 4 | """
Assignment: Challenge Problem 5.13
File: main.py
Purpose: Rolls dice x amount of times, and prints out a histogram for the number of times that each number was landed on
Instructions:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An... | true |
bb3e967a7776b571cca10fdb988cb09b8980cf63 | gptix/cs-module-project-algorithms2 | /moving_zeroes/moving_zeroes.py | 458 | 4.28125 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
def moving_zeroes(arr):
# Your code here
original_length = len(arr)
out = [element for element in arr if element is not 0]
out = out + [0]*original_length
return out[:original_length]
if __name__ == '__main__':
# Use the main funct... | true |
db13074a2c8dca8e5d1708a80760d6626f3b0b9b | AdyGCode/Python-Basics-2021S1 | /Week-7-1/functions-4.py | 1,251 | 4.34375 | 4 | """
File: Week-7-1/functions-4.py
Author: Adrian Gould
Purpose: Demonstrate taking code and making it a function
Move the get integer code to a function (see functions-3
for the previous code)
Design:
Define get_integer function
Define number to be None
While nu... | true |
425571e8bb0512c2a92f9068883189291acb771b | AdyGCode/Python-Basics-2021S1 | /Week-13-1/gui-7-exercise.py | 1,242 | 4.1875 | 4 | # --------------------------------------------------------------
# File: Week-13-1/gui-7-exercise.py
# Project: Python-Class-Demos
# Author: Adrian Gould <Adrian.Gould@nmtafe.wa.edu.au>
# Created: 11/05/2021
# Purpose: Practice using GUI
#
# Problem: Create a GUI that asks a user for their name and
# ... | true |
b306448e151d13b2caeb8cfced3a9650affc29ba | jfbeyond/Coding-Practice-Python | /101_symmetric_tree.py | 1,026 | 4.15625 | 4 |
# 101 Symmetric Tree
# Recursively
def isSymmetric(root):
# current node left child is equal to current node right child
if not root: return False
return checkSymmetry(root, root):
def checkSymmetry(node1, node2):
if not node1 and not node2: return True
if node1 and node2 and node1... | true |
1353ee42c247cd5d9a30cb3bd9fc5f33639d181a | F4Francisco/Algorithms_Notes_For_PRofessionals | /Section1.2_FizzBuzzV2.py | 777 | 4.125 | 4 | ''' Optimizing the orginal FizzBuzz:
if divisable by 3 sub with Fizz
if divisable by 5 sub with Buzz
if divisable by 15 sub with FizzBuzz
'''
# Create an array with numbers 1-5
number = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
#iterate through the array and check which numbers are fizz and which are Buzz
for num ... | true |
e5e7ef14baa4d4b7b3596bb4adf7cadaddea2e07 | SimaFish/python_practice | /class_practice/auto.py | 2,571 | 4.40625 | 4 | # Zen of Python
import this
# The definition of a class happens with the `class` statement.
# Defining the class `Auto`.
# class Auto(object): is also an allowable definition
class Auto():
# ToDo class attributes vs. instance attributes
# https://www.toptal.com/python/python-class-attributes-an-overly-thorough... | true |
43594d3f6b04fcee5ff2285226da49fd96471d89 | SimaFish/python_practice | /modules/mod_string.py | 1,027 | 4.25 | 4 | import string
# String constants (output type: str).
# The lowercase letters 'abcdefghijklmnopqrstuvwxyz'.
print('1: ' + string.ascii_lowercase)
# The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
print('2: ' + string.ascii_uppercase)
# The concatenation of the ascii_lowercase and ascii_uppercase constants descri... | true |
6896682b041713dff84ab145274b7858f3f3c7bc | seo0/MLstudy | /adsa_2016/module13_graphs01/part02_basics02/graphs_etc.py | 1,760 | 4.3125 | 4 |
import networkx as nx
import matplotlib.pyplot as plt
from module13_graphs01.part01_basics.graphs_basics import print_graph, display_and_save
def modulo_digraph(N,M):
"""
This function returns a directed graph DiGraph) with the following properties (see also cheatsheet at: http://screencast... | true |
1895a345a9021d25dcdc91982ff00b6f3090474a | luckydimdim/grokking | /tree_breadth_first_search/minimum_depth_of_a_binary_tree/main.py | 1,086 | 4.1875 | 4 | from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def find_minimum_depth(root):
'''
Find the minimum depth of a binary tree.
The minimum depth is the number of nodes along the shortest path
from the root node to the nearest leaf... | true |
48f1fa5d3668a54ec73e49e377c610b3bfdba024 | luckydimdim/grokking | /modified_binary_search/search_bitonic_array/main.py | 1,139 | 4.15625 | 4 | def search_bitonic_array(arr, key):
'''
Given a Bitonic array, find if a given ‘key’ is present in it.
An array is considered bitonic if it is monotonically increasing and then monotonically decreasing.
Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1].
... | true |
9e429a3d67b58bd3e34e0868fa203e80c8215925 | luckydimdim/grokking | /modified_binary_search/next_letter/main.py | 1,092 | 4.125 | 4 | import string
def search_next_letter(letters, key):
'''
Given an array of lowercase letters sorted in ascending order,
find the smallest letter in the given array greater than a given ‘key’.
Assume the given array is a circular list,
which means that the last letter is assumed to be connected with ... | true |
5921d9a5ee2ca9e587ea6d8a54cdaf6126ffd510 | luckydimdim/grokking | /subsets/permutations_recursive/main.py | 535 | 4.1875 | 4 | from collections import deque
def find_permutations(nums):
'''
Given a set of distinct numbers, find all of its permutations.
'''
result = []
permutate(nums, 0, [], result)
return result
def permutate(nums, i, current, result):
if i == len(nums):
result.append(current)
return
for l in range(... | true |
57bf01794444f9e3fc31973d50f33a3cdbd9639b | luckydimdim/grokking | /tree_breadth_first_search/zigzag_traversal/main.py | 1,289 | 4.15625 | 4 | from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def traverse(root):
'''
Given a binary tree, populate an array to represent its zigzag level order traversal.
You should populate the values of all nodes of the first level from lef... | true |
03e7a2218937f12112e322ac88ce065cceb7b23f | darshanchandran/PythonProject | /PythonProject/Classes and Modules/Classes/Compositions.py | 336 | 4.28125 | 4 | #This program shows how compositions work with out inheriting the parent class
class Parent(object):
def boss(self):
print("I'm the boss")
class Child(object):
def __init__(self):
self.child = Parent()
def boss(self):
print("Child is the boss")
self.child.boss()
son = Chi... | true |
c0c7027ee70e6be6a0f9b067fc0f1df9b6276bc0 | EmissaryEntertainment/3D-Scripting | /Week_2/McSpadden_Exercise_2.3.py | 699 | 4.21875 | 4 | #Use each form of calculation besides modulus
print("2 + 5 = " + str(2+5))
print("2 - 5 = " + str(2-5))
print("2 * 5 = " + str(2*5))
print("2 / 5 = " + str(2/5))
print("2 ** 5 = " + str(2**5))
#Calculation whos resluts depend on order of operations
print("160 + 5 * 7 = " + str(160 + 5 * 7))
#Force change order of oper... | true |
2c709c8d07c8a738177250eb5b4d029c3945dd7b | EmissaryEntertainment/3D-Scripting | /Week_4/McSpadden_Exercise_4.3.py | 897 | 4.25 | 4 | #THREE IS A CROWD
print("-------THREE IS A CROWD-------")
names = ["Jose", "Jim","Larry","Bran"]
def check_list(list):
if len(list) > 3:
print("This list is to crowded.")
check_list(names)
del names[0]
check_list(names)
#THREE IS A CROWD - PART 2
print("-------THREE IS A CROWD - PART 2-------")
def check_l... | true |
567addd4e775a0a80665b75a1666cbf1fdda28e9 | KumarjitDas/Algorithms | /Algorithms/Recursion/Python/countdown.py | 911 | 4.5 | 4 | def countdown(value: int):
""" Print the countdown values.
countdown
=========
The `countdown` function takes an integer value and decreases it. It prints
the value each time it. It uses 'recursion' to do this.
Parameters
----------
value: int
an integer value
Returns
-------
... | true |
110c972931fe16b1d605396a7d2813388ebf3282 | HossamSalaheldeen/Python_lab1 | /prob3.py | 915 | 4.1875 | 4 | # Problem 3
#-------------
# Consider dividing a string into two halves.
# Case 1:
# The length is even, the front and back halves are the same length.
# Case 2:
# The length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a a... | true |
2a7963e01f163f9b2c85e8d64de66630914f7328 | JemrickD-01/Python-Activity | /WhichWord.py | 617 | 4.21875 | 4 | def stringLength(fname,lname):
if len(fname)>len(lname):
print(fname,"is longer than",lname)
elif len(fname)<len(lname):
print(lname,"is longer than",fname)
else:
print(fname,"and",lname,"have the same size")
choices = ["y","n"]
ans="y"
while ans=="y":
x=input... | true |
af1ecc1dfb000a8dd0aab062123a29c489a7f426 | Raj-kar/PyRaj-codes | /password.py | 1,300 | 4.28125 | 4 | ''' Homework 1 -
WAP to genarate a secure password.
- 1. password must contains minimim 8 char.
- 2. both upper and lower case.
- 3. must contains two number and one special char.
bonus - shuffle the password, for better security.
Homework 2 -
Optimize the below Code.
'''
# Wap to check a password is secure o... | true |
82fc2124669344ca0291a5d9bef9d8f70b01e7b9 | avantikabagri/lecture8 | /3/gradepredict_stubs.py | 2,028 | 4.21875 | 4 |
# reads a CSV from a file, and creates a dictionary of this form:
# grade_dict['homeworks'] = [20, 20, 20, ...]
# grade_dict['lectures'] = [5, 5, 5, ...]
# ...
# params: none
# returns: a dictionary as specified above
def get_data():
return {}
# param: list of lecture excercise scores
# return: total scores for lec... | true |
42ea0a6fe036ea1fbb3059a715461680a0e13146 | saubhik/catalog | /src/catalog/tries/add-and-search-word-data-structure-design.py | 2,412 | 4.3125 | 4 | # Add and Search Word - Data structure design
#
# https://leetcode.com/problems/add-and-search-word-data-structure-design/
#
import unittest
from typing import Dict
class TrieNode:
def __init__(self):
self.children: Dict[str, TrieNode] = dict()
self.end: bool = False
class WordDictionary:
d... | true |
58d34d94f58f56f4c1e8dbf9d3b8a97d23ed8e0e | Ry09/Python-projects | /Random Stuff/collatz.py | 1,142 | 4.65625 | 5 | # This is a program to run the Collatz Sequence. It will
# take a number from the user and then divide it by 2 if
# it is even, or multiply by 3 and add 1 if it is odd. It
# will loop through this until it reaches the value of 1.
def collatz(num):
try:
num = int(num)
print(num)
if num == 1:... | true |
927170aae55b2529e503f3e1836cd0ac6d18516b | rayadamas/pythonmasterclassSequence | /coding exercise 14.py | 662 | 4.21875 | 4 | # Write a program which prompts the user to enter three integers separated by ","
# user input is: a, b, c; where those are numbers
# The following calculation should be displayed: a + b - c
# 10, 11, 10 = 11
# 7, 5, -1 = 13
# Take input from the user
user_input = input("Please enter three numbers: ")
# Sp... | true |
a6c5cc0f90f540202efa1c8f6b1098d99c3c4397 | surprise777/StrategyGame2017 | /Game/current_state.py | 1,959 | 4.3125 | 4 | """module: current_state (SuperClass)
"""
from typing import Any
class State:
"""a class represent the state of class.
current_player - the player name who is permitted to play this turn.
current_condition - the current condition of the state of the game
"""
current_player: str
current_condit... | true |
a23930569e83eb420cc1f2290f35bb43853be0c2 | caboosecodes/Python_Projects | /python_If.py | 297 | 4.25 | 4 |
height = 200
if height > 150:
if height > 195:
print('you are too tall ride the roller coaster')
else:
print('you can ride the roller coaster')
elif height >= 125:
print('you need a booster seat to ride the roller coaster')
else:
print('where are your parents?')
| true |
c901a714e56f22c3f31fef767205df16ab561035 | ScottSko/Python---Pearson---Third-Edition---Chapter-5 | /Chapter 5 - Maximum of Two Values.py | 379 | 4.21875 | 4 | def main():
num1 = int(input("Please enter a value: "))
num2 = int(input("Please enter another value: "))
greater_value = maximum(num1, num2)
print("The greater value is", greater_value)
def maximum(num1,num2):
if num1 > num2:
return num1
elif num1 == num2:
print("The ... | true |
3ce6d57c9a06622e7cae3f1bc2fa2baa1946be36 | Nikhil-Xavier-DS/Sort-Search-Algorithms | /bubble_sort.py | 467 | 4.28125 | 4 | """
Implementation of Bubble Sort.
"""
# Author: Nikhil Xavier <nikhilxavier@yahoo.com>
# License: BSD 3 clause
def Bubble_sort(arr):
"""Function to perform Bubble sort in ascending order.
TIME COMPLEXITY: Best:O(n), Average:O(n^2), Worst:O(n^2)
SPACE COMPLEXITY: Worst: O(1)
"""
for outer in ra... | true |
b8d279107217bfbf7174bb4dd054b254a5e90a7c | SreeramSP/Python-Programs-S1 | /factorial.py | 235 | 4.1875 | 4 | n=int(input("Enter the number="))
factorial=1
if n<0:
print("No negative Numbers")
elif n==0:
print("The factorial of 0 is 1")
else:
for i in range(1,n+1):
factorial=factorial*i
print("Factorial=",factorial)
| true |
283112adcd03688236d72a9748711469976a4976 | standrewscollege2018/2021-year-11-classwork-SamEdwards2006 | /Paracetamol.py | 662 | 4.125 | 4 | #sets the constants
AGE_LIMIT = 12
WEIGHT_LIMIT = 0
on = 1
#finds the users age
while(on > 0):
age = int(input("How old are you: "))
#tests if the age is more than 12,
#if not, it will go to the else.
if age >= AGE_LIMIT:
print("Recommend two 500 mg paracetamol tablets")
elif age >= 0:
... | true |
78a556658eea5d03ebbdd76ecf3e7d2888f3860c | rafa761/leetcode-coding-challenges | /2020 - august/008 - non-overlapping intervals.py | 1,500 | 4.40625 | 4 | """
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]
... | true |
2442c3261cc4d4280d0a46878a3e10d250298b4a | vismayatk002/PythonAssignment | /BasicCorePrograms/PrimeFactors.py | 542 | 4.3125 | 4 | """
@Author : Vismaya
@Date : 2021-10-18 11:39
@Last Modified by : Vismaya
@Last Modified time : 2021-10-18 12:52
@Title : Prime factors of a number
"""
def is_prime(num):
flag = 0
for j in range(2, num):
if num % j == 0:
flag = 1
break
j += 1
... | true |
33579d9a2d351a6a33f82b708c68be6233c45afb | DrSneus/cse-20289-sp21-examples | /lecture09/is_anagram.py | 2,111 | 4.1875 | 4 | #!/usr/bin/env python3
import os
import sys
# Functions
def usage(status=0):
print(f'''Usage: {os.path.basename(sys.argv[0])} [flags]
-i Ignore case distinctions
This program reads in two words per line and determines if they are anagrams.
''')
sys.exit(status)
def count_letters(string):
''' Retur... | true |
0b777077897ac2ae8fc9bea47dae6853cafd31fd | jemarsha/leetcode_shenanigans | /Random_problems/Merged_k_linked_lists.py | 1,138 | 4.375 | 4 | #from typing import List
class Node:
def __init__(self,value):
self.value = value
self.next = None
def merge_lists(lists):
"""
This function merges sorted linked lists- Reads the values in one at a time into a list O(kn). Then
sorts them O(nlogn). Then puts them into a linked list (... | true |
70826eefc7345f3d96c93173f0b17a4b5c1123e5 | Sumanpal3108/21-days-of-programming-Solutions | /Day14.py | 371 | 4.625 | 5 | str1 = input("Enter any String: ")
str2 = input("Enter the substring you want to replace: ")
str3 = input("Enter the string you want to replace it with: ")
s = str1.replace(str2,str3)
print("The original string is: ",str1)
print("The substring you want to replace: ",str2)
print("The string you want to use instead... | true |
fe511ba08d1ba756f4a7b7122ccee3b331bdf1a3 | Yasir77788/Shopping-Cart | /shoppingCart.py | 1,959 | 4.21875 | 4 | # shopping cart to perform adding, removing,
# clearing, and showing the items within the cart
# import functions
from IPython.display import clear_output
# global list variable
cart = []
# create function to add items to cart
def addItem(item):
clear_output()
cart.append(item)
print("{} ha... | true |
6f4cfa2188d0845d9ad888f1540edd6f74c83b87 | Kevinloritsch/Buffet-Dr.-Neato | /Python Warmup/Warmup #3 - #2 was Disneyland/run3.py | 766 | 4.125 | 4 | import math
shape = input("What shape do you want the area of? Choose a rectangle, triangle, or circle ;) ")
if shape=='rectangle':
rone = input("What is the length of the first side? ")
rtwo = input("What is the length of the second side? ")
answer = int(rone)*int(rtwo)
print(answer)
elif shape=='t... | true |
27fd01098ce6f68a304f25eb885af97217863453 | shivambhojani/Python-Practice | /remove_char.py | 372 | 4.3125 | 4 | # Write a method which will remove any given character from a String?
def remove(str, char):
new_str = ""
for i in range(0, len(str)):
if i != char:
new_str = new_str + str[i]
return new_str
a = input("String: ")
b = int(input("which Character you want to remove: "))
b = b... | true |
4067c6b39abf37b18537c930109aa732e9dfe885 | menliang99/CodingPractice | /PeakingIterator.py | 714 | 4.25 | 4 | # Decorator Pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.
class PeekingIterator(object):
def __init__(self, iterator):
self.iter = iterator
self.peekFlag = False
self.n... | true |
0312a221309f546836230b69bf7b6c81f02bac56 | mhetrick29/COS429_Assignments | /A4_P2/relu_backprop.py | 1,208 | 4.15625 | 4 | def relu_backprop(dLdy, x):
import numpy as np
# Backpropogates the partial derivatives of loss with respect to the output
# of the relu function to compute the partial derivatives of the loss with
# respect to the input of the relu function. Note that even though relu is
# applied elementwise to ma... | true |
e56c29cc6afc63b4ec4cf5afc97355e0385ee367 | nunu2021/DijkstraPathFinding | /dijkstra/basic_algo.py | 2,208 | 4.125 | 4 | import pygame
graph = {
'a': {'b': 1, 'c': 1, 'd': 1},
'b': {'c': 1, 'f': 1},
'c': {'f': 1, 'd': 1},
'd': {'e': 1, 'g': 1},
'e': {'g': 1, 'h': 1},
'f': {'e': 1, 'h': 1},
'g': {'h': 1},
'h': {'g': 1},
}
def dijkstra(graph, start,goal):
shortest_distance ={} # records the cost to re... | true |
079b0e961c408f6b2b6c8edf65b56eaa0f2b4e61 | WaqasAkbarEngr/Python-Tutorials | /smallest_number.py | 612 | 4.1875 | 4 | def smallest_number():
numbers = []
entries = input("How many number you want to enter? ")
entries = int(entries)
while entries > 0:
entered_number = input("Enter a number? ")
numbers.append(entered_number)
smallest_number = entered_number
entries = entries - 1
... | true |
83265b7915746a67e8240e49d3819e8e6d840526 | cmobrien123/Python-for-Everybody-Courses-1-through-4 | /Ch7Asmt7.2.py | 1,146 | 4.34375 | 4 | # Exercise 7.2: Write a program to prompt for a file name, and then read
# through the file and look for lines of the form:
# X-DSPAM-Confidence:0.8475
# When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
# the line to extract the floating-point number on the line. count these lines
# and then... | true |
d0a8a00b9834f82ef386fb2d2bc1a93bbd5c092a | arkadym74/pthexperience | /helloworld.py | 1,664 | 4.3125 | 4 | #Prints the Words "Hello World"
'''This is a multiline comment'''
print("Hello World")
userAge, userName = 30, 'Peter'
x = 5
y = 10
y = x
print("x = ", x)
print("y = ", y)
brand = 'Apple'
exchangeRate = 1.235235245
message = 'The price of this {0:s} laptop is {1:d} USD and the exchange rate is {2:4.2f} USD to 1... | true |
4af66f31e555e7fd67d00869653e8c7048c1f472 | mgomesq/neural_network_flappybird | /FlappyBird/brain.py | 1,735 | 4.46875 | 4 | # -*- coding: utf-8 -*-
'''
Brain
=====
Provides a Brain class, that simulates a bird's brain.
This class should be callable, returning True or False
depending on whether or not the bird should flap its wings.
How to use
----------
Brain is passed as an argument to Bird, which is defin... | true |
bba081265a85bbf2988ee18245ba83140fe8bb4a | Tlepley11/Home | /listlessthan10.py | 225 | 4.1875 | 4 | #A program that prints all integers in a list less than a value input by the user
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
x = input("Please enter a number: ")
b = []
for i in a:
if i < x: print(i); b.append(i)
print(b)
| true |
b652e232cb08379678bcdd9173d596a4afef4a05 | jamie0725/LeetCode-Solutions | /566ReshapetheMatrix.py | 1,737 | 4.25 | 4 | """
n MATLAB, there is a very useful function called 'reshape', which can reshape
a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive
integers r and c representing the row number and column number of the wanted
reshap... | true |
293fe7ead7c870e3f25bde546f2b34337eb32378 | optionalg/cracking_the_coding_interview_python-1 | /ch4_trees_and_graphs/4.2_minimal_tree.py | 1,190 | 4.125 | 4 | # [4.2] Minimal Tree: Given a sorted(increasing order)
# array with unique integer elements, write an algorithm
# to create a binary search tree with minimal height
# Space complexity:
# Time complexity:
import unittest
def create_bst(array):
if not array:
return None
elif len(array) == 1:
r... | true |
b0d9de4d3f59d074ea1ffc412a99e8610ddccab6 | optionalg/cracking_the_coding_interview_python-1 | /ch5_bit_manipulation/5.7_pairwise_swap.py | 1,734 | 4.15625 | 4 | # [5.7] Pairwise Swap: Write a program to swap odd and even bits
# in an integer with as few instructions as possible (e.g., bit
# 0 and bit 1 are swapped, bit 2 and bit 3 and swapped, and so on)
import unittest
def pairwise_swap(num):
even_mask = create_even_mask(num)
odd_mask = create_odd_mask(num)
... | true |
3dc3b3e5045027bcccafc7907b667a0d2c8ec606 | optionalg/cracking_the_coding_interview_python-1 | /ch1_arrays_and_strings/1.1_is_unique.py | 798 | 4.1875 | 4 | # Time complexity: O(n) because needs to check each character
# Space complexity: O(c) where c is each character
import unittest
def is_unique(s):
# create a hashmap to keep track of char count
char_count = {}
for char in s:
# if character is not in hashmap add it
if not char in char_c... | true |
738c5f3cfa7d3c58b05c5738822e0d807dbf1f7b | optionalg/cracking_the_coding_interview_python-1 | /ch8_recursion_and_dynamic_programming/8.1_triple_step.py | 1,634 | 4.15625 | 4 | # [8.1] Triple Step: A child is running up a staircase with n
# steps and can hop either 1 step, 2 steps, or 3 steps at a
# time. Implement a method to count how many possible ways
# the child can run up the stairs.
import unittest
def fib(n):
if n < 1:
raise ValueError('Must be positive Integer')
el... | true |
fdee0f3aaae1372696e95ba72cb3ca090df592fb | pieland-byte/Introduction-to-Programming | /week_4/ex_3.py | 1,341 | 4.3125 | 4 | #This program creates a dictionary from a text file of cars and prints the
#oldest and newest car from the original file
#create a list from the text file
def car_list():
car_list = [] #Empty list
with open ("cars_exercise_3.txt" , "r") as car_data: #Open text... | true |
c546d7555f99c6bb2b2fa6d0266e6615256aecb2 | pieland-byte/Introduction-to-Programming | /week_3/ex_2.py | 1,309 | 4.625 | 5 | #This program calculates the volume of given shapes specified by
#the user using recursion
import math
# creating a menu with options for user input
def main_menu():
menu_choice = input("Please type 1 for sphere, 2 for cylinder and 3 for cone: ")
if menu_choice == "1":
result = sphere(int(inp... | true |
119d31f2c4846ba1416da750b0e87a38d77509f3 | pieland-byte/Introduction-to-Programming | /week_4/ex_2.py | 1,159 | 4.15625 | 4 | #This program asks the user to name a sandwich ingredient and shows
#corresponding sandwiches from the menu
sandwiches = [] #Empty list
with open ("menu.txt","r") as menu: #Read menu.txt
for line in menu: #For each line
sandwiches.append(line.... | true |
401075a7b543a9eb6a6d81c820a371aa3a24a66f | pieland-byte/Introduction-to-Programming | /week_4/ex_1.py | 546 | 4.1875 | 4 | #This program asks the user to name a sandwich and shows corresponding
#sandwiches from the menu
sandwiches = []
with open ("menu.txt","r") as menu:
for line in menu:
sandwiches.append(line.rstrip("\n"))
def sandwich_choice():
choice = input("Enter which sarnie you would like: ")
for... | true |
0cbb1fbbfac2c26c8bba84d4ae8ca5a74ec76b98 | ioana01/Marketplace | /tema/consumer.py | 2,311 | 4.28125 | 4 | """
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
from threading import Thread
import time
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
"""
... | true |
4ff3e99a408d896b4260680980b204794cae01f4 | dnaport22/pyex | /Functions/averageheight.py | 1,081 | 4.15625 | 4 | #~PythonVersion 3.3
#Author: Navdeep Dhuti
#StudentNumber: 3433216
#Code below generate answer for question::
#What is the average value of the numbers in the field [height] in the range(1.75)and(2.48)inclusive?
#Function starts
def Average_height(doc_in):
doc = open(doc_in+'.csv','r') #Open the input file came ... | true |
a9fb3bc90fe2ce347f1ca6ea02239760e35963e6 | PhaniMandava7/Python | /Practice/Sets.py | 591 | 4.40625 | 4 | # Sets are collection of distinct elements with no ordering.
# Sets are good at membership testing.
# empty_set = {} -------> this creates a dict.
empty_set = set()
courses_set = {'History', 'Physics', 'Math'}
print(courses_set)
courses_set.add('Math')
print(courses_set)
print('Math' in courses_set)
courses_set =... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.