blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e7572d9c14c53c4ea50d2d2206d4710819de753a | jjerry-k/learning_data_structure | /Tree/Priority_queue.py | 1,961 | 4.28125 | 4 | # Priority queue
# Abstract data type
# Using heap
def swap(tree, index_1, index_2):
temp = tree[index_1]
tree[index_1] = tree[index_2]
tree[index_2] = temp
def heapify(tree, index, tree_size):
left_child_index = 2 * index
right_child_index = 2 * index + 1
largest = index
if (0 < le... | true |
6ddc98e49f12be54ad29d6ef0a70a6a9d4e75b49 | Minal2179/NLP-programs | /src/utils.py | 1,567 | 4.1875 | 4 | import sqlite3
# initialize the connection to the database
def db_connection():
connection = sqlite3.connect('chatdata.sqlite')
cursor = connection.cursor()
# create the tables needed by the program
create_table_request_list = [
'CREATE TABLE words(word TEXT UNIQUE)',
'CREATE TABLE sentences(sentence ... | true |
5ccff8703e594071092bf05fb3f7a2055e06f4b8 | mr-c/george_murray | /python_tutorials/sentdex_introduction/dna_complement.py | 328 | 4.15625 | 4 | sequenceInput = input("Find the reverse complement of this sequence: ")
def reverseComplement(sequenceInput):
complement = {'A':'T', 'C':'G', 'G':'C', 'T':'A'}
reverseComplement = []
for in sequenceInput:
reverseComplement = complement[base] + t
return reverseComplement:
print(reverseCompl... | true |
c767575b68cbebef0b28f58d1eb202cead6b5248 | subiksharaman1/Rock-Paper-Scissors-Python | /Rock Paper Scissors.py | 1,127 | 4.1875 | 4 | import random
yourCount, computerCount = 0, 0
while True:
userin = input("Rock, paper or scissors? ").upper()
randNum = random.randint(0,2) #to generate computer's play
myList = ["ROCK", "PAPER", "SCISSORS"]
if userin == "ROCK":
uservalue = 0
elif userin == "PAPER":
userva... | true |
929b51ad32bcbd56b6a330abea6076ccead0fbda | rumen89/programming_101_python | /week_1/sum_numbers.py | 639 | 4.125 | 4 | # Implement a Python script, called sum_numbers.py that takes one argument - a
# filename which has integers, separated by " ".
#
# The script should print the sum of all integers in that file.
import sys
def sum_numbers(string):
result = 0
number = '0'
for char in string:
if '0' <= char <= '9':... | true |
1fc8d328c2c6a67ca1098d958deb9f2320ed5ac1 | oliiiiiiiiiiiii/HowToFixPythonErrors | /Examples/RecursionErrorSolve.py | 568 | 4.15625 | 4 | # So lets create a function
def func(x):
return func(x)
# this would immediately raise RecursionError since calling this function will go on forever and ever
# you can see the maximum recurstion limit by printing sys.getrecursionlimit() like this
import sys
print(sys.getrecursionlimit())
# to fix a recursion er... | true |
87aa8ea053bb765dfeeaf9c0bf29c1b9928cd355 | LinnierGames/Core-Data-Structures | /source/search.py | 2,760 | 4.28125 | 4 | #!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return linear_search_recursive(array, i... | true |
772e631557fd8381e2201e98ea0008b55d82dcb3 | jjack94/python-code-samples | /day-calc-jj.py | 422 | 4.375 | 4 | # James Jack
# 1/28/21
# this program takes the starting weekday/number of days gone and gives the weekday of the return
start = input("what day of the week did you leave? please input between 0-6 (0=sunday/6=saturday")
start = int(start)
days_gone = input(" how many days were you gone for?")
days_gone = int(da... | true |
3b8d44aa019ceb6ef2fc545ffde159c57d6ed00b | SL-0305/Assignment-1 | /Assignment1_7.py | 334 | 4.25 | 4 | # Write a program which contains one function that accept one number from user and returns true
# if number is divisible by 5 otherwise return false.
def num(x):
if(x%5 ==0):
print("Number is divisible by 5")
else:
print("Number is not divisible by 5")
x=(int(input("Enter the numb... | true |
20e3b3cf9239e32b7a4783dad33830ddd09c28b9 | lraynes/cheat_sheets | /5.5-Saturday/comprehension.py | 1,633 | 4.25 | 4 | prices= ["24", "13", "16000", "1400"]
#convert string to integer within all of list by looping through
price_nums = [int(price) for price in prices]
print(prices)
print(price_nums)
dog = "poodle"
letters = [letter for letter in dog]
print(letters)
print(f"we iterate over a string into a list: {letters}")
#capitalize... | true |
66c5876716099ac5bc870032a5f4a98815b43717 | lraynes/cheat_sheets | /5.1-Tuesday/basic_variables.py | 351 | 4.15625 | 4 | my_name = input("What is your name?")
neighbor_name = input("what is your neighbor's name?")
my_coding = int(input("How many months have you been coding?"))
neighbor_coding = int(input("How many months has your neighbor been coding?"))
print(my_name + ", " + str(my_coding) + " months")
print (neighbor_name + ", " + st... | true |
9a75cb732c37aec181ec1b3573ed9ae46d55b9ed | Dheerajkg/py-4-everybody | /wk03/Assign 3.1.py | 676 | 4.21875 | 4 | #3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use inp... | true |
edf13334d1dbccb818dcd8714d52456ec91d8a0f | unblest/python | /ex35-2.py | 536 | 4.15625 | 4 | # a little 'what happens if' scenario
# basically, what happens if I have an 'if' function with an elif, but no else and something happens not covered by the 'if' function?
# turns out that nothing at all happens
# like actually nothing, so if you're expecting the if to return something (value, variable, function kick-... | true |
43f8d2211cf92bdf6f63f1644987ac57a3fa8ab4 | unblest/python | /ex4.py | 1,116 | 4.25 | 4 | # variable test file
# defines number of cars
cars = 100
# defines available space in a car
space_in_a_car = 4.0
# defines number of drivers
drivers = 30
# defines number of passengers
passengers = 90
# defines cars_not_driven as the number of cars minus the number of drivers lets see what happens if we scoot past this... | true |
d8a8d80cb0aa64c09cfb783dfcf78f8a41151a12 | anderfernandes/COSC1315 | /chapter3/Fernandes_Chapter_3_3.py | 556 | 4.15625 | 4 | # Name: Anderson Fernandes
# Date: September 13, 2017
# Description: Exercise 3, Chapter 3
grade = input("Enter a grade: ")
try:
grade = float(grade)
# Check if grade is out of range
if (grade < 0.0 or grade > 1.0):
print("Bad score")
else:
# Find letter grade
if (grade >= 0.9):... | true |
17a7e013bb93ed7e5f1694dc21d72abcb6cdc445 | bmk15897/Prerequisite-Assignments | /frequencyApp.py | 1,236 | 4.25 | 4 | '''
Assignment 2 - Write a program to find frequency of each distinct word in a given text file ‘input.txt’. Your Output
should be stored in a different file named ‘output.txt’ in alphanumeric order. Each line should
contain the word and its frequency separated by a comma. (if numeric values are present in file
they sh... | true |
e63d5be51fa356483a51acc355914e8450f46c19 | RhysLewingdon/COM404 | /2-Decisions/beeppainting.py | 573 | 4.21875 | 4 | def directioncode():
direction = input("Which direction should I paint in? ")
if direction == "up":
print("I am painting in the upward direction!")
elif direction =="down":
print("I am painting in the downward direction!")
elif direction =="left":
print("I am painting in the lef... | true |
907c4b7450d11eeccc3a5a356faf5a3ddb4a46f9 | RhysLewingdon/COM404 | /2-Decisions/NestedDecisions.py | 750 | 4.125 | 4 | firstlook = input("Where should I look? ")
if firstlook == "in the bedroom":
secondlook = input("Where in the bedroom should I look? ")
if secondlook == "in the cupboard":
print("Found some mess but no battery.")
else:
print("---------")
elif firstlook == "in the bathroom":
secondlook = ... | true |
b1476310b78859982e2c1c2f3c45f6aacd958a20 | PallabPandaOwn/python101 | /variables/venv/src/Assignment-6/assignment-6-solution-2.py | 981 | 4.46875 | 4 | # Assignment 6
# Create a function that takes in two parameters: rows, and columns, both of which are integers.
# The function should then proceed to draw a playing board (as in the examples from the lectures) the same number of rows and columns as specified.
# After drawing the board, your function should return True.... | true |
fb40d5c8310767bfde315a33f45a355a9ee19703 | pitzcritter/CodingDojo--Python | /16 Dictionary in, tuples out.py | 802 | 4.21875 | 4 | #Assignment: Dictionary in, tuples out
#Write a function that takes in a dictionary and returns a list of tuples where the first tuple item is the key and the second is the value. Here's an example:
### function input
#my_dict = {
# "Speros": "(555) 555-5555",
## "Michael": "(999) 999-9999",
## "Jay": "(777) 777-77... | true |
93a79d4b7a6e850940f4273dd7acf56f1f9eeb0b | mattalhamilton-zz/Python-and-Bash-Scripts | /Mod02Tutorial.py | 2,562 | 4.21875 | 4 | ##Matthew Hamilton
##Mod 02 Tutorial
import random
def rando_insert(thing_being_inserted):
position = random.randint(0,9)
my_list.insert(position, thing_being_inserted)
counter = 0
my_list = []
while counter < 10:
list_item = input('Please enter a word or a number: ')
my_list.app... | true |
e45f96adbf1b1e13f47a1038100542f5089c3174 | minhld99/Data-Structure-and-Algorithms-in-Python | /SelectionSort/SelectionSort.py | 626 | 4.15625 | 4 | # Selection Sort
def selectionSort(array):
for i in range(len(array)):
index = i
for j in range(i+1, len(array)):
if array[j] < array[index]: # Ascending Order
index = j # Find smallest element
if index != i: swap(array, index, i) ... | true |
db311282123ef6391f78de33be38a30fcf1ae0ac | piyush09/LeetCode | /Valid Parentheses.py | 1,672 | 4.15625 | 4 | """
Algo: An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
An empty string is also considered valid.
If opening bracket, push it onto the stack
If closing bracket, then check the element on top of the stack. ... | true |
a62d37fd43ffb0159ed660d559dfbaa900b25328 | piyush09/LeetCode | /Climbing Stairs.py | 636 | 4.15625 | 4 | """
Algo: Use concept of Fibonacci number
Fib(N) = Fib(N-1) + Fib(N-2)
Find nth number of the fibonacci series with Fib(1)=1 and Fib(2)=2.
T.C. - O(N) - Single loop upto n to calculate nth fibonacci number.
S.C.- O(1) - Constant space is used.
"""
def climbStairs(n):
if (n == 1):
return 1
first... | true |
7d6f74a667a6d43df0f8cbb77f11279ac64056ee | piyush09/LeetCode | /Invert Binary Tree.py | 1,566 | 4.21875 | 4 | """
Algo: Call invert of left subtree, call invert of right subtree.
Swap left and right subtrees.
Time and Space complexities similar to Tree traversal time and space complexities.
T.C. - O(N) - 'N' is the number of nodes as calculated by Master theorem.
S.C. - O(N) - Explained below - When tree is completely s... | true |
3cc47b4b74284b03e3fee038af7a71adb3ade386 | piyush09/LeetCode | /Product of Array Except Self.py | 1,008 | 4.53125 | 5 | """
Algo: Initialise output array corresponding to each element.
Calculate the product of numbers to the left of each array element
Calculate the product of numbers to right of each array element
T.C. - O(N), 'N' number of items in nums list, as two for loops to iterate through the numbers
S.C. - O(N), Out... | true |
b83d7216748e58b73d8b344a8f29f3b1ff39ac82 | vtphan/Graph | /example.py | 872 | 4.25 | 4 | from graph import Graph, DGraph
print("Example of unweighted undirected graph")
G = Graph()
G.add(2,3) # add edge (2,3); (3,2) is automatically addeded.
G.add(3,5) # add edge (3,5); (5,3) is automatically addeded.
G.add(3,10) # add edge (3,10); (10,3) is automatically addeded.
print(... | true |
f8a266e34c14259927ddc819901b9043f1630559 | lamwilton/DSCI-553-Data-Mining | /HW4/test.py | 2,359 | 4.34375 | 4 | # Python3 Program to print BFS traversal
# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict
import networkx as nx
import matplotlib.pyplot as plt
# This class represents a directed graph
# using adjacency list representation
class Graph:
# Construc... | true |
d71078dc702fc51e10036779ab14e796e5af64bf | arnav13081994/python-deepdive | /python-problems/main.py | 1,540 | 4.40625 | 4 | # Implement a class Rectangle
class Rectangle:
def __init__(self, height, width):
""" Initialises an instance of the Rectangle Class"""
# _width and _height are internal (private) Rectangle Instance's attributes. This is something
# We keep to ourselves to make sure the User can't just update these attrs rando... | true |
a97cad540333cf0c7095454117b8453fa5ff3e63 | srikanthpragada/PYTHON_17_JUN_2021 | /demo/oop/sum_of_numbers.py | 299 | 4.15625 | 4 | # Accept 5 numbers and display total
# Make sure invalid numbers are ignored
total = 0
count = 1
while count <= 5:
try:
num = int(input(f"Enter Number {count} :"))
total += num
count += 1
except ValueError:
print("Invalid Number!")
print("Total :", total)
| true |
78918e02e1d80ecb19c4956e4f81a992f828204a | krishnasairam/sairam | /cspp1-assignments/m22/assignment1/read_input.py | 288 | 4.34375 | 4 | '''
Write a python program to read multiple lines of text input and store the input into a string.
'''
def main():
'''printing string'''
int_input = int(input())
for _ in range(int_input):
string = input()
print(string)
if __name__ == '__main__':
main()
| true |
eba393633d02982f36662cf070b6cb8ccff695be | krishnasairam/sairam | /cspp1-assignments/m7/Functions - Assignment-1/assignment1.py | 859 | 4.1875 | 4 | '''credit card company each month.'''
def paying_debtoff(previous_balance, annual_interest, monthly_payment_rate):
'''updated_balance'''
monthly_interest = (annual_interest) / 12.0
updated_balance = previous_balance
i_temp = 1
while i_temp <= 12:
monthly_payment = monthly_payment_rate * upd... | true |
628f709ae0400b44a40d7d62f362f8f13a5c7f3f | Abhinav-Bala/ICS3U | /problem_set_1/hypotenuse_calculator.py | 892 | 4.4375 | 4 | # Abhinav Balasubramanian
# Feb. 18, 2021
# ICS3UO-C
# This program will output the length of the hypotenuse given the two other sides of a triangle
import math # imports the math library
print('Hello, this program will calculate the legnth of the hypotenuse of a right-triangle.') # prints welcome message
# INPUT
si... | true |
d99a4e06de6a02d7862be368a3e16e4872ef5aee | Abhinav-Bala/ICS3U | /problem_set_2/leap_year_checker.py | 815 | 4.1875 | 4 | # Abhinav Balasubramanian
# March 1, 2021
# ICS3UO-C
# This program will check whether an inputted year is a leap year or not
#INPUT
print("This program will check to see whether a given year is a leap year.") # displays welcome message
year = int(input("Please enter a year: ")) # gets user input for year and then cas... | true |
857bd453c9a11176d797fd4f288ca4300869782a | Abhinav-Bala/ICS3U | /problem_set_2/integer_classifier.py | 1,275 | 4.21875 | 4 | # Abhinav Balasubramanian
# March 1, 2021
# ICS3UO-C
# This program will check whether an inputted integer is even or odd and positive, negative or zero
#INPUT
print("This program will determine whether an integer is even or odd.\nIt will also determine if the integer is positive, negative or zero") # displays welcome... | true |
c1f8ff78272f8ed6b31bcc67d213abc124aba27d | patchen/battleship | /src/queue.py | 1,063 | 4.15625 | 4 | class EmptyQueueError(Exception):
'''Raised when pop is called on an empty Queue.'''
pass
class Queue(object):
'''A First-in, first-out (FIFO) Queue of items'''
def __init__(self):
'''(Queue) -> None
A new empty Queue.
'''
self.contents = []
def __st... | true |
3f408c1c2d8d338e47358196c085d7cdfcb83d4c | TimLatham/Udacity_Projects | /Intro_to_Programming/Stage2/productList.py | 666 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 08 11:42:46 2017
@author: tim.latham
"""
# Define a procedure, product_list,
# that takes as input a list of numbers,
# and returns a number that is
# the result of multiplying all
# those numbers together.
def product_list(list_of_numbers):
product = ... | true |
480c91a41ef1908fa06bea190e258477d28ca7d7 | SuperMartinYang/learning_algorithm | /leetcode/easy/Balanced_Binary_Tree.py | 1,215 | 4.15625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
a height-balanced binary tree is defined as a binary tree in which the de... | true |
155032d5e5c60b31d7c9ee313a3d27161cbb5f6e | lindaduong25/PythonChooseYourOwnAdventureGame | /FirstGame.py | 1,667 | 4.1875 | 4 | print("Welcome to Random Guessing!")
name = input("What is your name? ")
age = int(input("What is your age? "))
points = 20
if age >= 15:
print("You are old enough to play!")
wants_to_play = input("Do you want to play? ").lower()
if wants_to_play == "yes":
print("Let's begin then!")
print... | true |
902571ea8243955347359783adc96ff2a611c83d | pildurr/indexing | /indexing.py | 316 | 4.34375 | 4 | """Given a string of any length named s.
Extract and then print the first and last characters of the string (with one space between them).
For example, given s = 'abcdef'
the output will be
a f"""
s = input("Input a string: ")
s_first = s[0]
s_last = s[-1]
s_modified = s_first + " " + s_last
print(s_modified) | true |
a859edb41cd4e5781e9e677f9a083eb38d802483 | giosermon/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-append_write.py | 400 | 4.40625 | 4 | #!/usr/bin/python3
""" Append to a file """
def append_write(filename="", text=""):
"""Function to append a text in a file
Args:
filename (str): Name of the file to append to.
text (str): Text to append to the file.
Return:
The numbers of characters written.
"""
with o... | true |
f6c81a96ef98a1d413ba85ab89209ef920b894bf | MaunikQ/Sample | /Assesment Python/Q14.py | 229 | 4.125 | 4 | def power_of_two(n):
if(n==1):
return True
if(n%2==0):
return power_of_two(n/2)
else:
return False
if __name__ == '__main__':
num = int(input('Enter the number to be checked: '))
power = power_of_two(num)
print power | true |
6ebd58bb8157899588ca6376671ac33f40919007 | sunil2982/python_core | /story.py | 1,299 | 4.375 | 4 | #initializing variables
girlname = " "
boyname = " "
girl_desc = " "
boy_desc = " "
walk_desc = " "
animal = " "
gift = " "
answer = " "
#taking input from user
girlname=input("enter a girl name")
girlname=girlname.capitalize()
boyname = input("input a boy name")
boyname = boyname.capitalize()
girl_desc= input("enter... | true |
71171fbe056a8efc0134caee636e0abcb1a86e5c | sunil2982/python_core | /forloop_turtle.py | 279 | 4.15625 | 4 | import turtle
numsides = int(input("how many sides you want ??"))
tut=turtle.Turtle()
for step in range(numsides):
tut.forward(step+100)
tut.right(360/numsides)
for step in range(numsides):
tut.forward(step+70)
tut.right(360/numsides)
turtle.done() | true |
32d5718ae55bee81b9617efb2a96506c28280ecd | WangYangLau/learnpython | /dict.py | 509 | 4.125 | 4 | # -*- coding:utf-8 -*-
#dict
index = False
print('dict')
d = {'Michael':80,'Lisa':95,'Jack':72,'Bart':0}
d['Bart'] = 98
while index==False:
print('enter the name you find:')
name = input()
index = name in d
if index==False:
print('Without this guy,Do you want to insert one?(yes/no)')
a = input()
if a=='yes':... | true |
7b33c4306d1b85d58244af8db01481bac45cd763 | ceirius/teaching-python | /rectangle 1.py | 738 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
write a program to compute area of a rectangle
"""
class Rectangle:
length = 0
breadth = 0
def __init__(self, length, breadth):
self.breadth = breadth
self.length = length
# print(self.length, self.br... | true |
1e2e1fec71c9fc5657d9b4931d0d825741280711 | joselufb/Sudoku_Solver | /200914_Sudoku_Solver.py | 1,877 | 4.15625 | 4 | '''
Python array Sudoku solver
References:
https://towardsdatascience.com/solve-sudokus-automatically-4032b2203b64
'''
# Example of sudoky board
# Gaps are represented with number 0
board_test = [
[0, 0, 9, 8, 0, 0, 7, 6, 0],
[5, 0, 3, 6, 0, 7, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 3, 0, 5],
[2, 5, 0, 0, 8, 0, 6, 0, 0],
[0, 9... | true |
cd64ee861ad81f45fad453c188e83e46fad005b7 | soberoy1112/Lintcode | /my_answer/454.py | 787 | 4.125 | 4 | #/usr/bin/env python3
# -*- coding: utf-8 -*-
class Rectangle(object):
def __init__(self, width, height):
self.__width = width
self.__height = height
def setArea(self, width, height):
if width > 0 and height > 0:
self.__width = width
self.__height = height
else:
print('Sorry, we don\'t acc... | true |
78c45bfb60be63747dcbed7872731067edf76d4f | ravenusmc/flask_weather | /basic.py | 1,718 | 4.15625 | 4 | #This file will contain information to display basic information.
import pandas as pd
import numpy as np
#This class will be used to pull weather information for me
class Weather():
#I was using this method to set up the initial attribute but I needed
#to reset the attribute each time I used it.
# def __... | true |
f8b40ee65abf9adb5187079836a9e5cd6b3be4d3 | sudonitin/dsa | /sorting/algorithms/selection_sort.py | 1,316 | 4.21875 | 4 | ''' selection_sort.py
############### NOTES ###############
=> From GFG
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1) The subarray whi... | true |
1e77ca5042a4c3093dfe60ed40777c1fbab53b98 | branhoff/automation_class | /1.FilenamesAndFilepaths/rename_files.py | 1,464 | 4.25 | 4 | # import modules we'll need
import datetime
import os
def get_curr_month_name():
"""
Pulls current month as long form name i.e. "January"
"""
today = datetime.date.today()
curr_month = today.strftime("%B")
return curr_month
# Function to rename multiple files
def main():
print(os.getc... | true |
9f8bf1d75c990ffe082f866e9284e66ec70face2 | blakexcosta/Unit3_Python_Chapter10 | /main.py | 557 | 4.15625 | 4 | import turtle
# defining a method and default value
def add_list_numbers(list_name=[1, 2]):
total = 0
for number in list_name:
total = total + number
return total
# palindrome checker
def is_palindrome(orig_string):
letters_list = list(orig_string)
letters_list.reverse()
rev_string... | true |
26308787dd7f1c240868fbc8d93f3886a2c320f0 | parthcode/PythonMorningBatch | /caseAndOperators.py | 847 | 4.15625 | 4 | """
1.If else statement
These are the case statement in python which executes a block of code based on a condition
2.operators
comp : > , < , == , !=, >= , <=
"""
# x = 90
# y = 10
# print("sum", x + y)
# print("difference", x - y)
# print("product", x * y)
# print("Divide", x/y)
# print("reminder", x % y)
"""
check if... | true |
dee38444d6f8a2f8c2aa551cb4eea9bdaa497743 | nathanvanderleest/python | /while.py | 314 | 4.1875 | 4 |
# while loops
#use Ctrl+C to terminate the program.
import random
num1 = random.randint(1,6)
print("Guess the number:", end=" ")
guess = int(input())
count = 1
while guess != num1:
guess = int(input("Guess again: "))
count += 1
print("Your Right! It took you", count, "guesses")
| true |
25b43575af8086bb90db7271aecf7476668771af | nyy7/supermarket_register | /scripts/register.py | 904 | 4.125 | 4 | #!/usr/bin/python
#########
# author: Yanyan Ni
# date: 12/15/17
# description: a function to run calculator and print proper output
#########
from calculator import Calculator
import sys, os
def run(sku):
register = Calculator(sku)
if register.input_validation():
total_price = register.price_calculator()
#print... | true |
d4e829315440537e1934c6650fe835b8d9216555 | srane96/Data-Structure-and-Algorithms-Using-Cpp-and-Python | /Python/linked_list.py | 2,976 | 4.28125 | 4 | class Element(object):
""" Element object represents each element in the linked list."""
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinkedList(object):
""" Linked list manages all the Element objects. """
def __init__(self, head=None):
s... | true |
8fad61fa51fa6835a34e3abc8f3d0cba86b90229 | srane96/Data-Structure-and-Algorithms-Using-Cpp-and-Python | /Python/selection_sort.py | 583 | 4.1875 | 4 | def selection_sort(input_array):
""" Get the smallest element and put it in the front. """
for i in range(len(input_array)):
smallest = input_array[i]
smallest_ind = i
for j in range(i+1,len(input_array)):
if input_array[j] < smallest:
smallest = input_array[j... | true |
adf32b219f9121da3445ad7e34316fae972d79d3 | illusionist99/Python_BootCamp_42 | /module00/ex01/exec.py | 365 | 4.15625 | 4 | import sys
args = sys.argv[1:]
args.reverse()
displayed = ""
for word in args:
for letter in word[::-1]:
if letter.islower():
displayed += letter.upper()
elif letter.isupper():
displayed += letter.lower()
else:
displayed += letter
if word != args[-1]... | true |
6888d2e97d55e36f5483bac4682ba1231c4a29c3 | isaackrementsov/led-circuit | /Blinking_LED.py | 1,307 | 4.1875 | 4 | # Isaac Krementsov
# 3/8/2020
# Introduction to Systems Engineering
# Blinking LED - Controls two blinking LED lights
import RPi.GPIO as GPIO
import time
# GPIO pin numbers where the red and yellow LED circuits are connected
RED_PIN = 18
YELLOW_PIN = 24
# Set the GPIO header board to Broadcom Model setup
GPIO.setm... | true |
514acdf2ac68d64a26b1f913e4e5bbed05b6a495 | cpm205/ML_algorithm | /python/data_normalization/data_normalization.py | 1,182 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 12:23:07 2019
@author: derekh
"""
"""
It is a technique we use in Machine Learning and Deep Learning is to normalize our data.
It often leads to a better performance because gradient descent converges faster after normalization.
"""
"""
Implement normalizeRows() to ... | true |
b2785d0c67d2de85f4674cb5263b3e0599505a07 | rahulshivsharan/LearnPython01 | /ex27.py | 879 | 4.28125 | 4 |
def fun01():
nList = [2,4,3,7]
print("Original List ",nList) # printing original list
# looping through list 'nList' and multiple each element by 2
newList = [x*2 for x in nList]
print("Mulitply each element by 2")
print("Product of 2 ",newList)
nList = [12,45,15,67,28,19]
print("... | true |
05078c86bcc8680eef50048f60759c3052f33617 | acirederf/freddie-learns-python | /ex3.py | 1,283 | 4.5 | 4 | # This will print the thing it says.
print "I will now count my chickens:"
# This will print "Hens" and then calculate 25 plus 30 divided by 6
print "Hens", 25 + 30 / 6
# This will print "Roosters" and calculate the remainder of 100 minus the remainder of 75 divided by 4, which is 3.
print "Roosters", 100 - 25 * 3 % 4... | true |
0431197032b26c56e24d73e5ea7d48cce4cff33f | FrancescoSRende/Year9DesignCS-PythonFR | /AbusiveSovietCalculator.py | 1,244 | 4.3125 | 4 | import math
import os
os.system("say -v Milena Привет! I do addition for you, yes?")
input("Привет! I do addition for you, yes? ")
os.system("say -v Milena Too late, I do anyway!")
print("Too late, I do anyway!")
os.system("say -v Milena Give me number")
add_1 = input("Give me number: ")
os.system("say -v Milena One mo... | true |
40a107b297d30796397f97d0a4613944a69fca23 | gup-abhi/translation | /translator.py | 2,013 | 4.15625 | 4 | # importing all from tkinter
from tkinter import *
# importing Translator from googletrans
from googletrans import Translator
# creating window
win = Tk()
# giving title to the window
win.title('translator')
# specifying size of our window
win.geometry('500x100')
select = ""
# creating a function to get language
def ... | true |
db38d88c3a38e9322d95f87fc18333af881a3f74 | akkharin1/6230405347-oop-labs | /6230405347-oop-lab03 (1)/lab3_extra.py | 1,813 | 4.1875 | 4 | def lab3_special():
while True:
try:
first_number = check_quit("Enter the first number:")
second_number = check_quit("Enter the second number:")
operator = str(input("Enter the operator"))
except ValueError:
break
if operator == "+":
... | true |
a34b5049b40d1707a784aa4635f1a68ce9256642 | AbdulMalik-Marikar/COMP-1405 | /Guntha-Board.py | 1,775 | 4.28125 | 4 | #Abdul-Malik Marikar
#101042166
#Key Reference: Starting out with python 3rd edition
#---next 2 lines from Abdul Siddiqui. used to clear screen
import os
os.system("cls")
#one guntha is equal to 101.7 square meters
guntha = 101.17
#one board is equal to 0.007742 square meters
board = 0.007742
#function concept from ... | true |
731e965139d80cde23cf1a3dc9f95f6995d1a566 | li-poltorak/code_guild_labs | /dec_11/cars/car.py | 1,061 | 4.28125 | 4 | # Create a Car class with some attributes typical of automobiles, then use it to
# create some instances of different cars.
#
# Create a new directory called cars
# Create the following 2 files inside the cars directory: main.py and car.py
# In car.py, create a class called Car with the following characteristics:
# A s... | true |
bc65b9eb05b8e1eefb7be206cee4d664a3e0ef8a | glock3/Learning- | /Misha/Numbers/fast_exponentation.py | 360 | 4.375 | 4 | def pow(value, power):
result=1
if power != 0:
for index in range(power):
result *= value
return result
if __name__=="__main__":
print('This program requires two integers and returns value in power\n')
value=int(input('Enter value: '))
power=int(input('Enter power: '))
... | true |
35d1e730a7dd63f902a154a8b8e49e656610cdc3 | pawarspeaks/HacktoberFest_2021 | /python/Phone-Directory/main.py | 2,160 | 4.40625 | 4 | # Python program to implement a phone directory using arrays
# Array to store Contacts
directory = []
# To create a contact
def create_contact():
contact = []
name = input("Enter Name: ")
phone = int(input("Enter phone number: "))
contact.append(name)
contact.append(phone)
directory.append(con... | true |
586872568e78be78907e1d761c90af565d494b7c | pawarspeaks/HacktoberFest_2021 | /python/Python-cipher-program/cipher.py | 2,932 | 4.15625 | 4 | #program with different cipher algorithms
import base64
def rot13():
ch='y'
while ch=='y' or ch=='Y':
print("Menu:") #menu for asking choice
print("1.Cipher a message")
print("2.Decipher a message")
choice=int(input("Enter your choice: "))
i... | true |
5f205ba2255ff3f19a1b39dc92b2365a73a6267d | pawarspeaks/HacktoberFest_2021 | /python/insertion_sort.py | 796 | 4.4375 | 4 | # A program to implement insertion sort
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1 # j = index no of sorted element
while j >=0 and key < arr[j] : # if element of unsorted list is less than sorted one, it will swap
arr[j+1] = arr[j]
... | true |
462d2b7e8520f86dd1a470ef9188d1ca4881734a | TheGoodReverend/LetterCode | /LetterCode.py | 1,640 | 4.125 | 4 | #! /user/bin/env python3
#Letter Code by KBowen
from LetterCodeLogic import LetterCodeLogic
#from filename import class
def getChoice():
choice = -1
#while (choice > 0 and choice <3)
while (choice!=0):
try:
choice = int(input("Choice? (1=Encode, 2=Decode, 0=Quit... | true |
dd4e8ebb6559bc46730e00239a63d1f576a34fe5 | Mr-MayankThakur/My-Python-Scripts | /Algorithms/Sorting/merge_sort.py | 1,118 | 4.5625 | 5 | def merge_sort(lst, reversed = False):
"""
Sorts the given list using recursive merge sort algorithm.
Parameters
----------
lst (iterable)- python which you want to search
reversed (bool): sorts the list in ascending order if False
Returns
-------
sorted_list
"""
if len(ls... | true |
b4579540cb8f9b77209d2019ae7528bcf64efd26 | chttrjeankr/codechef2k19-dec6 | /MUL35/program.py | 670 | 4.28125 | 4 | """
Problem Statement:
If we list all the natural number below 20 that are multiples of 3 or 5,
we get 3,5,6,9,10,12,15,18. The sum if these multiples is 78.
Find the sum of all the multiples of 3 or 5 below N.
"""
def SumDivisibleBy35(n,target):
"""
Returns the sum of all the multiples of 3 or 5 below N
... | true |
0a078dc2a9ec31df291f13cedb133988f99900b3 | mehaktawakley/Python-Competitive-Programming | /ArmstrongNumber.py | 849 | 4.3125 | 4 | """
For a given 3 digit number, find whether it is armstrong number or not. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3^3 + 7^3 + 1^3 = 371
Input:
First line contains an integer, the number... | true |
ec5e4826b8bbe03f8c0b73d22258bf42b363c73d | rigo5632/CS-2302-Data-Structures | /Lab1/lab1C.py | 1,058 | 4.25 | 4 | # Lab 1
# By: Rigobeto Quiroz
# Class: 1:30 PM - 2:50 PM MW
# This program will draw a binary Tree. The tree will create a center point
# and will generate branches to the left and to the right according to center point
# the more recursion calls the more branches the tree will have. Each branch will have
# two childre... | true |
834a62bd5a68029a4ad27a7a0b4807b591de29f7 | icebowl/python | /ed1/3.4.1.py | 530 | 4.125 | 4 | '''
Input a word.
If it is "yellow" print "Correct", otherwise print "Nope".
What happens if you type in YELLOW? YellOW?
Does the capitalizing make a difference?
color = input("What color? ")
if (color == "yellow"):
print ("Correct")
else:
print ("Nope")
color = input("What color? ")
cString = color.lower(... | true |
2a3dbfc45a73b2173af5b4cd3a0afeaf6869687d | icebowl/python | /ed1/3.5.py | 368 | 4.125 | 4 | # your code goes here
'''
Input a grade number (9 - 12) and print
Freshman, Sophomore, Junior, Senior.
If it is not in [9-12], print Not in High School.
'''
g = int(input("What grade are you in ? "))
if(g == 9):
print("Freshman")
elif (g==10):
print("Sophomore")
elif (g==11):
print("Junior")
elif (g==12):
prin... | true |
7015096513fd7e28650960e928e4c53010024992 | icebowl/python | /tkinter/drive_turtle_1.py | 472 | 4.125 | 4 | #apt install python3-tk
import turtle
wn = turtle.Screen() # create a turtle
t = turtle.Turtle()
t.color('green') # set the color
t.forward(50) # draw a green line of leng
t.up() # lift up the tail
t.forward(50) # move forward 50 without drawing
t.right(90) # change dir... | true |
19890d597a8050926402d054d783d608cfaf4c66 | icebowl/python | /sift/example-ord.py | 230 | 4.21875 | 4 | #Python ord()
#The ord() method returns an integer representing Unicode code point for the given Unicode character.
print(ord('5'))
# code point of alphabet
print(ord('A'))
# code point of character
print(ord('$'))
print(ord(0))
| true |
f6f7f1143b8ee417fb1ed800e7fa0a370de48804 | UKDR/eng57_2 | /Week_3_Python/lists_basics.py | 1,607 | 4.5625 | 5 | # List
# list are exactly what you expect. They are lists
# they are organised with index. This means it starts at 0
# syntax
# [] = list
print(type([]))
print([]) # just prints the brackets []
print(len([])) # counts the number of items in the list
# example
# defining a list and assigning it to a variable
contact_... | true |
6f982282d53e973469174fdc4e139ec68699aea0 | Jasplet/my-isc-work | /python_work/IO_ex.py | 1,961 | 4.34375 | 4 | #! /usr/bin/python
# Exercise on input and output to files
print 'Part One. \nReading a csv file'
with open( './example_data/weather.csv', 'r') as readfile: #using with means we dont have to worry about closing the file. Readfile is a variable holding the open file pointer
data = readfile.read() #Actually reads ... | true |
8d94faca022abfdeff8c5e2da1a179d7a8ab5596 | EchoZen/Basics | /13. Dictionary.py | 1,367 | 4.46875 | 4 | # Use {} for dictionary
# variable= {"key":"value", "key":"value"...}
#1key:value is considered as 1 element in the dictionary
# To access value in variable, you can use the key
monthConversions= {"Jan": "January",
"Feb": "February",
"Mar": "March",
"Apr":... | true |
a1e8336a366d8c6ce2a7cf086be50799ed654593 | KHulsy/Project_Echo | /App/spaceturtles.py | 1,096 | 4.125 | 4 | (Disclaimer: This was found via Google Fu. I in no way, shape or form coded this. This is absolutely not my work. This is inspiration for Project 3).
# Click in the righthand window to make it active then use your arrow
# keys to control the spaceship!
import turtle
screen = turtle.Screen()
# this assures that the si... | true |
65e23e31dbc4ac23ae5b274408141566e30d9a99 | fgokdata/python | /extra/classes..py | 899 | 4.25 | 4 | # car is object and it has methods (in functions)
class car:
def __init__(self, brand, model, year): #starts the attribiutes
self.brand = brand
self.model = model # shows the features when it is created
self.year = year
def brandmodel(self):
return f'brand of the car {se... | true |
8819dedaa14cf1324ef2276dbcc5d2427720b5e7 | tomvdmade/LearnPython3 | /ex15.py | 885 | 4.4375 | 4 | # from the module named sys, import argv (argument vector > parameters).
# argv is a list containing all the command line arguments passed into the python script you're currently running. (run in the command line vs input)
from sys import argv
# define argv 0 and 1 as script and filename respectively
script, filename... | true |
c4934517e47b92cd457dab5d1a87220f4ba7f465 | rcjacques/Hexapod | /Simulation/more testing.py | 2,522 | 4.125 | 4 | from graphics import *
import math
width = 500
height = 500
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
win = GraphWin('Polygon Rotation Testing',width,height)
def drawGrid():
for i in range(10):
line = Line(Point(i*width/10,0),Point(i*width/10,height))
line.draw(win)
for j in range(10):
line ... | true |
4a15586920f3a7803b527a503a2a8f9e62fe0cff | cash2one/BHWGoogleProject | /pyglib/elapsed_time.py | 1,202 | 4.1875 | 4 | # Copyright 2004-2005 Google Inc.
# All Rights Reserved.
#
# Original Author: Mark D. Roth
#
def ElapsedTime(interval, fractional_seconds=0, abbreviate_days=0):
"""
Returns a string in the form "HH:MM:SS" for the indicated interval,
which is given in seconds. If the time is more than a day, prepends
"DD day(... | true |
a332dcb77ef3acc6c6446df070e5d621648be2d4 | bymestefe/Python_Task | /random_module_example/rock_paper_scissors.py | 1,562 | 4.21875 | 4 | import random
# rock-paper-scissors (taş-kağıt-makas)
# whoever reaches 3 is winner (3'e ulaşan kazanır)
def control_of_winner(u,p):
if u == 0 and p == 1:
print("winner of this stage is pc")
return 0
elif u == 0 and p == 2:
print("winner of this stage is user")
return 1
... | true |
03ff68ef13e367df0d1b6f953c04392843a48509 | gerard-geer/Detergent | /Shower/logger.py | 1,737 | 4.15625 | 4 | from datetime import datetime
class Logger:
__slots__ = ('filename', 'buffer', 'maxBufferSize')
def __init__(maxBufferSize):
"""
Creates an instance of Logger. The output file will be named
the date and time of this instance's creation.
Parameters:
-maxBufferSize(Integer): The maximum number of mess... | true |
ae19d0ea8605c8306f265576d16894dd7657cd14 | annehomann/python_crash_course | /02_lists/numbers.py | 597 | 4.375 | 4 | """ for value in range (1,11):
print (value) """
# Takes numbers 1-10 and inputs them into a list
numbers = list(range(1,11))
print(numbers)
# Skipping numbers in a range
# Starts with the value 2, adds 2 to the value until it reaches the final value of 11
even_numbers = list(range(2,11,2))
print(even_numbers)
# ... | true |
3d3d84f1e1df87f19bf47e31b39f5839829af2aa | annehomann/python_crash_course | /03_if_statements/hello_admin.py | 538 | 4.15625 | 4 | # usernames = ['anne', 'somerset', 'admin', 'sally', 'darius']
# for username in usernames:
# if 'admin' in username:
# print("Hello " + username.title() + ", would you like to see a status report?")
# else:
# print("Hello " + username + ", thank you for logging in today.")
# Using the if s... | true |
b2f93d7064571516d7485ceb9338f76f57a3ac33 | Umangsharma9533/DataStructuresWithPython | /Stack_isParenthesisBalanced.py | 1,144 | 4.25 | 4 | #Import Stack class from the CreatingStack.py file
from CreatingStack import Stack
#define a function for comparing 2 character, Return True if both matches, False if no match
def is_match(top,paren):
if top=='{' and paren=='}':
return True
elif top=='[' and paren==']':
return True
elif top=... | true |
3a9fc64d5d991be4f1bab97747ca1d6482f0d172 | felixzhao/questions | /Linked_Lists/Merge_Sorted_Array.py | 1,136 | 4.21875 | 4 | class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
time O(M + N), M is |copy_num1| which is less then |nums1|
space O(M)
logic:
- copy values from... | true |
dcf02197a487701312bf636007bdd108880e86c6 | felixzhao/questions | /Trees_and_Graphs/Lowest_Common_Ancestor_of_a_Binary_Tree.py | 1,124 | 4.125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.ans = None
def find(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> bool:
"""
... | true |
72d3888348e76741712c9d591a128f0d38a044e6 | ajpiter/PythonProTips | /Stats/%ModuloDivison.py | 910 | 4.5 | 4 | #In addition to standard division using '/' in python you can also use '%' to get modulo or remainder division
----- #Leftover Calculator -----
#Think of % as the leftover calcualtor if you shared everything evenly
#If you have an 8 slice pizza and 3 friends
leftovers = 8 % 3
print(leftovers)
#[output] 2
----... | true |
49dde09fe3d711e05f1c055cb46308f6a72d4b86 | ajpiter/PythonProTips | /Databases/OrderingResults.py | 1,129 | 4.25 | 4 | #Ordering Query Results in SQL Alchmy
#The order_by() command orders from lowest to highest, or alphabetically by default
#Example of building a select statement, appending an order_by() clause and executing the statement
#By Default this sorts alphabetically
stmt = select([tablename.columns.columnname])
stmt = st... | true |
d8a9b8f3f280c85293d01a2f3e108fe53f61fb36 | ajpiter/PythonProTips | /PythonBasics/Function/CreatingFunctions/Basics.py | 2,762 | 4.71875 | 5 | #Functions are useful when you will have to preform the same tasks repeatedly
#Creating your own Function
1. define the function
def function(parameter):
print(parameter + "string")
2. call the function, function()
----- #Basic Function: Outputs a Print Statement -----
def function(parameter, parameter... | true |
3b0ac51f4dfe49fcae7757f3c0403267714eb55d | ajpiter/PythonProTips | /Stats/BinomialDistribution.py | 760 | 4.125 | 4 | #A binomial distrubution is the number of r successes in n Bernoulli trials with probability p of success.
#Example, The number of heads in 4 coin flips of a fair coin.
np.random.binomial(The number of coin flips, the proability of success)
np.random.binomial(4, 0.5)
#To conduct the experiment repeatedly use the ... | true |
8ff1b79dabf59fc2ff3d746878d3f891b602c1ad | ajpiter/PythonProTips | /PythonBasics/Lists/CopyingLists.py | 617 | 4.40625 | 4 | #Usually you want to create a new list, but by using the '=' you accidential create a reference to a list
----- #This creates a copy of the reference to the list -----
x = ['a', 'b', 'c']
y = x
#Which means this will change the elements in both list x and y
y[1] = 'z'
print(x)
print(y)
#output ['a', 'z', 'c']
#... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.