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 |
|---|---|---|---|---|---|---|
3f9a9ae7cec11d0d24860f33db755a812348123b | SuryakantKumar/decorator-drills | /Fibonacci-Cache.py | 1,159 | 4.0625 | 4 | """Import 'functools' module of python"""
import functools
def count_calls(func):
"""Decorator for counting for function call"""
@functools.wraps(func)
def wrapper_count_calls(*args, **kwargs):
"""wrapper function for counting function call"""
wrapper_count_calls.num_calls += 1
p... |
2adcb54acae88f33bccb5107e31d2655d396651d | toatts/project-euler | /P25.py | 1,173 | 4 | 4 | # ==============================================================================
print ("Project Euler - Problem 25\n\n")
# ==============================================================================
# Description:
# The Fibonacci sequence is defined by the recurrence relation:
# Fn = Fn-1 + Fn-2, where F1 = 1 and F... |
c645466e60b26bcfd5437626bc241bbaf272ad11 | toatts/project-euler | /P12.py | 1,972 | 3.734375 | 4 | # ==============================================================================
print ("Project Euler - Problem 12\n\n")
# ==============================================================================
# Description:
# The sequence of triangle numbers is generated by adding the natural numbers.
# So the 7th triangle ... |
d5eac064a8bf2a2c702a1c7c2572aed428223307 | toatts/project-euler | /P30.py | 1,936 | 3.515625 | 4 | # ==============================================================================
print ("=============================")
print ("Project Euler - Problem 30")
print ("=============================")
# ==============================================================================
# Description:
# Surprisingly there are o... |
403553e00382b19458f13ee88e129be42e59668d | spalagat/intelligentSystemsProject2 | /random_restart.py | 5,998 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 01:02:08 2019
@author: sunny
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 18:42:17 2019
@author: sunny
"""
import numpy as np
import random as rand
import copy
from queue import PriorityQueue
from operator import itemgetter
"""This is a ... |
421ec9afc21ffd74c3d1987ed38c08a801e43b14 | dionyziz/advent-of-code | /2021/8/8b.py | 823 | 3.53125 | 4 | from itertools import permutations
with open('small.txt') as f:
lines = f.read().splitlines()
alphabet = 'abcdefg'
led_patterns = [
'abcefg', 'cf', 'acdeg', 'acdfg', 'bcdf',
'abdfg', 'abdefg', 'acf', 'abcdefg', 'abcdfg'
]
inv_patterns = {v: k for k, v in enumerate(led_patterns)}
def translator(src, dst):
map... |
2d322f074b9c600b9060cdc7c8cec91892838339 | dionyziz/advent-of-code | /2022/3/3.py | 343 | 3.625 | 4 | with open('in.txt') as f:
lines = f.read().strip().split('\n')
total = 0
for line in lines:
left, right = line[:len(line)//2], line[len(line)//2:]
common = ord((set(left) & set(right)).pop())
if ord('a') <= common <= ord('z'):
score = common - ord('a') + 1
else:
score = common - ord('A') + 27
total... |
3126e53f12a7953a10d2d7e68b190511b222bb3d | joydip29/test1 | /StudentTest.py | 1,262 | 3.9375 | 4 |
import unittest
# This is the class we want to test. So, we need to import it
import Student as StudentClass
class Test(unittest.TestCase):
student = StudentClass.Student()
student_roll = []
student_name = []
def test_0_insert_name(self):
print("Start insert_name test\n")
for i in range(4):
name = 'name... |
cccfeeb16d38db6e1c3e2172f40d65dcdafb311a | Gera2019/gu_python_algorythm | /lesson_7/task_2.py | 1,593 | 4 | 4 | '''
2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами
на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
'''
import random
def merge_sort(arr, start, end):
''' Сортировка вещественного массива методом слияния '''
if end - start... |
b4b85b99c1b454fea81f33d2cd53e1eb07cf1b8f | Gera2019/gu_python_algorythm | /lesson_2/task_6.py | 1,436 | 4.03125 | 4 | '''
В программе генерируется случайное целое число от 0 до 100.
Пользователь должен его отгадать не более чем за 10 попыток.
После каждой неудачной попытки должно сообщаться больше или меньше введенное пользователем число, чем то, что загадано.
Если за 10 попыток число не отгадано, то вывести загаданное число.
'''
imp... |
3e291520337ebab9ece5dd5d3f468b35358b9a7d | karlaevellyn/Git-kei | /cartas.py | 614 | 4.09375 | 4 | print ("Olá, esse programa serve para te informar qual o número da quarta e última carta do mini-game. Lembrando que esses números estão entre 0 e 100, e que as quatro cartas formam dois pares de cartas iguais.")
a= int ( input ("Digite o número inteiro da primeira carta:"))
b= int ( input ("Digite o número inteiro da... |
fe6ca51feff4dcc4635e8dae15b6dfb68fad1c36 | NauvalHernandoko/Nauval-Hernandoko_I0320075_Muhammad-Wildan-Rusydani_Tugas-3 | /I0320075_Exercise3.1.py | 167 | 3.8125 | 4 | #Cara mengakses nilai di dalam list python
list1 = ['fisika','kimia', 1999, 2009]
list2 = [1,2,3,4,5,6,7]
print("list1[2]:",list1[2])
print("list2[2:4]:",list2[2:4])
|
a4795fe0e0d16d9ce24777910838d9a4882bf107 | 2BSJ/python_practice01 | /prob02.py | 407 | 3.9375 | 4 | #문제2. 키보드로 정수 수치를 입력 받아 짝수인지 홀수 인지 판별하는 코드를 작성하세요
number = input('수를 입력하세요 : ')
def isNumber(number):
try:
int(number)
return True
except ValueError:
return False
if isNumber(number) == False :
print('정수가 아닙니다')
elif int(number) % 2 == 0 :
print('짝수')
else :
print('홀수') |
7c4cd1d809fd23942247f5e8da7a179fcd81e33c | avasilistov/Codewars | /Unique In Order.py | 193 | 3.5 | 4 | from itertools import groupby
def unique_in_order(iterable):
return [k for k, g in groupby(iterable)]
# test.assert_equals(unique_in_order('AAAABBBCCDAABBB'), ['A','B','C','D','A','B'])
|
8db0c570f68b1ce26773385ecbd8900e3a7057c1 | shawl6201/CTI110 | /P2T1_SalesPrediction_LeslieShaw.py | 392 | 3.84375 | 4 | #Determine the projected profit amount based on total sales
#September 12, 2018
#CTI-110P2T1-Sales Prediction
#Leslie Shaw
#Get the projected total sales
total_sales = float(input('Enter the projected sales: '))
#Calculate the profit as 23 percent of total sales
profit = total_sales * 0.23
#Display the pr... |
ffc6e2fda607020f9c8f320cb42a607e79d7f44b | shawl6201/CTI110 | /P3T1_AreasOfRectangles_LeslieShaw.py | 748 | 4.5 | 4 | #CTI-110
#P3T1- Areas of Rectangles
#Leslie Shaw
#October 6, 2018
#This program is to determine which rectangle has the greater area
#Get the length and width of rectangle 1
length1=int(input('Enter the length of rectangle 1:'))
width1=int(input('Enter the width of rectangle 1:'))
#Get the length and widt... |
30e2d03c51d3bddbce4f97e29952f3b24f7bee69 | nmukerje/esutil | /esutil/sqlite_util.py | 30,316 | 3.671875 | 4 | from __future__ import print_function
_instantiate_docs="""
Class:
SqliteConnection
Purpose:
Inherits from the sqlite3.Connection class and adds
new functionality.
Useful Methods:
See each method's documentation for more details.
execute:
Exec... |
2bbf0a300d80782e456d65be8a5289f9cda4b286 | jameljammel/tp | /Ex3.py | 389 | 4 | 4 | import math
a = int(input("donné a:"))
b = int(input("donné b:"))
c = int(input("donné c:"))
def denifi_triangle(a,b,c):
d: int = (a+b+c)/2
print(d)
if a >= d and b >= d and c >= d :
r: bool = "true"
print(r)
elif a < d and b > d and c > d :
r: bool = "false"
print(r)
... |
42b406eed5f926b9af97648d00c37ed350d15d53 | RivenTheExile1/IrisSeniorProject | /Motor/Old_servo_motor_test_v1.py | 960 | 3.75 | 4 | #pip3 install keyboard type this in before you run
#connect the red wire to pin 1, Black to pin 6, and white to pin 11 (GPIO170
#THIS CODE IS NOT TESTED. MY PI BROKE IN THE TRANSPORTATION TO SAN ANTONIO.
#Purpose:
# 1) To set up the pi so that when we press the 'd' key the servo will turn 90 degrees
# 1.1) It ... |
f96776571a6d799eecf6ad05920d35aef2574856 | fchikwekwe/CS-1-2-tutorials | /fisher_yates.py | 444 | 4.0625 | 4 | import random
def fisher_yates_shuffle(list):
# if there are items to shuffle
for index in range(len(list)):
# pick a random index
random_index = random.randint(0, len(list)-1)
# swap it with the current element
list[index], list[random_index] = list[random_index], list[index]
... |
cc909d85ba280a5dc383da83f73abdec347a00aa | 77kHlbG/Python | /CeaserCypher.py | 1,123 | 4.21875 | 4 | #!/usr/bin/python -tt
import sys
# Define a main() function
def main():
rotation=1
# Get cyphertext from user
cyphertext = input('Enter cyphertext: ')
plaintext = cyphertext
cyphertext = cyphertext.upper()
print('\n')
print('Performing Rotation Cypher...')
# Repeats for all 25 possible rota... |
c420c26aa1f06d63d1b067005dfdde516b5d455a | AbhinavGupta90/PythonIntro | /abstract_class.py | 989 | 3.875 | 4 | from abc import ABC, abstractmethod
class AbstractRecipe(ABC):
def execute_recipe(self):
self.get_ready()
self.prepare_the_dish()
self.wash_up()
@abstractmethod
def get_ready(self):
pass
@abstractmethod
def prepare_the_dish(self):
pass
@abstractmetho... |
50baca3f7f9eda4b8a600dc0d7ee3c0b53233a83 | AbhinavGupta90/PythonIntro | /program.py | 1,199 | 4.09375 | 4 | name = "Blazej"
surname = "Wielk"
print("Test print")
print(name + " " + surname)
def print_personal_details(name, surname, yob):
print("NAME: " + name
+ "\nSURNAME: " + surname
+ "\nYEAR OF BIRTH: " + yob)
print_personal_details(name, surname, "1992")
def print_personal_details_multiple_time... |
dd8d1be02bcaa65703c3f3b8c812b50485cb2215 | elimgoodman/Ply-Test | /lang/exprs.py | 3,347 | 3.546875 | 4 | class Expr(object):
def evaluate(self, scope):
raise NotImplementedError("Unevaluable! in %s" % (self.__class__.__name__))
class StatementList(Expr):
def __init__(self):
self.statements = []
def append(self, stmt):
self.statements.append(stmt)
def evaluate(self, scope):
... |
b29ec8da2330fc45a346ab67bc48220a161754ab | anssssss/Vietnamese-Speech-Recognition | /src/processing_text.py | 1,191 | 3.640625 | 4 | # encodes text data
# Vietnamese characters
chars = 'AĂÂBCDĐEÊGHIKLMNOÔƠPQRSTUƯVXYÁÀẢÃẠĂẮẰẲẴẶÂẤẦẨẪẬĐÉÈẺẼẸÊẾỀỂỄỆÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴ '
# encodes characters to numbers
def encode(text):
encoded = []
for char in text:
encoded.append(chars.find(char))
return encoded
# decodes number... |
0f05e0f4891bf5964df0b986d46e195c8571825f | BrianHarringtonUTSC/CMS-URG | /VideoStyleDifferences/Lecture_4/functions.py | 1,332 | 4.34375 | 4 | ''' You are building a login system for your new app.
In order to protect the users, you require their password to have
certain propoerties, they are listed below:
1. Must be at least 8 characters long
2. Must have at least 1 uppercase letter
3. Must have at least 1 lowercase letter
4. Must have at lea... |
e0de498a31b3ee88acf6469123fcc0029991054c | Pablu23/WhatsTheTime | /main.py | 5,805 | 3.609375 | 4 | import time
from datetime import datetime, timezone
import keyboard
import requests
import tweepy
# Keys is a simple py file with just a Dictionary in it.
from keys import keys
'''
The structure of the dictionary is like this:
keys = dict(
access_token='XXXXXXXXXXXXXXXXXXXX',
access_secret='XXXXXXXXXXXXXXXXX... |
1ef7b2986a9278d0ff6710b52685464ecb4204c8 | AlecLjpg/PythonSetlist1 | /Setlist1/Q9.py | 143 | 3.765625 | 4 | x = 5 + 7j
y = 12 + 3j
print("Addition = ", x+y)
print("Subtraction = ", x-y)
print("Multiplication = ", x*y)
print("Division = ",x/y)
|
106f5cbaec53f77e657bc0be6610624dd0492643 | AlecLjpg/PythonSetlist1 | /Setlist1/Q12.py | 476 | 4 | 4 | low = []
av = []
high = []
x = [int(y) for y in input("Enter 10 numbers to be processed: ").split()]
avg = (sum(x)/len(x))
print("The average of all numbers entered is: " + str(avg))
for y in x:
if y > avg: high.append(y)
elif y == avg: av.append(y)
elif y < avg: low.append(y)
print(str(... |
d87bbaee67a9409d7b000a88e920ed87743f676c | koenongena/codewars | /python/Sudoku Solution Validator.py | 992 | 3.609375 | 4 | def valid(arr):
return sorted(arr) == list(range(1, 10))
def extract_grids(rows):
return [[rows[row + i][col + j] for i in range(3) for j in range(3)] for row in (0, 3, 6) for col in (0, 3, 6)]
def valid_solution(board):
rows = [row for row in board]
columns = [list((row[col] for row in rows)) for c... |
85d99bafb7015da0267e1205eadebe5c50739510 | koenongena/codewars | /python/Sort the odd.py | 211 | 4.09375 | 4 | def sort_array(arr):
odd = sorted([x for x in arr if x % 2 == 1], reverse=True)
return [x if x % 2 == 0 else odd.pop() for x in arr]
if __name__ == '__main__':
print(sort_array([5, 3, 2, 8, 1, 4]))
|
c0e744053358c09250092c2073667e14991b9b5d | kevindjf66/Little-Programming-in-Free-Time | /Prac4.py | 195 | 4.1875 | 4 | '''
enter three numbers and print out the three numbers from smallest to biggest
'''
l = []
for i in range(0, 3):
x = int(raw_input('enter an integer:\n'))
l.append(x)
l.sort()
print l
|
a81fc2dd8f67097c6d8b3e4ac6c35e2961665bac | lichader/leetcode-challenge | /problems/median_of_two_sorted_arrays.py | 1,832 | 4.125 | 4 | """
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nu... |
2885b6a4a9d88743cf56561d122b6dcf179f86a0 | urmustafa/python_tasks | /python_task-06.py | 316 | 3.96875 | 4 | # while loop ile aklımdaki sayıyı bil oyunu
answer = 40
question = "Enter a number : "
print("Let's play game!")
while True :
guess = int(input(question))
if answer < answer:
print("Little higher")
elif answer > answer :
print("Little lower")
else :
print("Are you mindreader?")
break
|
22d0245623841b17e81d7d9b3e5553da917a4d21 | jonchhen/CS3354-teamAwesome | /projUnitTest.py | 985 | 3.875 | 4 | #Unit Test written in python
import unittest
class TestBookMethods(unittest.TestCase):
# nextPage should set currentPage to an integer value passed by the user.
# In doing so, we consider the cases numbers in page range, zero or below, and
# past the maximum page count of the book
def test_setPage(self):
... |
35c412079911acaa4ad47b1c3448ebb6531e4ead | Yuichi-iwatalab/Python_Learn_Repository | /chapter12.py | 734 | 3.890625 | 4 | class Orange:
def __init__(self,w,c):
self.weight = w
self.color = c
self.mold = 0
print("Created!")
def rot(self, days, temp):
self.mold = days*temp
or1 = Orange(10,"dark orange")
or1.weight = 100
or1.color = "light orange"
print(or1.weight)
print(or1.color)
orange =... |
ec1337c5d0c0533964b703c0aa6bf76dd2e4e472 | bbevan/Emphasis | /emphtest.py | 1,654 | 3.6875 | 4 | import unittest
from emph import *
import random
# pre-selected "random" numbers from the seed 123456789;
# they're in the array backwards for the sake of pop();
# the tests effictively synchronize r with the seed to
# the rng. This is its intended purpose.
text = "one two three four five"
em = ['<em>', '</em>']
b = ... |
e50d18a4868cd178cf3bfa267eb4bfae9078af5f | AndresCallejasG/holbertonschool-higher_level_programming | /0x0A-python-inheritance/10-square.py | 543 | 3.96875 | 4 | #!/usr/bin/python3
"""Inheritance project
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
""" Square class, inherts from Rectangle
"""
def __init__(self, size):
""" init method
Arguments:
size {int} -- Square's size
"""
super().i... |
3a5799e02f956e88f27f2c6d81953a274536cb5e | AndresCallejasG/holbertonschool-higher_level_programming | /0x0A-python-inheritance/7-base_geometry.py | 656 | 3.53125 | 4 | #!/usr/bin/python3
"""Inheritance project
"""
class BaseGeometry():
""" Improved Geometry
"""
def area(self):
"""returns area - not implemented yet
"""
raise Exception("area() is not implemented")
def integer_validator(self, name, value):
"""Validates that value is a ... |
12b445121f9502189b6d3534196f2ddecd07253d | AndresCallejasG/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 145 | 3.796875 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
new = {}
new = {key: (a_dictionary[key] * 2) for key in a_dictionary}
return new
|
a26d8a5c9f82ba0c7cdf5608cbd451397f3f6f40 | AndresCallejasG/holbertonschool-higher_level_programming | /0x03-python-data_structures/4-new_in_list.py | 170 | 3.578125 | 4 | #!/usr/bin/python3
def new_in_list(my_list, idx, element):
new = list.copy(my_list)
if idx < len(my_list) and idx >= 0:
new[idx] = element
return new
|
b7430b669331a0e5f5cbf9284b1e07958f06faed | AndresCallejasG/holbertonschool-higher_level_programming | /0x0B-python-input_output/5-to_json_string.py | 253 | 3.6875 | 4 | #!/usr/bin/python3
""" Input/Output project
"""
import json
def to_json_string(my_obj):
""" returns the JSON representation of an object (string)
Arguments:
my_obj {obj} -- object to be printed
"""
return json.dumps(my_obj)
|
a185c8220308fed8abd2d61775fde5c2bb7e8754 | gitter-badger/Project2A | /pandas101.py | 1,628 | 3.75 | 4 | #
# Fonctions principales nécessaires au traitement de tables de concept formelle.
#
# Basic imports in pandas
import pandas as pd
import numpy as np
from xlrd101 import import_xls
# -- I. Création de la table -- #
# 1. A la main #
df1 = pd.DataFrame(
{
"SW I":[1,0,1,0,1,0],
"Kill Bill":[0,1,1,0,1,1],
... |
cdec7f80ccd1a1d1e5249de0fd530c84a28b54c4 | ParkJeongseop/Algorithm | /Python/2577.py | 177 | 3.65625 | 4 | num = 1
for i in range(3):
num *= int(input())
count = [0 for i in range(10)]
for i in range(len(str(num))):
count[int(str(num)[i])] += 1
for i in count:
print(i) |
3f4bf4fcbea7fd124eb46728c0d9115c54275672 | ParkJeongseop/Algorithm | /Python/4779.py | 194 | 3.703125 | 4 | def f(n):
if n == 1:
return '-'
block = f(n//3)
return block + ' ' * (n//3) + block
while True:
try:
print(f(3**int(input())))
except EOFError:
break |
e00f47287eee09f664208b47e696c6cd9b6e7cc5 | ParkJeongseop/Algorithm | /Python/1924.py | 216 | 3.6875 | 4 | x, y = map(int, input().split())
month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
week = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]
day = y
for i in range(x-1):
day += month[i]
print(week[day%7]) |
3f33532c5360e5fbdbe57607d5c099ca8baf71f9 | shahmilshahidan/mathematics | /mixed_numbers.py | 2,679 | 3.796875 | 4 | import re, math
def mixed_fraction(s):
parsing = re.split("\/", s)
numerator = int(parsing[0])
denominator = int(parsing[1])
if denominator == 0:
raise ZeroDivisionError
elif numerator == 0:
return '0'
result = numerator % denominator
if result == 0:
return str(numer... |
4c0e01485636e314bc7356fda4bf0c77e8f71757 | SergioO21/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,591 | 4.3125 | 4 | #!/usr/bin/python3
""" matrix_divided function """
def matrix_divided(matrix, div):
"""
# Divides all elements of a matrix.
Args:
matrix (list) = The matrix
div (int) = Matrix divisor
- ``matrix`` must be a list of lists of integers or floats,
otherwise raise a ``TypeError`` ex... |
e8b1f3c9dd3e97b74d37ca22c4b88403954ff202 | SergioO21/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 2,299 | 4.1875 | 4 | #!/usr/bin/python3
""" Unittest for ``max_integer`` function """
import unittest
max_integer = __import__('6-max_integer').max_integer
class test_max_integer(unittest.TestCase):
"""
# unittests for the function ``max_integer(list=[])``
"""
def test_one_argument(self):
self.assertEqual(max_in... |
fe443d6ad9c1d93b2c10506a97681e4356dab9fa | SergioO21/holbertonschool-higher_level_programming | /0x0B-python-input_output/8-class_to_json.py | 329 | 3.53125 | 4 | #!/usr/bin/python3
""" Class to JSON """
def class_to_json(obj):
"""
# returns the dictionary description with simple data structure
(list, dictionary, string, integer and boolean) for JSON
serialization of an object.
Args:
obj (class) = Instance of a Class.
"""
return (obj._... |
725ff0d07c62ebda16b710000f79a838917e5e2a | themertzy/Python-UM | /Math/PyCalc.py | 1,132 | 3.609375 | 4 | class calculator:
def __init__(self):
self.fuctioncalls = 0
def add(self, a, b):
return float(a + b)
def subtract(self, a, b):
return float(a-b)
def multiply(self, a, b):
return float(a*b)
def divide(self, a, b):
return float(a / b)
def power(base, exp):
if(exp==1):
... |
6ac10b8629531cd423e089a2a70f09d57faf7725 | guenter82/myschool.dagucar | /org.myschool.dagucar.release/simulator.plugin/python/old-examples/turtle-aufgabe7.py | 309 | 3.5 | 4 | from gturtle import Turtle
def vieleck(ecken):
angle = 360 / ecken
repeat ecken:
t.forward(50)
t.left(angle)
t = Turtle()
anzahl = inputInt("Gib die Anzahl der Ecken an [3-10]:")
i = 10
angle=360/i
t.hideTurtle()
repeat i:
vieleck(anzahl)
t.left(angle)
|
85686c4d05e6b6d3672cc35bd6d1be81f39dc1a3 | jcbbeiter/misc-projects | /advent_of_code_2017/03.py | 576 | 3.5 | 4 | #!/usr/bin/env python2.7
import math
# First part
nums = [12, 23, 1024, 368078]
for num in nums:
factor = 1
while num > factor**2:
factor = factor + 2
largest = factor**2
smallest = (factor-2)**2
ring = (factor-1)/2
ordinal = (num-smallest)%(2*ring)
diff = ring-ordinal if ordina... |
aa918d60f044a0199b04fc0f95fe999621db62a9 | jcbbeiter/misc-projects | /advent_of_code_2017/09.py | 893 | 3.5625 | 4 | #!/usr/bin/env python2.7
def process(stream):
garbage = False
depth = 0
score = 0
garbage_count = 0
i = 0
while i < len(stream):
if garbage:
if stream[i] == '!':
i = i + 1
elif stream[i] == '>':
garbage = False
else:
... |
b54c86d6a2cab9e5d92e5501e68d7e3f054600f4 | poke53280/ml_mercari | /Train_Stemmer.py | 3,077 | 3.671875 | 4 | # http://napitupulu-jon.appspot.com/posts/text-learning-ud120.html
import numpy
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
string1 = "hi Katie the self driving car will be late Best Sebastian"
string2 = "Hi Sebastian the machine learning will be great greate best Kat... |
5eda140dc39c4af82486e233b7eb080e09255f66 | htong01/Biology-Model | /Final/popu_with_note.py | 3,347 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 9 21:37:51 2018
@author: yuanning
"""
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
'''
this is for 2 species, B x2 eats x1
assume:
1 when the food is plenty, the birth rate is in direct proportion to its ... |
c62e478e67ef88f6dbc076d066e371b816abb918 | htong01/Biology-Model | /5_ManducaModel/manducaFitness.py | 9,514 | 3.5625 | 4 | # This function returns the distance covered by Manduca's head.
# Inputs:
# Two 10-row matrices; each row is one of the 10 time segments.
# - 'muscles' is a 10x4 matrix of muscle forces; all entries are 100 or 0
# - 'legs' is a 10x5 matrix of legs locked. 1 means locked, 0 means not.
# - 'record': if 0 or not supplied,... |
336d444b002b302a75a5697bcf9c4301ccd93248 | gabrieloest/dictionary | /module/main.py | 232 | 3.578125 | 4 | import json
import dictionary
data = json.load(open("./data/dictionary.json"))
dictionary = dictionary.Dictionary(data)
word_user = input("Enter a word:")
output = dictionary.search_word(word_user)
dictionary.print_result(output)
|
808811951c539c67504735063f407442135aa7d9 | meighanv/05-Python-Programming | /LABS/Threading/multithreading.py | 1,309 | 4.21875 | 4 | """
Running things concurrently is known as multithreading
Running things in parallel is known as multiprocessing
I/O bound tasks - Waiting for input and output to be completed,
reading and writing from file system,
network operations
These all benefit more f... |
4a23b8eca75e3ab4d85135818bf5c496292894d4 | meighanv/05-Python-Programming | /LABS/Labs-3-4/lab3-4-9-shipCharge.py | 1,160 | 4.21875 | 4 | #Setting up main function
def main():
#Calling Charge function passing result of the getWeight function as an argument
calcCharge(float(getWeight()))
#Defining function to capture and validate the user's input of the number of packages purchased
def getWeight():
#Getting initial input
packageWeight = i... |
37c5c209079b920c816c6a06442630b6ee933fe2 | meighanv/05-Python-Programming | /LABS/Classes/cellphone.py | 2,698 | 4.5 | 4 | """
Wireless Solutions, Inc. is a business that sells cell phones and wireless service.
You are a programmer in the company’s IT department, and your team is designing a program to manage
all of the cell phones that are in inventory. You have been asked to design a class that represents
a cell phone. The data that sh... |
7d98bd2fd04350fe32eb01b62a271deadf7aa638 | meighanv/05-Python-Programming | /Algorithms/counting.py | 453 | 3.890625 | 4 | # This prints number of iterations for problem sizes that double
# using a single loop
problemSize = 1000
for count in range(5):
# Accumulator for the number of instructions
number = 0
# Start of Algorithm
work = 1
for j in range(problemSize):
for k in range(problemSize):
numb... |
d4fe3d0ffdf97fdaead64e61cedb80d097a5c28f | meighanv/05-Python-Programming | /LABS/DICTIONARIES-SETS/dict-set-capitol.py | 950 | 4.09375 | 4 | import random
capitols = {'Virginia':'Richmond',
'Texas':'Austin',
'New York':'Albany',
'Maryland':'Baltimore'}
def main():
correct = 0
incorrect = 0
count = 0
while count < 3:
states = getStates(capitols)
state = quizChoice(states)
if getAn... |
a4eb1b6d68bc9568f7261304f5bdc685c5e10fab | meighanv/05-Python-Programming | /LABS/Labs-3-4/lab3-4-5-colorMixer.py | 818 | 3.984375 | 4 | #Defining CONSTANT array of primary colors
PRI_COLORS = ['red','blue','yellow']
MIXES = {'redblue': 'purple',
'bluered': 'purple',
'blueyellow': 'green',
'yellowblue': 'green',
'yellowred': 'orange',
'redyellow': 'orange'
}
def main():
color1 = getColor()
color2 = getColor()
mixColor... |
3e52bda4af910dccd9710c8d2bfd86388fe4fe07 | meighanv/05-Python-Programming | /LABS/recursion/rec-lines.py | 442 | 4.53125 | 5 | """
3. Recursive Lines
Write a recursive function that accepts an integer argument, n. The function should display
n lines of asterisks on the screen, with the first line showing 1 asterisk, the second line
showing 2 asterisks, up to the nth line which shows n asterisks.
"""
def main():
recLines(7)
d... |
9608a3857524bea6b4356013b8ff78fa0aa1e1e4 | meighanv/05-Python-Programming | /LABS/Threading/multithreading2.py | 569 | 3.890625 | 4 | """
Run 10 threads
We can also now pass in an argument for seconds
"""
import threading
import time
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping {seconds} second(s)...')
time.sleep(seconds)
print('Done Sleeping...')
# initialize list of threads
threads = []
# set up loop to s... |
d00a40884ba51cd5e12a01541e6dd828b884088a | meighanv/05-Python-Programming | /LABS/Classes/animals.py | 1,084 | 4.125 | 4 | class Mammal:
# Initializing Mammal object attributes
def __init__(self, species):
self.__species = species
def show_species(self):
print('I am a ', self.__species)
def make_sound(self):
print('Grrr')
class Dog(Mammal):
# Initializing Dog subclass object attributes
de... |
d7ed0009cbf618921988a81e0f7dee29e14913f1 | meighanv/05-Python-Programming | /LABS/Labs-3-1/lab3-1-7.py | 273 | 3.953125 | 4 | #Miles per gallon calculator
#Asking user for miles driven and gas used
milesDriven = input('Provide miles driven:\n')
gasUsed = input('Provide gallons of gas used:\n')
mpg = float(milesDriven)/float(gasUsed)
print('The miles used per gallon was {:.2f}'.format(mpg)) |
7f42e3ab86260b7cf128a676b60a6fc7bb2365f1 | meighanv/05-Python-Programming | /LABS/Labs-6-1/lab6-1-10.py | 197 | 3.765625 | 4 | rows = input('Row height')
columns = input('column width')
for i in range(int(rows)):
for i in range(int(columns)):
print('#', end='')
print(' '*i, end='')
print('#')
|
bab0a4b95d1487f5beaa7c40cbb0a6545cbb794b | meighanv/05-Python-Programming | /Trees/trees.py | 3,125 | 3.75 | 4 | """
Binary tree is a tree data structure in which wach node has at most two
children which are left child and right child
Top node is the root
Complete binary tree - Every level, except possibly the last, is
completely filled and all nodes in the last level
are as ... |
3c02cf70dec31ebebc481d91ec12d35a963001ae | meighanv/05-Python-Programming | /LABS/Lab-2-1/lab2d.py | 240 | 4.09375 | 4 | print("Please input a string:")
x = str(input())
count = len(x) - 1
revStr = ''
while count >= 0:
revStr += x[count].upper()
count -= 1
print("Your string was " + x + ". your string reversed and capitalized is " + revStr + "!")
|
6963e9b7069b8bcd986331c1fe8a244eca289398 | meighanv/05-Python-Programming | /LABS/DICTIONARIES-SETS/dict-set-wordcount.py | 1,981 | 4.4375 | 4 | #This program is to grab all the unique words in a file.
def main():
#this is the dictionary to store a word count for each unique word
wordcount = {}
#Stores the lines of the file specified by the user
source = readFile()
#This calls the function to extract all the words from a file
words ... |
1d62245208f7b471d5b153e8484b6c22f333d813 | meighanv/05-Python-Programming | /LABS/Projects/crypto.py | 498 | 3.828125 | 4 | alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
string_input = input("Enter a string to encrypt:")
shift = int(input('Provide th enumber of places to shift input:'))
input_length = len(string_input)
print(string_input)
#print(input_length)
string_output = ""
for i in range(input_length):
chara... |
024c7e170cd7ac8d85e72f4e5f4e12d31ef235ef | meighanv/05-Python-Programming | /LABS/Iteration/zip_func.py | 307 | 3.796875 | 4 | # zip() function
# a good way to take two sequences of data and
# pair elements together
# set up two lists
prices = [72.51, 9.27, 153.74, 30.23, 53.00]
names = ['CAT', 'GE', 'MSFT', 'AA', 'IBM']
# use for loop and zip() to pair together
for name, price in zip(names, prices):
print(name, '=',price) |
9274734c6e50e164d86eb699a38088f1c6259aa1 | meighanv/05-Python-Programming | /LABS/Labs-3-4/lab3-4-8-Discount.py | 1,400 | 4.21875 | 4 | #Setting up main function
def main():
#Calling Discount function passing result of the numPurchase function as an argument
calcDiscount(int(numPurchase()))
#Defining function to capture and validate the user's input of the number of packages purchased
def numPurchase():
#Getting initial input
packages ... |
b55ebd53ebb77477db456d291cb792140abdd0a4 | meighanv/05-Python-Programming | /Algorithms/fastersorting.py | 4,852 | 3.875 | 4 | """
Faster Sorting
Up until now we've leared about sorting methods with a O(n^2) complexity. Even
w/ mods they are only marginally better.
Let's now discuss some algs w/ a complexity of O(log n) or )(n log n)
The secret here is that we use our divide and conquer strategy
Each Alg finds a way of breaking the list int... |
11fbcfd7fa221cccbb29bb6c115b4a4abee7903d | meighanv/05-Python-Programming | /LABS/Classes/cashregister.py | 2,056 | 4.46875 | 4 | """
7. Cash Register
This exercise assumes that you have created the RetailItem class for Programming
Exercise 5. Create a CashRegister class that can be used with the RetailItem class. The
CashRegister class should be able to internally keep a list of RetailItem objects. The
class should have the foll... |
6ed508655be4ba9942be195b59639f862c493c9b | meighanv/05-Python-Programming | /Practice_Test/buildMatrix.py | 1,241 | 4.03125 | 4 | def buildMatrix (rows, cols):
# set midpoint variable for the odd square matrix situation
midpoint = 0
# Identify if parameters define a square matrix
if (rows == cols):
# Checking to see if the dimensions are odd
if (rows%2 != 0):
#Setting the midpoint variable to be an... |
b23211372afe6302c2c4a81313cbe424fccd0bd9 | sandhyakopparla/pythonprograms | /sum.py | 98 | 3.78125 | 4 | #a=10
#b=20
num1=int(input("enter the a"))
num2=int(input("ente the b"))
sum=num1+num2
print(sum)
|
4d2c15a0faea4172da35ad39af43e7cf7af2f831 | sandhyakopparla/pythonprograms | /function1.py | 173 | 3.953125 | 4 | # def function_name():
# print("hello world")
# function_name()
def sayHello(name):
return "hello" +name
getName=input("enter the string:")
print(sayHello(getName))
|
b14621577e1060bc9c56f8147b5f2d6a09d18209 | andrewtmn/python-projects | /Alarm_Clock/alarm_clock.py | 3,251 | 3.765625 | 4 | import time
import tkinter as tk
import winsound
import datetime
from tkinter import messagebox
class AlarmClock():
""" Simple class that represents an alarm clock."""
def __init__(self, master):
""" Constructor of an alarm clock object. """
self._master=master
self._current_time = t... |
8e6382b3fd4a87237c39af5d531b7da6dbe6b253 | halfwaysleet97/test_feb_019 | /qn2.py | 284 | 3.765625 | 4 | class Circle:
pi=22/7
def __init__(self,radius):
self.radius=radius
def getArea(self):
return Circle.pi*self.radius**2
def getCircumference(self):
return 2*Circle.pi*self.radius
st= Circle(5)
print(st.getArea())
print(st.getCircumference()) |
9cca418a272f2fc01d066bb8578aeac425c7b5dd | shivampandoh2000/Chatbot-Recommendation-Sys | /nltk/stop_words.py | 405 | 3.546875 | 4 | import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
stop_words=set(stopwords.words("english"))
print(stop_words)
sen="Hi how , are , you, bye, I an me with you..."
tok=word_tokenize(sen)
filtered_sent=[]
for w in tok:
if w not in stop_words:
filtered_sent.append(w)
print(... |
3d22441754ef037778c9dceacdb8ff248cf38740 | brfarlow/advent_of_code_2016 | /day3/day3-part1.py | 229 | 3.640625 | 4 | with open('input.txt') as f:
valid = 0
for line in f.readlines():
line = sorted([int(x) for x in line.split()])
print(line)
if line[0] + line[1] > line[2]:
valid += 1
print(valid)
|
1b4d0a460da73a473d4c8f169e34ef621df8c1ca | DennisHallerbach/Codewarskatas | /Sum_of_the_first_nth_term.py | 167 | 3.6875 | 4 | def series_sum(n):
below= 1
sum = 0.00
for i in range(n):
sum += (1/below)
below +=3
return "{:.2f}".format(sum)
print(series_sum(1))
|
ff91338092a9465a1b10bda92be847922cd1cc9a | janaleible/hackerrank | /30-days-of-code/day-06.py | 288 | 3.984375 | 4 | number_of_cases = int(input())
for case in range(number_of_cases):
string = input()
odd = ''
even = ''
for index, char in enumerate(string):
if index % 2 == 0:
even = even + char
else:
odd = odd + char
print(even + ' ' + odd) |
e92a8f5f9b93f4ace98db2f6da6a9416b34819d8 | devansh-07/GUI_Calculator | /Calc-tk.py | 6,334 | 3.5625 | 4 | from tkinter import *
from tkinter import ttk
class Calculator(object):
def __init__(self):
self.exp = ""
self.flag = "expression"
self.oper_list = ["+", "-", "*", "/", "**"]
root.bind("<Key>", None)
self.ans_label = Text(root, width=25, height=3, font=("Calibri", 14), bd=0, background="#06989A", highlig... |
041e263bf20440e54deb57f50d18db2dc7586953 | yohn-dezmon/python-projs | /mad_lib_git.py | 734 | 4.53125 | 5 | # Prompt user for their name
name = input("What is your name? ")
# Greeting with users name
print(f'''Hey {name}! Welcome to Mad Libs the program!
Please provide us with...''')
# Prompt user for a noun, adjective, and verb(ING)
noun = input("A noun: ")
adj = input("An adjective: ")
verb = input("A verb ending in ing... |
a53093ab02f768f6de26c4e7955182d098c9bce2 | ccrawford1983/Web-Scraping-Starter-Code | /web_scraping.py | 5,373 | 4.1875 | 4 | '''
CLASS: Web Scraping with Beautiful Soup
What is web scraping?
- Extracting information from websites (simulates a human copying and pasting)
- Based on finding patterns in website code (usually HTML)
What are best practices for web scraping?
- Scraping too many pages too fast can get your IP address blocked
- Pay... |
f97b49d71868b3e45bfb79f831aecf16dc1f5d6a | aishsharma/Karan-Projects | /Solutions/Numbers/Prime_Factorization.py | 1,272 | 4.3125 | 4 | """
Author: Aishwarya Sharma
Question: Prime Factorization - Have the user enter a number and find all Prime Factors (if there are any) and display
them.
"""
from math import sqrt
from typing import List
# Tests if a number is prime or not. Uses simple formula for test.
def is_prime(n: int)->bool:
i... |
95c16969d3928a4ec8993e31640002b5fa95f1c7 | jardellx/arcade | /base/084/solver.py | 375 | 3.53125 | 4 | num = int(input())
slista = input().split(" ")
lista = []
for x in slista:
lista.append(int(x))
olista = sorted(lista)
lista = olista
difer = []
difer.append(lista[0])
for x in range(1, num):
if lista[x] != lista[x - 1]:
difer.append(lista[x])
for x in difer:
print (x, end = "")
if(x != difer... |
2873a032319930bbfe21fcf9e4e2b5be88e017bc | jardellx/arcade | /base/060/solver.py | 200 | 3.515625 | 4 | #!/usr/bin/env python3
lista = [int(x) for x in input().split(" ")]
M = lista[0] #maior
m = lista[0] #menor
for x in lista:
if x > M:
M = x
if x < m:
m = x
print(str(m + M))
|
b70a2362726906617082d79282ce6cb5c15d79f6 | jardellx/arcade | /base/040/solver.py | 256 | 3.84375 | 4 | dia = int(input())
hora = int(input())
minuto = int(input())
if (dia >= 2 and dia <= 6) and ((hora >= 8 and hora < 12) or (hora >= 14 and hora < 18)):
print ("SIM")
elif dia == 7 and (hora >= 8 and hora < 12):
print ("SIM")
else:
print ("NAO") |
a502e5dd23f05ea7ab7f8baada95111b05d276b2 | skybear73/Rechnung | /Uebungen/h-Methode.py | 291 | 3.796875 | 4 | 'Definition'
x = 0
x_i = 0.5
dx = x_i - x
stopp = 10**(-3)
z = 1
'Funktion'
f_x = x**3 - 3*x - 1
dif_f_x = 3*x**2 - 3
'Iterationsvorschrif'
while dx >= stopp and z < 10e5:
z = z + 1
print(z)
x_i = x - f_x/dif_f_x
x = x_i
dx = x_i - x
'Ausgabe'
print(x)
print(dx) |
bad3f3bc881470c895cf0ea118bd2192a29b381a | jeff87b/Python-module-1 | /Day 1-5/007 The area of a square with if and else.py | 405 | 4.28125 | 4 | print ("This program calculates the area of a square.")
side1 = float(input("Enter side number one: "))
side2 = float(input("Enter side number two:"))
print("The area is:", side1*side2)
if side1<0:
print("You have entered a negative first number")
else:
print("The first number is ok")
if side2<0:
print("Yo... |
2f218b9f31c503b5ff1ed49b311a44a8e1e9c31b | jeff87b/Python-module-1 | /Day 6-10/Day 8/02.py | 316 | 4.125 | 4 | yearEntered = int(input("Enter a year: "))
def isLeapYear(year_entered):
leapYearAlg = year_entered % 4
moreLeapYearAlg = year_entered % 100
if leapYearAlg == 0 and moreLeapYearAlg == 0:
print("Yes it's a leap year")
else:
print("No, it's not a leap year")
isLeapYear(yearEntered)
|
9de78fd43f6ce55871ace3dbc267c5f5791732a2 | jeff87b/Python-module-1 | /Day 1-5/024 Task for homework turtle.py | 228 | 4 | 4 | import turtle
myTurtle = turtle.Turtle()
count = 0
starSize = int(input("Enter the size of the star: "))
while count in range(0, 5):
myTurtle.forward(starSize)
myTurtle.right(144)
count = count + 1
turtle.done()
|
1bb64c7dc478443cc59a76fff9dc177aa338a9d2 | jeff87b/Python-module-1 | /Day 1-5/009 New python file 2.py | 189 | 3.78125 | 4 | theYearIEntered=int(input("Please enter a year in the future: "))
theYearIWasBornIn=int(input("Please enter the year in witch you where born: "))
if theYearIEntered ==1900:
print("Ok")
|
855a0d6c510b845653aa861b4ea41c0f9b1d4703 | jChapman/ponlygono | /polygono/test/test_circle.py | 1,063 | 3.703125 | 4 | from polygono.polygon import Circle, Point
def test_simple_creation():
circle = Circle(Point(0, 0), 1)
def test_self_intersecting():
circle = Circle(Point(0, 0), 1)
assert circle.intersects(circle)
def test_simple_intersection():
# Point of one is within the radius of another
c1 = Circle(Point... |
2244ce27906555df5f547b31144268b2e93b2d4a | CharmingTree/PythonLearning | /solution/phoneBook.py | 1,668 | 3.78125 | 4 | def solution(phone_book):
answer = True
s = set(phone_book)
if len(s) != len(phone_book):
return False
phoneMap = {}
for i in range(len(phone_book)):
if phone_book[i][0] not in phoneMap:
phoneMap.setdefault(phone_book[i][0], [phone_book[i]])
else:
ph... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.