blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
a8c88902f372893a9275d9cc05af29eb1a6fe526 | mpatriak/Python-Hangman | /Hangman.py | 4,607 | 4.15625 | 4 | #!/usr/bin/env python 2
from random import *
player_score = 0
computer_score = 0
# Define the graphics that will be used in the game
def hangedman(hangman):
graphic = [
"""
+-------+
|
|
|
|
|
==============
"""
... |
6cdc61e07a9a2a52d7c07a5a48570e4f2d80c0ce | aliamjad1/Data-Structure-Fall-2020 | /BubbleSorting.py | 571 | 4.28125 | 4 | ##It compares every index like [2,1,4,3]-------Firstly 2 compare with 1 bcz of greater 1 is moved towards left and 2 is on right
# [1,2,4,3]
def bubblesort(list):
listed=len(list)
isSorted=False
while not isSorted:
isSorted=True
for eachvalue in range(0,listed-1):
if list[eac... |
cf7edacf72935e2d409f60cdf3428c0e6f9ea06e | karthiiekeyan/Python_CodingBat.com | /Warmup-2.py | 2,874 | 3.6875 | 4 | # Warmup-2 > string_times
# Given a string and a non-negative int n, return a larger string that is n copies of the original string.
def string_times(str, n):
return n * str
# Warmup-2 > front_times
# Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or
# whate... |
555e2f48b3aa08732b0d95a082bac874a4722b47 | BostonREB/pirate | /pirate.py | 2,200 | 3.671875 | 4 | import random
questions = {
"strong": "Do ye like yer drinks strong?",
"salty": "Do ye like it with a salty tang?",
"bitter": "Are ye a lubber who likes it bitter?",
"sweet": "Would ye like a bit of sweetness with yer poison?",
"fruity": "Are ye one for a fruity finish?"
}
ingredients = {
"str... |
aa8073ad2579bce1c16666358e49db790d5aa9ba | ananth3/Preparation | /array/xor_operations_in_array.py | 463 | 3.65625 | 4 | #Given an integer n and an integer start.
#Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length.
#Return the bitwise XOR of all elements of nums.
# Input: n = 5, start = 0
# Output: 8
# Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
class Solution:
... |
232d26118d39855dac3af1001ecf491e18f1d95d | ananth3/Preparation | /array/Monotonic_Array.py | 239 | 3.609375 | 4 | class Solution:
def isMonotonic(self, A: List[int]) -> bool:
sort_a = sorted(A)
rev_sort = sorted(A, reverse=True)
if A == sort_a or A == rev_sort:
return True
return False
|
b6b7e3dc7cedda894b8fa566a43fe54a9d44a797 | mayerxc/learn-python | /variables.py | 380 | 3.859375 | 4 | GPA = 3.88
studentName = "Chris Mayer"
studentNumber = 34523452345
places = ["Colorado", "Oregon", "Peru", "Chile"]
print(GPA)
print(studentName)
print(studentNumber)
print("\n")
print("%s has the following student number: %d" % (studentName, studentNumber))
print("%s has the following GPA: %.2f" % (studentName, GPA)... |
3b418876d15d528b5ed0b4eda20b1f7041033c8d | explorerwjy/rosalind | /iprb.py | 447 | 3.578125 | 4 | from sys import argv
def factorial(start,stop):
res = 1
while start >= stop:
res *= start
start -= 1
return res
def combine(m,n):
return (factorial(n,n-m+1)+0.0)/(factorial(m,1))
k,m,n = map(int,file(argv[1]).read().split())
print "%.5f"%(combine(2,k)/combine(2,k+m+n)+combine(1,k)*combine(1,m)/combine(2,k+n+m... |
4a117edd4e73e2a8830804061c0f3e61a7ea4865 | trademark152/Data_Mining_USC | /hw5/test.py | 1,156 | 4.15625 | 4 | import re
import random
def isprime(num):
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num // 2):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
retu... |
5b34907079a2d3c0318af36707d6c6ade2bae90d | Steve-D-Eckles/mountain-of-madness-flask-edition | /madness/scenes.py | 7,476 | 3.859375 | 4 | from random import randint
class Scene(object):
def __init__(self):
self.result = []
def enter(self):
self.result.append("Oops, this scene isn't done!")
class MountainExterior(Scene):
def enter(self):
self.result.append("""
You are Otaku Jeff, an adventurer of little renow... |
2f1f46a303bdcc707a33b3bc309982ea9843720d | RodellRodriguez/coding-problems | /leetcode/valid_parentheses.py | 679 | 3.5 | 4 | """https://leetcode.com/problems/valid-parentheses/description/
"""
class Solution:
def isValid(self, s):
def isClosingSymbol(symbol, paren_dict):
if symbol in paren_dict: return True
return False
paren_dict = {
']':'[',
'}':'{',
... |
2f72cadb371281f6e619876de67d74d0d840053f | RodellRodriguez/coding-problems | /leetcode/intersection_of_two_linked_lists.py | 1,288 | 3.921875 | 4 | """
Time Complexity: O(n)
The idea is to preserve the value of the two heads and increment them using temp variables until
either of the temp nodes reach the end. Once that happens, set that temp node to the head of the
other linked list.
The idea is if you switch head, the possible difference between lengths of the ... |
1af343e041242512b048cd47790bc9a7ad5f7f52 | RodellRodriguez/coding-problems | /leetcode/lru_cache.py | 3,821 | 4.09375 | 4 | """ https://leetcode.com/problems/lru-cache/description/
There are 3 main requirements for an LRU cache:
1. Has to be a fixed size set by the user
2. Needs O(1) access and insert for any item
3. Needs a cache eviction policy/algorithm when the cache is full
whereby the least recently used item is deleted upon inse... |
414020d6c4e9c3ec4b2cb844f760a25252310001 | RodellRodriguez/coding-problems | /leetcode/path_sum_I.py | 1,055 | 4.03125 | 4 | """ https://leetcode.com/problems/path-sum/
1.) If root is None then return False
2.) Subtract (root value from sum and update sum to that new value
3.) If root is the leaf then:
if sum == 0:
return True
return False
4.) Recursively call the function for root.le... |
8b398401d12c5c9470dabcf3acf682e91aa3520a | RokKrivicic/webdevelopment2 | /Homeworks/homework1.py | 840 | 4.21875 | 4 | from smartninja_sql.sqlite import SQLiteDatabase
db = SQLiteDatabase("Chinook_Sqlite.sqlite")
# all tables in the database
db.print_tables(verbose=True)
#This database has many tables. Write an SQL command that will print Name
# from the table Artist (for all the database entries)
db.pretty_print("SELECT Name FROM A... |
ec60c2a11fce6cdcbcf73f9e481723d6f62b7a34 | mustazhap/Algorithms-by-Python | /week3/1.py | 572 | 3.5 | 4 | def rpn(data):
lis = []
operators = ['-', '+', '*', '/']
for element in data.split(' '):
if element in operators:
n1 = lis.pop()
n2 = lis.pop()
if element=='-': result = n2 - n1
if element=='+': result = n2 + n1
if element=='*': result... |
4c94b95cc43c2a265025a841eed348c99334fd5f | mottybar/SudokuOOP | /SudokuBoard.py | 2,174 | 4.03125 | 4 | """
Board is a singleton implements class which represents a single board
"""
class Board:
def __new__(self):
if not hasattr(self, 'instance'):
self.instance = super().__new__(self)
return self.instance
@staticmethod
def convert_column_list_to_numeric_value(column):
for ... |
8093f13800e2d07c830b118f23f5e6ea505987bc | ChinaBackGo/automate-boring-stuff | /commaCode.py | 345 | 3.53125 | 4 | #output: 'apples, bananas, tofu, and cats'
spam = ['apples', 'bananas', 'tofu', 'cats']
def comma_code(list_param):
comma_string = ''
for i in range(len(list_param)-1):
comma_string = comma_string + list_param[i] + ', '
comma_string = comma_string + 'and ' + list_param[-1]
return comma_string
... |
7f36d99c3de1d11f2b517b5c543965091ee5d2bc | ChinaBackGo/automate-boring-stuff | /fantasyGame_ch5.py | 753 | 3.703125 | 4 | import pprint
# Inventory:
# 12 arrow
# 42 gold coin
# 1 rope
# 6 torch
# 1 dagger
# Total number of items: 62
inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def printInventory(inventory):
print('Inventory: ')... |
783e421bca28879d22862320b7662c7dd659f9df | jeremy886/learn_p5 | /session_3/seek_with_limit.py | 1,160 | 3.546875 | 4 | from p5 import *
class Vehicle:
def __init__(self, start_x, start_y):
self.pos = Vector(start_x, start_y)
self.vel = Vector(0, 0)
self.acc = Vector(0, 0)
self.max_speed = 5
self.max_force = 0.5
def seek(self, target):
"""
Craig Reynolds:
steerin... |
9d68160bdbd775a5f0d9462b831ad7a0c5200674 | jeremy886/learn_p5 | /session_3/star.py | 1,433 | 3.640625 | 4 | # Star
#
# The star() function created for this example is capable of drawing a
# wide range of different forms. Try placing different numbers into
# the star() function calls within setup() to explore.
#
# https://github.com/p5py/p5-examples/blob/master/basics/form/star.py
from p5 import *
star_one = None
star_two =... |
a1675e46df676847b8576ef35a2ef5bf95061fab | Omisw/Python_100_days | /Day 3/leap_year.py | 950 | 4.53125 | 5 | # Day 3 - Third exercise.
# Leap Year
# Instructions
# Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February.
# The reason why we have leap years is really fascinating, this video does it more justice:
# This ... |
93dc5203b837b3ce41dd6df3051f1e8446113245 | Omisw/Python_100_days | /Day 10/Calculator/main.py | 1,438 | 4.1875 | 4 | # Day 10 - Final challenge.
from art import logo
# from replit import clear
def add(number_1, number_2):
return number_1 + number_2
def subtract(number_1, number_2):
return number_1 - number_2
def multiply(number_1, number_2):
return number_1 * number_2
def divide(number_1, number_2):
return number_1 / numbe... |
367e4dad412e35bb44db183fad52dc76641c7f8a | Omisw/Python_100_days | /Day 25/pandas/main.py | 1,460 | 3.84375 | 4 | # import csv
#
# with open("weather_data.csv") as data_file:
# data = csv.reader(data_file)
# weather = []
# temperatures = []
#
# for row in data:
# if row[1] != "temp":
# temperatures.append(int(row[1]))
#
# print(temperatures)
# import pandas
# data = pandas.read_csv("weathe... |
24c5920330ecb18cad06ee63444aa9432ad58dfc | Omisw/Python_100_days | /Day 9/dictionary_in_list.py | 1,258 | 4.5 | 4 | # Day 9 - Second exercise.
# Dictionary in List
# Instructions
# You are going to write a program that adds to a travel_log. You can see a travel_log which is a List that contains 2 Dictionaries.
# Write a function that will work with the following line of code on line 21 to add the entry for Russia to the travel_l... |
498e80a75aa31b4bad5652b9cebc4f0c11dfeb7a | Omisw/Python_100_days | /Day 9/grading_program.py | 1,517 | 4.65625 | 5 | # Day 9 - First exercise.
# Instructions
# You have access to a database of student_scores in the format of a dictionary. The keys in student_scores are the names of the students and the values are their exam scores.
# Write a program that converts their scores to grades. By the end of your program, you should have ... |
3749b95cdde1a8da66a859af80a16ad18dd5dab5 | Omisw/Python_100_days | /Day 3/treasure_island_game.py | 3,223 | 4.1875 | 4 | # Day 3 - Final challenge.
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
#https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Treasure%20Island%20Conditional.drawio#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oDe4ehjWZipYRsVfeAx2HyB7LCQ8_Fvi%26exp... |
106bd582708b66fbd49f96de8c7ee3a500bc8ac2 | eddieatkinson/Python101 | /digit_factorials.py | 378 | 4 | 4 | import math
def is_curious_number(n):
number_as_string = str(n)
sum_of_digits = 0
for digit in number_as_string:
sum_of_digits += math.factorial(int(digit))
if sum_of_digits == n:
return True
else:
return False
sum_of_curious_numbers = 0
for i in range(3, 100000):
if is_curious_number(i):
... |
6506edd060393f2a8d40ed4c4f2f1a3dcca76093 | eddieatkinson/Python101 | /loops_box.py | 196 | 4 | 4 | width = int(raw_input("Width? "))
height = int(raw_input("Height? "))
for i in range(1, height + 1):
if(i == 1 or i == height):
print "*" * width
else:
print "*" + " " * (width - 2) + "*"
|
62d5ab70daaf6ea89567f6e2e3903f481401dc29 | eddieatkinson/Python101 | /guess_num_high_low.py | 421 | 4.25 | 4 | # Guess the number! Gives clues as to whether the guess is too high or too low.
secret_number = 5
guess = 2
print "I'm thinking of a number between 1 and 10."
while secret_number != guess:
print "What's the number?"
guess = int(raw_input("> "))
if (guess > secret_number):
print "%d is too high. Try again!" % guess... |
c1319867968cf1d2bb0205318074482e47895473 | eddieatkinson/Python101 | /pythagorean_triplet.py | 312 | 4 | 4 | def three_numbers_that_sum_to_n(n):
for a in range(1, n + 1):
for b in range(1, n + 1):
if (a < b) & (a + b < n):
c = n - a - b
if ((a < c) & (b < c)):
if (a**2 + b**2 == c**2):
product = a*b*c
return product
print(three_numbers_that_sum_to_n(1000)) |
a918aa3b7cc8371cf85148ea96349d5b6ed4708c | eddieatkinson/Python101 | /string_reverse.py | 144 | 3.671875 | 4 | user_string = raw_input("Give me a string! ")
user_list = list(user_string)
user_list.reverse()
new_string = "".join(user_list)
print new_string |
5094ee261c96aa2a30730c2af79cf2337353fdef | eddieatkinson/Python101 | /name_scores.py | 789 | 3.609375 | 4 | import string
lower_case_alphabet = list(string.ascii_uppercase)
f = open('p022_names.txt', 'r')
names = f.read()
names_without_first_and_last = names[1:-1]
names_as_list = names_without_first_and_last.split('","')
names_as_list.sort()
number_of_names = len(names_as_list)
def get_name_score(i):
name_number_in_list =... |
434ed857c998b998f1e7e4922768e69d7f481ea8 | eddieatkinson/Python101 | /tip_calc.py | 383 | 3.921875 | 4 | amount = float(raw_input("What is the bill amount? "))
service = raw_input("How was your service (good, fair, or bad)? ")
if (service == "good"):
tip = .2 * amount
elif (service == "fair"):
tip = .15 * amount
else:
tip = .1 * amount
total = amount + tip
tip_rnd = round(tip, 2)
tot_rnd = round(total, 2)
print "Your t... |
ae3adae0d5240d72a31dd1b5067aebf3a777e969 | eddieatkinson/Python101 | /distinct_powers.py | 778 | 3.6875 | 4 | # Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
# 22=4, 23=8, 24=16, 25=32
# 32=9, 33=27, 34=81, 35=243
# 42=16, 43=64, 44=256, 45=1024
# 52=25, 53=125, 54=625, 55=3125
# If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
# ... |
d6d2f7a2dd422ab7a19b86adc468f49b088f98bb | lenileiro/politico-api | /app/api/v1/models/party.py | 2,185 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""Party model.
This module helps data manipulation.
PartyOffice class has multiple methods that manipulate,
the party data received from party views.
"""
# Mock data
DB = [
{
"id": 1,
"name": 'party A',
"hqAddress": 'box 432, Nairobi',
"logoUrl": 'https://v... |
936323e1098b2f7d1074c5124898e5127626a85c | fm1ck3y/BruteHashWithCrunch | /brute_hash.py | 1,269 | 3.5625 | 4 | from hashlib import md5, sha256, sha512
import sys
# chmod 777 brute_hash.py
# brute_hash.py type_hash hash.txt dict_word.txt
try:
type_hash , file_hash, dict = sys.argv[1],sys.argv[2],sys.argv[3]
except:
try:
type_hash, file_hash = sys.argv[1], sys.argv[2]
dict = sys.stdin.read()
except:
... |
7a5f261ac605c99fc267403a59ba043a555ff7ac | dinanad/LatihanGitHub | /daily task/tugasday6_dina.py | 2,010 | 4.0625 | 4 | # # Menu
# # 1) Show Produk
# # 2) Tambahkan Produk
# # 3) Update Harga
# # 4) Hapus Produk
nama = ['Jeruk', 'Kiwi', 'Apel']
harga = [1000,2000,3000]
### Function u/ menampilkan list produk
def show_produk():
daftar_produk=''
print('\nDaftar produk :')
for item in range (len(nama)):
daftar_pro... |
99caa620da89695673bbadcd673a31179a5e3073 | GuillermoBustosPerez/Portfolio | /SQL with Python and R/SQL with Python.py | 1,101 | 3.578125 | 4 | '''
A basic system for quering and storing data from SQL files into pandas dataframes
SQL data from
https://www.kaggle.com/harsha547/ipldatabase
'''
# Import basic needed packages
import pandas as pd
from sqlalchemy import create_engine
# Set up engine and get relational database table names
engine = create_engin... |
d9ffd7498abe93df1b25a284fbec730229b912ae | MOMOKO606/CLRS_Code_in_Python | /chapter_9.py | 9,694 | 4.25 | 4 | """
The median-selection algorithm is generally not used in practice, as he overhead of pivot computation is significant.
But this technique is of theoretical interest in relating selection and sorting algorithms.
-- https://www.geeksforgeeks.org/selection-algorithms/
"""
import random
import math
"""
Get the minimum ... |
5c02a7864f45d4950016c089349819c82c3168c2 | yang-qian/literature-clustering-and-analysis | /subset.py | 2,208 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
===========================================================
02 subset.py
subsets the pre-clustering dataset for individual analysis
- Qian Yang (qyang1@cs.cmu.edu)
===========================================================
"""
import pandas as pd
from analyze_cluster im... |
3b54c84a97e0b86da983103bbb166a513d21a125 | OlegMoiseev/exam-ml | /ridge_reg.py | 3,564 | 3.59375 | 4 | import csv
import matplotlib.pyplot as plt
import numpy as np
def csv_reader(file_obj):
reader = csv.reader(file_obj)
x1, x2, y = [], [], []
for row in reader:
x1.append(float(row[1]))
x2.append(float(row[2]))
y.append(float(row[4]))
return x1, x2, y
# Calculate the mean valu... |
e8cd83ac7a16c81a513beccc951e0e7675a195b7 | ankith-v/ML-class | /libraries/numpy/numpyIntro-210615-115430.py | 12,604 | 3.75 | 4 | ###########################################################################
# intro
# import numpy
# arr = numpy.array([1, 2, 3, 4, 5])
# print(arr)
###########################################################################
# #alias
# import numpy as np
# arr = np.array([1, 2, 3, 4, 5])
# print(arr)
##############... |
26344b08858ea1faa5618680dfc3ae4be29e5768 | ankith-v/ML-class | /vectors,matrices/operations-210625-173943.py | 5,443 | 4.46875 | 4 | ###################################################################################
# numpy matrix operations | empty() function
# numpy.matlib.empty() is another function for doing matrix operations in numpy.
# It returns a new matrix of given shape and type, without initializing entries.
# Syntax : numpy.matlib.emp... |
80a1dd6d5d717b59f0b395bd7da2dbc7eeb5a827 | ankith-v/ML-class | /libraries/matplotlib/matScatter-210625-173337.py | 5,621 | 4.25 | 4 | ########################################################################
# Creating Scatter Plots
# With Pyplot, you can use the scatter() function to draw a scatter plot.
# The scatter() function plots one dot for each observation.
# It needs two arrays of the same length, one for the values of the x-axis, and one f... |
4795d4fa1ef6e354154329b8aa16d1864b299cb0 | ankith-v/ML-class | /projects/mini2/hierarchical-210712-115550.py | 1,394 | 3.75 | 4 | # Step 1: Data pre-processing
# importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# importing dataset
dataset = pd.read_csv('projects\mini2\Mall_Customers-210707-122914.csv')
print(dataset.head())
# extracting the matrix feature
x = dataset.iloc[:, [3,4]].val... |
dc4eb333ae37addc848566c8dd07d5be10e464f5 | ankith-v/ML-class | /libraries/matplotlib/matPie-210625-173337.py | 4,305 | 4.1875 | 4 | ########################################################################
# Creating Pie Charts
# With Pyplot, you can use the pie() function to draw pie charts:
# import matplotlib
# matplotlib.use('TkAgg')
# import matplotlib.pyplot as plt
# import numpy as np
# y = np.array([35, 25, 25, 15])
# plt.pie(y)
# plt.show... |
0ac52dcaa2ebbec951be317029ffdd81ead25094 | ankith-v/ML-class | /libraries/scipy/scipyInterpolation-210625-172902.py | 3,924 | 4.5 | 4 | ##############################################################
# SciPy Interpolation
# Interpolation is a method for generating points between given points.
# Interpolation is defined as finding a value between two points on a line or a curve.
# The first part of the word is "inter" as meaning "enter", which indicat... |
f33a414096049b7c82900ac2b8fcc92a9994c3f9 | jayasri22/python | /natural.py | 105 | 3.875 | 4 | a=int(input("Enter no: "))
m1 = 0
while(a > 0):
m1=m1+a
a=a-1
print("sum of 1st natural no ",m1)
|
dc1c2fbf6f654cef0f16c58a6a0c2d1d39a22b6d | soumya2309-A/Plasma-Donation | /DonorPlasmaFunctions.py | 6,461 | 3.578125 | 4 | import sqlite3
con=sqlite3.connect('PlasmaDb')
curs=con.cursor()
def InsertDonorPlasmaDetails(donor_id):
#curs.execute(' drop table DonorPlasmaTb ')
curs.execute('''create table if not exists DonorPlasmaTb(donorId int primary key,bloodGroup text,weight float,covidPositive text,
covidDate text,plas... |
7b43a979f92cea189aff7190c9ab5cd12030cb98 | zaunaro/pysketchfix | /Evaluation/evaluationtestrunner.py | 1,977 | 3.515625 | 4 | import sys
import unittest
def run(test_directory, test_basename, result_file):
"""
This file is executed in a new python environment. This is done because the test loader execution can be not done
in one environment. If you execute the code to run a unit test in the same environment again and again. So a... |
1fb3875553dd99fb89943a9c954029f1d0213877 | saddamarbaa/object-oriented-programming-concepts | /Intro OOP1.py | 1,187 | 4.4375 | 4 | # Object Oriented Programming
# Class and Object in Python
# Robot class
class Robot:
# instance attribute
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
# instance method
def introduce_self(self):
print(... |
01b221ec4a1606b8e7f80c5b6d7fd96ab0d32bd1 | gomathibalasubramaniam/imfy-pfday2 | /coin.py | 667 | 3.859375 | 4 | def make_amount(rupees_to_make,no_of_five,no_of_one):
five_needed=0
one_needed=0
a=(no_of_five*5)+(no_of_one*1)
if(a<rupees_to_make):
print(-1)
else:
b=rupees_to_make//5
c=rupees_to_make%5
if(b>no_of_five):
five_needed=b
c=rupees_to_make-(b*5)
... |
493852e995f1e4bf7f14d2c85ce8b2646631acf8 | ghigbie/python-practice-basic | /animal.py | 208 | 4.03125 | 4 | animal = input("Please enter your favorite animal.")
if animal:
print(f"{animal} is my favorite too!")
else:
print("You didn't say anything!!!")
animal = input("Please enter your favorite animal") |
ef78417e61ba37db38043f0d874f4eec0eb4b006 | yeahajeong/algorithm-solution | /programers/다리를 지나는 트럭/다리를지나는트럭(다른사람풀이).py | 1,547 | 3.8125 | 4 | from collections import deque
DUMMY_TRUCK = 0
class Bridge(object):
# 생성자
def __init__(self, length, weight):
self._max_length = length
self._max_weight = weight
self._queue = deque()
self._current_weight = 0
def push(self, truck):
next_weight = self._current_we... |
0d20083276a2d4102cf64ced4b5350242101d805 | 200262/QuizGameI2PSummative | /Quiz Game 1.py | 4,865 | 4.40625 | 4 | name = input("What is your name?")
name = name.upper()
#takes name and makes it uppercase
print ("Hello", name, ", this is my quiz game. It is very simple. ""With every question there will be four possible answers, A through D. Just type "
"the letter of your answer. At the end you’ll get your sco... |
b2afccc1a525b01d0e04c4d5b77a11bc7bbe2d5a | Sukhrobjon/exercism | /python/armstrong-numbers/armstrong_numbers.py | 188 | 3.625 | 4 | def is_armstrong_number(number):
"""
armstrong number is a number that is the sum of its own digits each
raised to the power of the number of digits.
"""
pass
|
090e8ba50ae508009101afe7da667f2be29ff7c7 | ejspeiro/HackerRank | /all_domains/python/strings/find_a_string.py | 522 | 4.0625 | 4 | # -*- coding: utf8 -*-
def count_substring(string, sub_string):
stringLength = len(string)
subStringLength = len(sub_string)
countSubStr = 0
for ii in range(0, stringLength):
aux = string[ii] == sub_string[0]
if aux and string[ii:ii + subStringLength] == sub_string:
countSu... |
cf409be2a09a8d99ac6d8b665cf204ec97b86139 | ejspeiro/HackerRank | /all_domains/tutorials/10_days_of_statistics/day_1-standard_deviation.py | 489 | 3.84375 | 4 | # -*- coding: utf8 -*-
import math
def mean(numSamples, samples):
return sum(samples)/numSamples
def standardDeviation(numSamples, samples):
samplesMean = mean(numSamples, samples)
numerator = sum([(xx - samplesMean)*(xx - samplesMean) for xx in samples])
return math.sqrt(numerator/numSamples)
if... |
9a15607d3e35bf3b8153b236dc1c634e15577a41 | JrHaroldd/Simple-Genetic-Algorithm- | /main.py | 4,674 | 3.53125 | 4 | import random
#this functin creates the individual chromosomes that populate the generation
def createIndividualChromosome(chromosomeLength): #generates chromosome
chromosome = ""
chromosomeFitness = 0
for i in range(chromosomeLength):
code = random.randint(0,1)
chromosomeFitness += code
... |
f9347f761c0dabc945517b8a96e8828d549a423a | IIT-BHU-CyberSec/CSOC-CTF-1 | /Web/teeka/source/CreateusersDB.py | 390 | 3.625 | 4 | import sqlite3
con=sqlite3.connect('usersDB.db')
print("Connected to database")
con.execute("create table users(id INTEGER PRIMARY KEY AUTOINCREMENT, usrname TEXT NOT NULL,password TEXT NOT NULL)")
print("Table created successfully")
# cur = con.cursor()
con.execute("insert into users(usrname,password) values('J... |
b99dbf6bb0ee7916267dc4b96c13d660d05306e0 | DavidWallacedot/recursiveFunctions.py | /recursive.py | 2,649 | 3.953125 | 4 | #David Wallace
#5-22-2018
# This is a program that contains several recursive functions
import random,sys
def sumOfNumbers(inputNum):
num = int(inputNum)
if(num != 0):
num = num + sumOfNumbers(num-1);
return num
def isMember(array,value,size):
if(size != 0):
if(value==array[size]):
return True
else:... |
795b55f251675a55d5d470858f4d059fa76bb6bf | srajeevteaching/prog-assignment1-sarikarajeev33 | /prog1.py | 140 | 4.03125 | 4 | # ask user to input
# calulate area of walls
w=int(input("Enter width"))
h=int(input("enter heght"))
area=w*h
print("area of wall is:",area) |
97c7fb60a2b8dfe5149d60c8729a128bffaf5718 | shreyashmehta12/Analysis-of-stock-market | /final.py | 8,191 | 3.5 | 4 | # Importing required libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
import datetime as dt1
from datetime import datetime as dt
import quandl
import datetime
imp... |
60c1fa15882afad8bb5fa297a27226340d68e7f6 | scottkirkwood/scott-bin | /dupfiledeleter.py | 576 | 3.90625 | 4 | #!/usr/bin/python
"""Have no idea what this does!
"""
import re
def ReadFile(fname):
lines = []
re_hex = re.compile(r'([0-9a-f]{32})')
re_key = re.compile(r'([a-z0-9]+):')
for line in open(fname):
line = line.strip()
line = re_hex.sub(r"'\1'", line)
line = re_key.sub(r"'\1':", l... |
d6005f7fe9289c3a42eea69c4fc88c09b8070fac | HungryLim/pythoncourse2018 | /day09/class09_players.py | 9,558 | 3.65625 | 4 | # install sqlite from sqlite.org
# pip install sqlalchemy
# pip install pysqlite
# Check: http://pythoncentral.io/introductory-tutorial-python-sqlalchemy/
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, and_, or_
from sqlalchemy.orm ... |
d521a5fec72d11847c9be53e754ec4bc65482696 | HungryLim/pythoncourse2018 | /day01/lab01_erin.py | 3,413 | 4.5 | 4 | ## Trick and explanation
## http://www.purplemath.com/modules/base_why.htm
"""convert positive integer to base 2"""
def binarify(num):
if num <= 0:
return "Error" ## we will learn error handling later in course
digits = []
while num > 0:
digits.append(num % 2)
num = num / 2
#assigns digits the sequence ... |
3e63f37f28eaee851effba096e3300825443a981 | mselser95/Machine-Learning | /mlfin/plotting.py | 1,773 | 3.5 | 4 | """
Utilidades para visualización de resultados.
"""
import numpy as np
import matplotlib.pyplot as plt
import sklearn.metrics as sk_mt
def plot_roc_curve(model, X_test, y_true):
"""
Grafica curva ROC para un modelo de clasificación binaria dado.
Parámetros
model : Modelo ya fi... |
2d76e10a7bfb1244a094bd0a70b04a61568a0959 | andysitu/algo-problems | /leetcode/400/312_burst_balloons.py | 1,245 | 3.578125 | 4 | """
the most difficult problem I've encountered so far
dp used doesn't make intuitive sense.
it's observed from how coins are calculated
eg [3,1,5,8] -> coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
3*1*5 - no dp, uses nums calculation,
3*5*8 - length 2 - will use dp from previous & uses nums calc size 2 (thus 3*1*5 +... |
177efeb6db001acbe74d8c89231f686729248380 | andysitu/algo-problems | /leetcode/100/5_longest_palin.py | 705 | 3.53125 | 4 | def longestPalindrome(s):
start_points = {}
ls = len(s)
for i in range(ls):
if (i+1 < ls and s[i] == s[i+1]):
start_points[str(i) + "_2"] = [i,i+1]
if (i+2 < ls and s[i] == s[i+2]):
start_points[str(i) + "_3"] = [i,i+2]
max_length = -1
max_sa = 0
max_sb =... |
99ff04e0e61db5edf4f1c43b044c8bc26a29bc04 | andysitu/algo-problems | /leetcode/300/210_course_schedule_slow.py | 1,922 | 3.5 | 4 | import queue
class Solution:
def travel(self, dependencies, cycle_status, value):
if cycle_status[value] >= 1:
return True
if cycle_status[value] == -1:
return False
for d in dependencies[value]:
cycle_status[value] = -1
r = self.travel(depend... |
17d14e9af3a4cc71a379ed55173c63ef727daee4 | andysitu/algo-problems | /leetcode/400/337_house_robber_3_almostworking.py | 1,702 | 3.546875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def get_max(self, node):
v = node.val
vl = 0
under_vl=0
if node.lef... |
fc386454e8e25617fd6611966cef12e3c0f2800c | andysitu/algo-problems | /leetcode/200/151_reverse_string.py | 605 | 3.53125 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
start_index = None
new_s = ""
for i in range(len(s)):
if start_index == None:
if s[i] != ' ':
start_index = i
else:
if s[i] == ' ' and start_index != None:
... |
41c994ac7de5e5699e15889a9397b77e1a12c9e8 | andysitu/algo-problems | /problems_analysis/container_with_most_water.py | 690 | 3.53125 | 4 | """
Brute Force
Try every single combination at each i
Runtime : O(n^2); Space O(1)
"""
"""
In Brute Force, you can see that you don't need to look
at numbers with a lower height than i. This is related to
the iterated /moving number.
In the non-moving number, i, which is moved from one number
to another in the outer... |
6160b49813d17b2347f01445da1a7a0f55678aa0 | andysitu/algo-problems | /leetcode/100/98_validate_bst_iter.py | 808 | 3.84375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if root is None:
return True
n1 = No... |
20517fc968a3080bb68923805f779c14751f8796 | andysitu/algo-problems | /leetcode/100/37_sudoku_solver1.py | 4,194 | 3.578125 | 4 | class Solution:
solved = -1
def build_table(self, board):
self.solved = 0
for row in range(9):
for col in range(9):
if board[row][col] == ".":
board[row][col] = {
"length": 9,
"nums": [1] * 9
... |
15bb0f64ebe412bd9221132fe00dad93dd0b226f | andysitu/algo-problems | /problems_analysis/best_time_stocks_sell.py | 1,251 | 4.03125 | 4 | """
Brute Force approach:
Iterate through all of them with two for loops to test
out all combinations
Runtime: O(n^2), Space: O(1)
"""
def maxProfit(self, prices):
maxprofit = 0
for i in range(len(prices)-1):
for j in range(i, len(prices)-1):
maxprofit = max( prices[j] - prices[i], maxprofit... |
c7100cb29ef4c40ad5a191005e3633462d74620f | andysitu/algo-problems | /leetcode/200/108_convert_sorted_array_to_bst.py | 1,002 | 3.96875 | 4 | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def create_node(self, nums, start, end):
if end == start:
# print(nums[s... |
2c78c9a14cf3fca0931a93aa881037aba2dfe4d7 | andysitu/algo-problems | /leetcode/300/212_word_search_slow.py | 2,519 | 3.84375 | 4 | from typing import List
from data_for_212 import a1, a2
# Can use a dictionary to search all the words at once through the board
# Dictionary will contain a structure similar to the prefix/ trie word problems
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
found... |
471e3756de82e5b081af96e075beddaac6e9f047 | andysitu/algo-problems | /leetcode/400/310_min_height_trees_slow.py | 2,570 | 3.640625 | 4 | from typing import List
import queue
import data310
class Solution:
def travel(self, root, n):
travelset = set()
travelset.add(root)
q = queue.Queue()
q.put((n, 1, [root, n]))
maxheight = 0
paths = None
while not q.empty():
ntup = q.get(... |
94823982075c1d05239c9c422d5dc999b8b25065 | andysitu/algo-problems | /leetcode/400/328_odd_even_linked_list.py | 786 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return head
odd_status = True
n = head
... |
49d01a816c4b0ee5ff035ac842e695af1869453d | andysitu/algo-problems | /problems_analysis/shufft_array.py | 569 | 3.5625 | 4 | """
I need a way to shuffle the indices in the array using
in a way ideally with cosntant space. With space,
what would this look like? You would need a data
structure that you could randomize but also but able
to pop or shorten at the same time.
The way that I thought of was that instead you could
just simply randomi... |
cfe80277af817b30140517ced9bdb85d4ad5d8d6 | andysitu/algo-problems | /leetcode/400/327_count_range_sum.py | 1,225 | 3.6875 | 4 | from typing import List;
class Solution:
def mergesort(self, nums, lower, upper):
nlen = len(nums)
mid = nlen // 2
if mid > 0:
left, right = self.mergesort(nums[:mid],lower,upper), self.mergesort(nums[mid:],lower,upper)
rlen = len(right)
i=j=... |
0e5c1e1c5d28a037e43064d4a800d0ed0dd99cfd | andysitu/algo-problems | /leetcode/441_arranging_coins_wrong.py | 283 | 3.890625 | 4 | """
Doesn't work because the area of a triangle
accounts for the small edges. In other words,
it's not discrete in the values/ height such that
this problem would require.
"""
import math
class Solution:
def arrangeCoins(self, n: int) -> int:
return int(math.sqrt(n*2)) |
fd64ff7aee29f703a39895d2aed6a052ed60dbf9 | andysitu/algo-problems | /leetcode/23_merged_sort_list_lt_in_listnode.py | 796 | 3.90625 | 4 | import queue
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return
ListNode.__lt__ = lambda x, ... |
d21eb25e58a63c4a1183d66969e152e27375d99f | andysitu/algo-problems | /leetcode/200/126_word_ladder_2c.py | 2,321 | 3.625 | 4 | from typing import List
import queue
class Solution:
routes = None
def print_dict(self, dict):
for k in dict:
print(k, dict[k])
def find_num_diff(self, s1, s2, max_diff):
num_diff = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
num_diff += 1
... |
512e991ec6f0c3d28b2e9cc45be42d360c6f53b0 | andysitu/algo-problems | /leetcode/200/126_word_ladder_2b.py | 4,093 | 3.5 | 4 | from typing import List
import queue
class Solution:
def print_dict(self, dict):
for k in dict:
print(k, dict[k])
def find_num_diff(self, s1, s2, max_diff):
num_diff = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
num_diff += 1
if ... |
eed8f6f34dfd7748e2ced2b17cefeca153fa56a7 | andysitu/algo-problems | /leetcode/200/189_rotate_array.py | 643 | 3.84375 | 4 | from typing import List
class Solution:
def reverse(self, nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify ... |
92d3eeecb0efceb24b34a7f87488d3296c7d99de | lelongrvp/Special_Subject_01 | /homeword_2/problem3.py | 1,856 | 4.53125 | 5 | # Obtain phone number from user and split it into 3 parts
phone_number = input('Enter a phone number using the format XXX-XXX-XXXX: ')
split_number = phone_number.split('-')
#initializing some control variables
weird_character = False # True will stop while loop and display an error
count = 0 # Keeps tra... |
e10dc790fa17cd74f2a5d0600e2fdb655f4c0aeb | lelongrvp/Special_Subject_01 | /Homework_1/Problem 4.py | 159 | 3.765625 | 4 | total_sales = float(input("Enter the expected total sales: $"))
profit = total_sales * 0.23
print("The expected profit is $", format(profit, ',.2f'), sep='') |
5654b68f9f86a9382bf06b7a540db62cb1fdb89b | IgaoGuru/TicTacToe- | /binary_search.py | 2,012 | 3.6875 | 4 | import time
import matplotlib.pyplot as plt
import numpy as np
#looping one
def find_element(elements:list, element:int):
for i in elements:
if element == i:
return True
return False
#recursive one
def find_element2(elements:list, element:int):
if len(elements) == 0:
return Fal... |
3a309edd16323ea50d5fd47fd1deadf61ec63362 | kkrawczykpl/downloads-sort | /sort.py | 1,858 | 3.578125 | 4 | import os
def main():
folder_to_sort = input("Sort files in folder (path): ")
change_location = input("Change files location? (True or False): ")
if change_location == "True":
folder_destination = input("Location (path): ")
else:
folder_destination = folder_to_sort
sort(folder_to... |
f167bd60226a3af05e2fe47edbdbc4536cdab6ee | firefly-cpp/NiaARM | /niaarm/feature.py | 1,305 | 3.53125 | 4 | class Feature:
r"""Class representing a feature.
Args:
name (str): Name of the feature.
dtype (str): Datatype of the feature.
min_val (Optional[float]): Minimum value of the feature in the transaction database.
max_val (Optional[float]): Maximum value of the feature in the transacti... |
d6c5a21cffa5ee525f8f47cd3f0b4fc607cb7087 | koolhussain/Test-Code | /screenshot.py | 823 | 3.703125 | 4 | #This works like a screen shot of the whole screen
#numpy to convert data to numpy array as cv2 supports images as numpy array
import numpy as np
#cv2 to display the Images
import cv2
#To Grab screen
from PIL import ImageGrab
#Screen captured and stored in screen varaible its not numpy array type
s... |
92b6bcce2771904efe737902d72e5dd30d82375a | ChenshuXu/Foundations-of-Artificial-Intelligence | /little go game/myplayer_play/QLearner/s2_submit/cnt33/my_player3.py | 8,356 | 3.75 | 4 | import GameBoard as GameBoard
# Black=1, White=2
class MinmaxPlayer:
def __init__(self, depth=2, debug=False):
self.type = 'minmax'
self.piece_type = None
self.depth = depth
self.previous_board = None
self.board = None
self.debug = debug
# self.branching_fac... |
58ff2ceec5cb5abc06bb8c962b9f921effd8f233 | spyros-1206/curso_python | /dividiendo.py | 505 | 3.765625 | 4 | # -*- coding: utf-8 -*-
class Modelo:
divisor = 23
def devolver_resultado(self, numero):
""" Divide el número por el diviso y devuelve un entero """
resultado = numero//self.divisor
return resultado
def __init__(self):
valor = raw_input("Elige un número entero entre 0... |
44746aec5d7405051b68ec4f1ead570f57e57ce0 | tnovak123/hello-spring | /crypto/caesar.py | 567 | 4.1875 | 4 | from helpers import rotate_character, alphabet_position
def encrypt(text, rot):
newtext = ""
for char in text:
if char.isalpha() == True:
newtext += rotate_character(char, rot)
else:
newtext += char
return(newtext)
def main():
inputtext = ""
displace = 0
inputtext... |
baccc4338e37de72d5449464505c3092edae747c | Moonzie/boring_stuff_python | /collatz_sequence.py | 352 | 4 | 4 | def collatz(number):
if number % 2 == 0:
sequence = number // 2
return(sequence)
elif number % 2 == 1:
sequence = 3 * number + 1
return(sequence)
else:
print ("errrrrrorrrrr")
def main():
number_in = input('enter a number: ')
while True:
number_in = collatz(int(number_in))
print(number_in)
if ... |
639c1652e9b3de66cf802474cd1ad586f14758c5 | ParvathiVenugopal/pythonprogram | /small3.py | 240 | 4 | 4 | a = int(input("enter first number"))
b = int(input("enter second number"))
c = int(input("enter third number"))
if(a<b):
if(a<c):
print(a)
else:
print(c)
else:
if(b<c):
print(b)
else:
print(c) |
c78989cadf088fff059eb83a74d4743a9048a021 | JesusUrtasun/MachineLearningRep | /TF2_TextClassification.py | 6,137 | 4.15625 | 4 | # TensorFlow Chapter 2. Text Classification
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
# Check the version of TensorFlow
print("TensorFlow version: {}".format(tf.__version__))
print("TensorFlow Chapter 2: Text Classification")
# Binary classification. Class... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.