blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
f78f63eee3f5c35d2a564abb81adf7a24f5dba3f | BryCant/Intro-to-Programming-MSMS- | /FInal/finalLibrary.py | 2,489 | 3.84375 | 4 | import random
class Student:
def __init__(self, name, age, glasses, volume, nag_level):
self.name = name
self.age = age
self.glasses = glasses
self.volume = volume
self.nag_level = nag_level
def __str__(self):
return f"Hi I am {self.name} and I am {self.age} ye... |
53439bc9fed95069408cec769fddd8fc2fc9376d | BryCant/Intro-to-Programming-MSMS- | /Chapter13.py | 2,435 | 4.34375 | 4 | # Exception Handling
# encapsulation take all data associated with an object and put it in one class
# data hiding
# inheritance
# polymorphism ; function that syntactically looks same is different based on how you use it
"""
# basic syntax
try:
# Your normal code goes here.
# Your code should include function ... |
ec9dc44facac9d6f6bdda9f3eb7c178c0b67ff0f | iannase/win2k17 | /cycles.py | 508 | 3.796875 | 4 | wholeString = input()
shifter = ""
stringList = []
stringSize = ""
stringShift = ""
shift = 0
size = 0
z = 0
for x in wholeString:
if z == 0:
stringSize += x
if z == 1:
stringList.append(x)
if z == 2:
stringShift+= x
if x == " ":
z += 1
size = int(stringSize)
shift = int(stringShift)
stringList.pop(size)
f... |
2679e524fb70ea8bc6a8801a3a9149ee258d9090 | daviscuen/Astro-119-hw-1 | /check_in_solution.py | 818 | 4.125 | 4 | #this imports numpy
import numpy as np
#this step creates a function called main
def main():
i = 0 #sets a variable i equal to 0
x = 119. # sets a variable x equal to 119 and the decimal makes it a float (do you need the 0?)
for i in range(120): #starting at i, add one everytime the program gets to t... |
d0da8ed0d77bc22e2b4212747ecbcf6c82b9a30c | mvinovivek/BA_Python | /Class_3/1_4_ValueError.py | 303 | 3.671875 | 4 | #Value error will be raised when you try to change the type of an argument with improper value
#most common example of the value error is while converting string to int or float
number=int("number")
#The above statement will throw an error as "number" as a string cannot be considered as int or float
|
0d4aad51ef559c9bf11cd905cf14de63a6011457 | mvinovivek/BA_Python | /Class_3/8_functions_with_return.py | 982 | 4.375 | 4 | #Function can return a value
#Defining the function
def cbrt(X):
"""
This is called as docstring short form of Document String
This is useful to give information about the function.
For example,
This function computes the cube root of the given number
"""
cuberoot=X**(1/3)
retur... |
53cee6f939c97b0d84be910eee64b6e7f515b12f | mvinovivek/BA_Python | /Class_3/7_functions_with_default.py | 680 | 4.1875 | 4 | # We can set some default values for the function arguments
#Passing Multiple Arguments
def greet(name, message="How are you!"):
print("Hi {}".format(name))
print(message)
greet("Bellatrix", "You are Awesome!")
greet("Bellatrix")
#NOTE Default arguments must come at the last. All arguments before default are... |
626da3ed48d7dabc2074e13c6c6fda948a5ab34c | mvinovivek/BA_Python | /Class_3/1_7_IndexError.py | 327 | 3.953125 | 4 | #index errors will be raised when you try to access an index which is not present in the list or tuple or array
X=[1,2,3,4,5]
print(X[41])
#in case of dictionaries it will be KeyError
Person={
'Name': 'Vivek',
'Company' : 'Bellatrix'
}
print(Person['Name']) #it will work
print(Person['Age']) #it will throw K... |
0eb58cd27ce6822be0c7dc2d66524bbd6a207659 | mvinovivek/BA_Python | /Class_4/10_comparting_projectiles_class.py | 2,365 | 3.90625 | 4 | import numpy as np
import matplotlib.pyplot as plt
class projectile():
g=9.81
def __init__(self,launch_angle,launch_velocity):
self.launch_angle=launch_angle
self.launch_velocity=launch_velocity
def duration(self):
duration=2*self.launch_velocity*np.sin(np.radians(self.launch_angl... |
3cb1bc2560b5771e4c9ec69d429fcfd9c0eadd2c | mvinovivek/BA_Python | /Class_2/7_for_loop_2.py | 1,009 | 4.625 | 5 | #In case if we want to loop over several lists in one go, or need to access corresponding
#values of any list pairs, we can make use of the range method
#
# range is a method when called will create an array of integers upto the given value
# for example range(3) will return an array with elements [0,1,2]
#now we can... |
3cbfde72e5c26d2a8f498273e1e11ce7c8d65fe1 | mvinovivek/BA_Python | /Class_5/7_widgets_radio_use.py | 855 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
Xvals=np.linspace(0,2*np.pi,50)
Yvals=np.sin(Xvals)
Zvals=np.cos(Xvals)
#Creating the Plot
# Plotting
fig = plt.figure()
ax = fig.subplots()
plt.subplots_adjust(right=0.8)
plt.title("Click the Radio Button to Change the C... |
c9a6c2f6b8f0655b3e417057f7e52015794d26d6 | 316126510004/ostlab04 | /scramble.py | 1,456 | 4.40625 | 4 | def scramble(word, stop):
'''
scramble(word, stop)
word -> the text to be scrambled
stop -> The last index it can extract word from
returns a scrambled version of the word.
This function takes a word as input and returns a scrambled version of it.
However, the letters in the beginning and ending do not change.
... |
c456b13bb5316097a6856510e0e0140765216f18 | Rahulllkumarrr/Simple-Program | /Cut the sticks.py | 2,366 | 3.65625 | 4 | '''
Cut the stick
-------------
You are given a number of sticks of varying lengths. You will iteratively cut
the sticks into smaller sticks, discarding the shortest pieces until there
are none left. At each iteration you will determine the length of the
shortest stick remaining, cut that length from each of th... |
a7a2abaa6a70a9da4f81c1c5a9d7d231e9551434 | Rahulllkumarrr/Simple-Program | /diagonal Difference.py | 492 | 3.796875 | 4 | def diagonalDifference(a):
right,left=0,0
n=len(a)
l=n-1
r=0
for i in range(n):
right=right+(a[r][r])
left=left+a[r][l]
r+=1
l+=-1
difference=abs(right-left)
return difference
if __name__ == "__main__":
n = int(input().strip())
a = []... |
476f71e3734a9ab494dd28662b5ceac58f321ffc | TundraStorm/raticus | /MyGame/on_key_press.py | 555 | 3.671875 | 4 | import arcade
def on_key_press(self, key, modifiers):
"""Called whenever a key is pressed. """
# If the player presses a key, update the speed
if key == arcade.key.UP:
self.player_sprite.change_y = 7
#self.player_sprite.change_y = -MOVEMENT_SPEED*0.5
elif key == arcade.key.DOWN:
... |
d24514f8bed4e72aaaee68ae96076ec3921f5898 | ChanghaoWang/py4e | /Chapter9_Dictionaries/TwoIterationVariable.py | 429 | 4.375 | 4 | # Two iteration varibales
# We can have multiple itertion variables in a for loop
name = {'first name':'Changhao','middle name':None,'last name':'Wang'}
keys = list(name.keys())
values = list(name.values())
items = list(name.items())
print("Keys of the dict:",keys)
print("Values of the dict:",values)
print("Items of th... |
d22d71b73ef371210d49a71f2abb69383e97cca8 | ChanghaoWang/py4e | /Chapter2/assignment2_3.py | 260 | 3.78125 | 4 | inp_hour=float(input('Enter the hour:'))
inp_rate=float(input('Enter the rate per hour:'))
if inp_hour > 40:
inp_rate_new=1.5*inp_rate
grosspay = inp_rate_new*(inp_hour-40)+40*inp_rate
else:
grosspay=inp_hour*inp_rate
print('Grosspay is',grosspay)
|
47675250b07dd0f5a0c3eae348b35ee4885a04a2 | ChanghaoWang/py4e | /Chapter10_Tuples/Commonwords.py | 671 | 3.921875 | 4 | #Count words Chapter 10 Page 131
import string
inp = input("Please enter the filename: ")
if len(inp) < 1:
inp = 'romeo-full.txt'
try:
fhand = open(inp)
except:
print("Cannot open the file:",inp)
quit()
count_dict = dict()
for line in fhand:
line = line.translate(str.maketrans('','',string.punctuati... |
3cae3e36c80ac6d2040d872705091194edc954af | ChanghaoWang/py4e | /Chapter8_Lists/modify.py | 612 | 4.09375 | 4 | # List modify
#It's important to remember which methods modify the list or create a new one
def delete_head(t):
del t[0]
def pop_head(t):
t.pop(0)
def add_append(t1,t2):
t1.append(t2)
def add(t1,t2):
return t1 + t2
def delete_head_alternative(t):
return t[1:]
letters = ['a',1,'b',2,'c',3]
delete_hea... |
6d325039a3caa4c331ecc6fa6bb058ff431218f8 | ChanghaoWang/py4e | /Chapter8_Lists/note.py | 921 | 4.21875 | 4 | # Chapter 8 Lists Page 97
a = ['Changhao','Wang','scores',[100,200],'points','.']
# method: append & extend
a.append('Yeah!') #Note, the method returns None. it is different with str
a.extend(['He','is','so','clever','!'])
# method : sort (arranges the elements of the list from low to high)
b= ['He','is','clever','!']
... |
4be436e6a4b5aff0bcdd99dded5d1a2c3ce0763e | ChanghaoWang/py4e | /Chapter11_Expressions/Exercise1.py | 329 | 3.921875 | 4 | # Exercise 1 Chapter 11 Page 149
import re
inp = input("Enter a regular expression: ")
if len(inp) < 1:
inp = '^From:'
fhand = open("mbox.txt")
count = 0
for line in fhand:
line = line.strip()
words = re.findall(inp,line)
if len(words) > 0:
count += 1
print("mbox.txt had",count,"lines that match... |
c2b24f3f587202bdea4e6ec7895d06f70e9c3d04 | celine5/GUVIrepo | /even.py | 118 | 4.25 | 4 | num=int(input("enter a number:"))
if(num%2)==0:
print("{0} is even".fomat(num))
else:
print("{0} is odd".format(num))
|
802707f723581bda40c9d53b34d12858a58592d5 | celine5/GUVIrepo | /vowelc.py | 245 | 3.859375 | 4 | original =input('Enter a character:')
character= original.lower()
first =character[0]
if len(original) > 0 and original.isalpha():
if first in 'aeiou':
print("Vowel")
else:
print("Consonant")
else:
print ("invalid")
|
1f36f982a91c6257911b91f1f5005d900fac104c | junbeomLim/Algorithm | /BOJ/backjoon 2750.py | 129 | 3.59375 | 4 | N = int(input())
n = [0 for i in range(N)]
for i in range(N):
n[i] = int(input())
n.sort()
for i in range(N):
print(n[i]) |
d21ea5dda881f239defc04d28018acc89ac99c86 | ArpitaBawgi/Devops-Training | /third.py | 274 | 3.984375 | 4 | name=''
condition=True
while(condition):
print('who are you')
name=input()
if(name!='joe'):
continue
else:
print("Hello Joe, What is password?(it is fish)");
password=input();
if(password =='swoardfish'):
#condition=False;
break;
print('Access Granted')
|
a632cf8c425a392504331ee4413aeb4727ea4318 | wesyang/sudoku_solver | /misc/findIslands.py | 1,606 | 3.625 | 4 | class Solution(object):
def printMap(self, map):
for r in map:
for c in r:
print(f'{c} ', end='')
print()
print('-----------------')
def checkAndMarkIsland(self, map, x, y, cc, rc):
if x < 0 or y < 0: return
if x >= cc or y >= rc: return
... |
63155a1d3a461b958561d57c38adbea2c8be1e26 | wesyang/sudoku_solver | /misc/getSqrt.py | 1,394 | 3.65625 | 4 | class Solution(object):
@staticmethod
def getSqrt(min, max, x):
while (True):
mid = int((max - min +1) / 2) + min
mm = mid * mid
#print (min, mid, max, mm, x)
if mm == x:
return mid
elif mm < x:
nextSqrt = (mid... |
c76f613f2855a56d738d64439a2d857d1ca15781 | jayashreemohan29/pmemkv-testing | /count_ops.py | 882 | 3.640625 | 4 | #!/usr/bin/env python
import getopt
import sys
def main():
#input arg : file name
if (len(sys.argv) != 2):
print("Please input log file")
exit(1)
log_file = sys.argv[1]
count = 0
count_fence = 0
count_flush = 0
count_store = 0
count_others = 0
operations = open(log_file).read().split("|")
for op in ... |
007064524296a592bf238f413029a41a12bafc0b | bharath144/PythonWorkshop | /sorting/bubble_sort.py | 1,481 | 3.703125 | 4 | import random
import time
input_a = [x for x in range(0, 1000)]
input_b = random.sample(input_a, 10)
input_c = input_b.copy()
def iterative_sort(unsorted_list):
print(unsorted_list)
for i in range(0, len(unsorted_list)):
# Improved exit condition, if there are no swaps, all numbers are sorted
... |
3422c8df4de8e5e1bf18e154be725f7879f797c5 | MaxMcCarthy/Recommender-System | /Scraper/web_scraper.py | 6,479 | 3.71875 | 4 | from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
import csv
# with help from:
# https://realpython.com/python-web-scraping-practical-introduction/
def simple_get(url):
"""
Attempts to get the content at `url` by making an ... |
b2e057bd9d63ba6da9a755f2c879bc58ae65086b | tomcat1969/CodingDojo_python_stack | /python/fundamentals/forloopbasic2.py | 1,654 | 3.953125 | 4 | # def biggie_size(list):
# for i in range(len(list)):
# if list[i] > 0:
# list[i] = "big"
# return list
# print(biggie_size([-1,3,5,-5]))
# def count_positives(list):
# count = 0
# for i in range(len(list)):
# if list[i] > 0:
# count = count + 1
# list[len(list)-1] = count
# return list
# print... |
d593ffafc59015480c713c213b59f6304914d660 | Ayush10/python-programs | /vowel_or_consonant.py | 1,451 | 4.40625 | 4 | # Program to check if the given alphabet is vowel or consonant
# Taking user input
alphabet = input("Enter any alphabet: ")
# Function to check if the given alphabet is vowel or consonant
def check_alphabets(letter):
lower_case_letter = letter.lower()
if lower_case_letter == 'a' or lower_case_letter == 'e' or... |
2676477d211e0702d1c44802f9295e8457df21a8 | Ayush10/python-programs | /greatest_of_three_numbers.py | 492 | 4.3125 | 4 | # Program to find greatest among three numbers
# Taking user input
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
# Comparison Algorithm and displaying result
if a > b > c:
print("%d is the greatest number among %d, %d and %d." % (a, a, b, c))
... |
172102809e9f1fc0ebf8516b78f7dab417f05e5e | ecarlos09/procedural-python-exercises | /name_generator/penguin_name.py | 423 | 3.5 | 4 | penguin_converter = {
"January": "Mumble",
"February": "Squeak",
"March": "Skipper",
"April": "Gloria",
"May": "Kowalski",
"June": "Rico",
"July": "Private",
"August": "King",
"September": "Pingu",
"October": "Feathers McGraw",
"November": "Chocolatey",
"December": "Ice C... |
82b3b3358fc08521b6e714a7d1b5cf2c40aee47c | MiriSilva/Avaliacao1 | /Questao2.py | 354 | 4.09375 | 4 | n1 = int(input("informe um numero inteiro: "))
n2 = int(input("informe um numero inteiro: "))
n3 = float(input("informe um numero real: "))
print ("o produto do dobro do primeiro com metade do segundo è :", n1*2*(n2/2))
print ("a soma do triplo do primeiro com o terceiro é:", (n1*3)+n3 )
print ("o terceiro... |
a42ff81b035de48e6628dbac29315ae1e2e78bb1 | MiriSilva/Avaliacao1 | /Questao4.py | 363 | 3.828125 | 4 | x = float(input("Informe quanto ganha por hora:"))
y = float(input("Informe quantas horas trabalhadas no mês:"))
SB = (x*y)
IR = SB * 0.11
INSS = SB* 0.08
SD = SB*0.05
SL = SB-(IR+INSS+SD)
print("Salário Bruto : R$",SB)
print("IR (11%) : R$",IR )
print("INSS (8%) : R$",INSS )
print("Sindicato ( 5%) : R$"... |
3fefcd97afaccac58e7c18e5303c44d2c11699a0 | hendy3/A-beautiful-code-in-Python | /Teil_15_Sudoku_Algorithm_x.py | 2,701 | 3.8125 | 4 | #!/usr/bin/env python3
# Author: Ali Assaf <ali.assaf.mail@gmail.com>
# Copyright: (C) 2010 Ali Assaf
# License: GNU General Public License <http://www.gnu.org/licenses/>
from itertools import product
import time
def solve_sudoku(size, grid):
""" An efficient Sudoku solver using Algorithm X.
"""
R, C = size
... |
e50f8e37210054df2e5c54eb55e7dee381a91aff | super468/leetcode | /python/src/BestMeetingPoint.py | 1,219 | 4.15625 | 4 | class Solution:
def minTotalDistance(self, grid):
"""
the point is that median can minimize the total distance of different points.
the math explanation is https://leetcode.com/problems/best-meeting-point/discuss/74217/The-theory-behind-(why-the-median-works)
the more human language ... |
71c87f644ac21e84586fa2fcb51e9c160151c6a7 | super468/leetcode | /python/src/FlipGameII.py | 749 | 3.734375 | 4 | """
the basic idea is that track every movement of the first player, if the other player can not make a movement, then movement
the first player made is a winning movement.
the optimization is to use memorization to memorize the string state that we have seen.
this is a backtracking problem with memorization optimizati... |
3228d9c857bd5e39ca56b0d8d5f4f43b8c8f8d5c | scotchka/scotchka.github.io | /2018/06/16/balance_brackets.py | 821 | 3.578125 | 4 | import inspect
BRACKETS = {")": "(", "]": "[", "}": "{"}
def _stack(chars):
"""Push/pop frames to/from call stack."""
while chars:
char = chars.pop(0)
if char in BRACKETS.values():
_stack(chars) # push
elif char in BRACKETS:
previous = inspect.stack()[1]
... |
cdccb6138c604da36be9d9b97d65e0270bc57cb8 | monicadsong/matrix_factorization_mp | /test_multiprocessing.py | 3,289 | 3.5625 | 4 | import multiprocessing
from multiprocessing import pool
print("cpu count: ", multiprocessing.pool.cpu_count())
import os, time
# g_cnt is not shared with each worker
def test_process_with_global_variable():
g_cnt = 4
def worker(idx, data, g_cnt):
global g_cnt
g_cnt += 1
time.sleep(1)
print("wo... |
a5333df631bfbbc3f2ab5e6f8631eb7cb17611f1 | PanchoF1/56107-Francisco-Saldana | /Clase05 Calculadora/calculadora_test.py | 1,052 | 3.546875 | 4 | import unittest
from clases import Calculator
class TestCalculador(unittest.TestCase):
def resul_calculator_1_add_1_(self):
calc = Calculator()
calc.ingresar('1')
calc.ingresar('+')
calc.ingresar('1')
calc.ingresar('=')
self.assertEqual(calc.display(),'2')
... |
3da888a1d429023b69d7e4efd7e4f7d6909e3f75 | afterthought325/cp_lab | /atm_machine-0.5.py | 3,095 | 3.84375 | 4 | ################################################################################
# Name: Chaise Farrar Date Assigned:10/16/2014 #
# Partner: Rebecca Siciliano #
# Course: CSE 1284 Sec 10 Date Due: 10/16/2014 ... |
977125662ad8ba83bbe8cedc6bce54ab9836d207 | kunxin-chor/tgc-python | /select-example/main.py | 343 | 3.515625 | 4 | import pymysql
connection = pymysql.connect(host='localhost',
user="admin",
password="password",
database="Chinook"
)
cursor = connection.cursor()
cursor.execute("SELECT * from Employee")
for r in cursor:
# print (r)
# We have to refer each field by its index
print ("Name: " + r[1] + " " + r[2... |
8b46f6ce79908a511e258e2af636e398387f0474 | accimeesterlin/scrape_linkedin | /filter_contact.py | 2,087 | 3.59375 | 4 | import json
from pprint import pprint
data = json.load(open("contacts.json"))
def set_max(arr, limit):
for index, contact in enumerate(arr):
if index <= int(limit) - 1:
print("_______________________________________")
print("_______________________________________")
pr... |
5e6544c168eba12bfd9cc44e1734ec5dd5691dac | ajaycode/study | /class05/math/tests/test_temperature.py | 827 | 3.5 | 4 | # ..\tests>python test_fraction.py
import unittest
from unittest import TestCase
__author__ = 'Ajay'
import sys
sys.path.append('..\\')
from temperature import *
class TestTemperature(TestCase):
def test_celsius_from_fahrenheit(self):
question, answer = celsius_from_fahrenheit (60)
self.assertE... |
d60032107ecb73851a9abeb29cc1f5dedcf0b111 | nicolassnider/udemy_machine_learning_r_python | /testProject/seccion08/tuplas.py | 268 | 3.78125 | 4 | p1=(1,)
p2=(1,2,3,4)
p3=(1,2,'e',3.1415)
print(p1)
print(p2)
print(p3)
print(p3[0:2])
a,b,c,d=p3
print(a)
print(c)
#
L4 = list(p3)
print(L4)
p5=tuple(L4)
print(p5)
#
L=tuple(input('Escribe numeros separados por comas: \n').split(','))
for n in L:
print(2*int(n))
|
10c930abce072e05a3e4b1f1608f918c3b7c5afe | vinaybommana/twitter-analytics | /step_4/influentials_users.py | 1,671 | 3.625 | 4 | import csv
import codecs
import math
def read_csv(filename):
rows = list()
with open(str(filename), "r") as c:
csvreader = csv.reader(c)
next(csvreader)
for row in csvreader:
rows.append(row)
return rows
def main():
second_rows = read_csv("step_two_output.csv")
... |
819cdf9e9e096ce54c22847b91c165171bba45be | Ruslan-Skira/PythonHW1 | /listModification.py | 4,631 | 4.375 | 4 | """Первая версия функции извлекает первый аргумент (args – это кортеж) и обходит
остальную часть коллекции, отсекая первый элемент (нет никакого
смысла сравнивать объект сам с собой, особенно если это довольно крупная
структура данных)."""
def min1(*args):
current = args[0]
for i in args[1:]: # all but the fir... |
69c903b677e32ce1de2e292ef315f68c05361452 | Ruslan-Skira/PythonHW1 | /OOP/test_resource.py | 349 | 3.703125 | 4 | import unittest
from math import pi
import resource
class TestCircleArea(unittest.TestCase):
def test_area(self):
# Test areas when radius > = 0
self.assertAlmostEqual(resource.circle_area(1), pi)
self.assertAlmostEqual(resource.circle_area(55), 1)
self.assertAlmostEqual(resource.c... |
f40434748d69a754a43d733df64129d39bc12e48 | kevinmartinjos/mapleblow | /game.py | 2,270 | 3.640625 | 4 | import pygame
from world import Hurdle
from vector2 import Vector2
from pygame.locals import *
from sys import exit
from leaf import Leaf
from wind import Wind
import wx
start=False
def run_game(run_is_pressed):
pygame.init()
clock=pygame.time.Clock()
screen=pygame.display.set_mode((640,480))
picture='leaf.png'
bl... |
5234c1163f18bfd1e095b287f5a75ec97a37a898 | tfmorris/wrangler | /runtime/python/wrangler/sort.py | 1,806 | 3.5 | 4 | from transform import Transform
def mergesort(list, comparison):
if len(list) < 2:
return list
else:
middle = len(list) / 2
left = mergesort(list[:middle], comparison)
right = mergesort(list[middle:], comparison)
return merge(left, right, comparison)
def merge(left, r... |
72cdf859ab9d5adcbddf25295b4da9dea6015c90 | EdwardTFS/TensorflowExamples | /example1.py | 999 | 3.84375 | 4 | #based on https://developers.google.com/codelabs/tensorflow-1-helloworld
#fitting a linear function
import sys
print("Python version:",sys.version)
import tensorflow as tf
import numpy as np
print("TensorFlow version:", tf.__version__)
from tensorflow import keras
#create model
model = keras.Sequential([keras.laye... |
5d0b56e2c02f10090b62c259d5b7782c144eb840 | prajwolshakya/visualization-sorting-algorithms | /shell_sort.py | 762 | 3.859375 | 4 | from cube import Run
def shell_sort():
run = Run()
arr = run.display()
sublistcount = len(arr) // 2
while sublistcount > 0:
for start in range(sublistcount):
gap_insertion_sort(arr,start,sublistcount,run)
#print(sublistcount)
#print(arr)
sublistcount = sublistcount // 2
return arr
def gap_insertio... |
42167b22a0b27f5172f2c432979a397201cffde4 | 2508Fernan/Taller-3 | /FernandaUshcasina_EstrellaPar_Turtle.py | 507 | 3.921875 | 4 | from turtle import*
import time
import turtle
t= turtle.Pen()
##tamaño de la ventana
turtle.setup (500,600)
##establecer el objeto en pantalla
wn= turtle.Screen()
##color de la pantalla
wn.bgcolor("pink")
##titulo de la pantalla
wn.title("Estrella de Puntas Pares")
a=int(input("ingrese un numero par:"))
pr... |
045cc9ae2292052a918ccca9ab13c76b442ea0bc | SamSweere/MRS | /gui/localization_path.py | 2,861 | 3.578125 | 4 | import pygame
import math
# Draws a dashed curve
# Works by using the fraction variable to keep track of the dash strokes
# fraction from 0 to 1 means dash
# fraction from 1 to 2 means no dash
def draw_dashed_curve(surf, color, start, end, fraction, dash_length=10):
start = pygame.Vector2(start)
end = pygame.V... |
4934d8f72ee6a0b00a6350c29e00f9994ef862ed | marccathomen/troccas | /app/card.py | 516 | 3.5625 | 4 | class Card:
def __init__(self, id, power, value, suit, label):
self.id = id # unique identification number
self.power = power # beating power
# value of the card in points
self.value = value
# suit of the card [r osa,s pada,c uppa,b astun,t rocca,n arr]
self.suit = ... |
1e37be68e28933fc50eb1eff40c74f6fb2d08da0 | Krikiba/ATM | /fonction_atm.py | 466 | 3.515625 | 4 |
def withdraw(request):
i=0
liste=[100,50,10,5,4,3,2,1]
for lis in liste:
if request>=lis :
request-=lis
return request
else :
i+=1
def atm(money,request):
balence=request
print "Current balance =" +str(money)
while request>0:
if request>money :
print ("le montant n'existe pas en ATM"... |
3aeec4d5aae9f02d788af92f97af7e1ad5453940 | mhurtad14/1500-intergration | /intergration project version 2.py | 6,185 | 4 | 4 | #Mijail Hurtado
#Integration Project
#COP 1500
#Professor Vanselow
import math
def get_bmr():
gender = input("What is your gender: M or F?")
age = int(input("What is your age?"))
height = int(input("What is your height in inches?"))
weight = (int(input("What is your weight in pounds?")))
... |
aec194198be1a68b82f0fa306aff480d9e4fc396 | rbusquet/advent-of-code | /aoc_2021/day11.py | 1,880 | 3.53125 | 4 | from itertools import count, product
from pathlib import Path
from typing import Iterator
Point = tuple[int, int]
def neighborhood(point: Point) -> Iterator[Point]:
x, y = point
for i, j in product([-1, 0, 1], repeat=2):
if i == j == 0:
continue
yield x + i, y + j
def flash(poin... |
c1232f17b340a952c18208ffe66c59ad3e5b9243 | rbusquet/advent-of-code | /aoc_2015/day1.py | 622 | 3.640625 | 4 | from pathlib import Path
def part_1() -> int:
with open(Path(__file__).parent / "input.txt") as file:
floor = 0
while step := file.read(1):
floor += step == "(" or -1
return floor
def part_2() -> int:
with open(Path(__file__).parent / "input.txt") as file:
floor =... |
48a7d98ef8acfdd3fc5c7ace832810e2fe3c6092 | rbusquet/advent-of-code | /aoc_2020/day3.py | 771 | 3.65625 | 4 | from functools import reduce
from itertools import count
from operator import mul
from typing import Iterator
def read_file() -> Iterator[str]:
with open("./input.txt") as f:
yield from f.readlines()
def count_trees(right: int, down: int) -> int:
counter = count(step=right)
total_trees = 0
f... |
9abc4c7c745318043728354a75b0e6cc58e532e7 | rbusquet/advent-of-code | /aoc_2020/day24.py | 2,339 | 3.78125 | 4 | from collections import defaultdict
from dataclasses import dataclass
@dataclass
class Cube:
x: int
y: int
z: int
def __add__(self, cube: "Cube") -> "Cube":
return Cube(self.x + cube.x, self.y + cube.y, self.z + cube.z)
@classmethod
def new(cls) -> "Cube":
return Cube(0, 0, 0... |
bedc3696e18c0810fffc6e0095d884de1c42b970 | rbusquet/advent-of-code | /aoc_2020/day17.py | 1,673 | 3.578125 | 4 | from collections import defaultdict
from itertools import product
initial = """
####.#..
.......#
#..#####
.....##.
##...###
#..#.#.#
.##...#.
#...##..
""".strip()
def neighborhood(*position: int):
for diff in product([-1, 0, 1], repeat=len(position)):
neighbor = tuple(pos + diff[i] for i, pos in enumera... |
dbcf6b5acffdf9a54c1a18efc214dcaed6bae1c7 | HanniSYC/Practice_code | /二维数组中的查找练习.py | 1,405 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/11/3 下午9:38
# @Author : Hanni
# @Fun : 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
# 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
print '欢迎来到二维数组中的查找v1.0 @星辰\n'
class Solution:
def Find(self, target, array):
rowcount = len(array)... |
98144aeef549d072b82e1ec8b6fe04b231c4016d | rollingonroad/Python005-01 | /week06/assignment.py | 1,777 | 3.984375 | 4 | from abc import ABCMeta, abstractmethod
# 动物
class Animal(metaclass=ABCMeta):
def __init__(self, food_type, body_size, character):
self.food_type = food_type
self.body_size = body_size
self.character = character
@property
def is_fierce(self):
return self.body_size != '小' ... |
fc9366b9c351ebcc8ee1408a82cbb2a051785b40 | schardt8237/Codecademy | /Data Science Career Path/Unit 14: Learn Statistics With Python/life_expectancy_by_country.py | 840 | 3.75 | 4 | import codecademylib3_seaborn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("country_data.csv")
#print(data.head())
life_expectancy = data["Life Expectancy"]
life_expectancy_quartiles = np.quantile(life_expectancy, [0.25, 0.5, 0.75])
print(life_expectancy_quartiles)... |
e1ecce71b4e466e4028e2528e627a61486137ee5 | IzMasters/timefuzz | /timefuzz.py | 3,720 | 3.546875 | 4 | class Namespace:
def __init__(self, **names):
for name in names.keys():
setattr(self, name, names[name])
# helper class for "speaking" units..
# singular and plural are the respective forms, plural defaults to a regular "s"-plural
# vowel_onset determines whether or not to use "an" for the indefinite article
cla... |
7c7e46570e38bc54ba1c1fabd9c11de78f8f27b9 | CharlieGodfrey1/Python-practice | /divisors practice.py | 409 | 4 | 4 | #user enters number
num=int(input("Please enter a number: "))
#works out the intigers from 1 to the entered number
listrange = list(range(1,num+1))
#list of divisors
divisors = []
#for loop to work out divisors
for i in listrange:
#divides the entered number by the list range integers and if they have a modula... |
cb69532884a199d684d49739f1bc17e3076600a8 | calcsam/toyprojects | /socialwire_example.py | 3,142 | 3.65625 | 4 | # in response to http://www.socialwire.com/exercise1.html; took me about 2 hours to code
# python 2.7
def test(aString):
stillNumber = True
expectedExpressions = 0
allExp = []
currentExp = []
for char in aString:
#print "iterate" + char
if is_number(char) and stillNumber:
expectedExpressions = expectedExp... |
63825db8fd9cd5e9e6aaa551ef7bfec29713a925 | Rohit439/pythonLab-file | /lab 9 .py | 1,686 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### q1
# In[2]:
class Triangle:
def _init_(self):
self.a=0
self.b=0
self.c=0
def create_triangle(self):
self.a=int(input("enter the first side"))
self.b=int(input("enter the second side"))
self.c=int(input("e... |
100419d5cdb569188d4c1231a7e603bc6c16353b | racheltsitomeneas/python_homework | /Python Homework/PyBank/Analysis/PyBank.py | 1,915 | 3.84375 | 4 | #pybank homework
import os
import csv
#variables
months = []
profit_loss_changes = []
count_months = 0
net_profit_loss = 0
previous_month_profit_loss = 0
current_month_profit_loss = 0
profit_loss_change = 0
os.chdir(os.path.dirname(__file__))
budget_data_csv_path = os.path.join("budget_data.csv")
... |
b3717109102391a9eed15d86869e05c0866d6c29 | MusawerAli/python_practise | /nesteddict.py | 512 | 3.84375 | 4 | #nested dictionary
parent_child = {
"child1": {
"name": "jorg",
"age": 22
},
"child": {
"name": "bush",
"age": 30
}
}
parent_brother = {
"brother1": {
"name": "jonze",
"age": 43
},
"brother2": {
"name": "bus",
"age": 65
... |
34c328e731795ee17c1e887a966c33a6bf2ca327 | MusawerAli/python_practise | /regex/regex.py | 125 | 3.890625 | 4 | import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
print("Have a match") if (x) else print("no match") |
644dd04680b280b1def7e3d5023e2dfa0a253161 | MusawerAli/python_practise | /regex/endwithword.py | 182 | 4.59375 | 5 | import re
str = "hello world"
#Check if the string ends with 'world':
x = re.findall("world$", str)
if (x):
print("Yes, the string ends with 'world'")
else:
print("No match")
|
ea81873f62f22fb784403d68c7c443a4b3749a40 | MusawerAli/python_practise | /if_else.py | 501 | 3.890625 | 4 | a = 50
b =20
c = 54
d=50
if b > a:
print("b is greater than b")
elif c>a:
print("c is grater than a")
else:
print("a is grater than b")
#Short Hand if...Else
print("A") if a > b else print("B")
#print Multiple
print("A") if a< d else print("=") if a == d else print("B")
if a>b and d>b:
print("Bo... |
80656a2831924d203537b5788143bf03e149dd7d | lalitasharma04/Computer_Networks | /source codes/Bit_Stuffing_and_character_stuffing.py | 4,154 | 3.984375 | 4 | '''
==============================================================================
Name :Lalita Sharma
RNo :06
===============================================================================
Experiment :02
***************
Aim:W... |
63e1f1008273f5dcd65fd12e22b47886a6be3bec | lautaroGonzalez97/practica2 | /ejercicio3.py | 262 | 3.796875 | 4 | texto="Tres tristes tigres, tragaban trigo en un trigal, en tres tristes trastos, tragaban trigo tres tristes tigres."
letra = input("ingrese una letra")
lista= texto.lower().replace(",","").split()
for ele in lista:
if ele[0] == letra:
print(ele) |
332b831f3602141a6dac113e04bf7caee197b9ce | bartkim0426/algorithm-study | /questions/leetcode_199.py | 7,815 | 4.03125 | 4 | # https://leetcode.com/problems/binary-tree-right-side-view/
# 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
'''
TreeNode{
val:1,
left: TreeNode{
val: 2... |
6cca9c50b24c23b7b0f45721b84cb06646185442 | brpasiliao/Girls_Who_Code_Projects | /commute.py | 1,814 | 3.953125 | 4 | qhome = "walk or drive: "
qwalk = "bus or lirr: "
qlirr = "subway or speedwalk: "
qdrive1 = "lirr or drive: "
qdrive2 = "bridge or tunnel: "
# def plurality()
# if plural == True:
# word += "s"
# else:
# None
def end(time, money):
hours = time // 60
minutes = time - hours * 60
if ... |
6558d052e684878a271533df745aa0aaf398d710 | apollo-chiu/password-retry | /pssw-try3.py | 267 | 3.84375 | 4 | key = 'a123456'
x = 3
while x > 0:
x = x - 1
psw = input('請輸入密碼: ')
if psw == key:
print('登入成功!')
break
else:
print('密碼錯誤!')
if x > 0:
print('還有', x, '次機會')
else:
print('沒機會嘗試了! 要鎖帳號了啦!') |
a9540bff47bfe8f9939f81c00fefa3348e91675c | tianshuaifei/kaggle | /feature.py | 1,222 | 3.890625 | 4 | import numpy as np
#类别变量处理 treat categorical features as numerical ones
#1 labelencode
#2 frequency encoding
#3 mean-target encoding
#https://www.kaggle.com/c/petfinder-adoption-prediction/discussion/79981
# Mean-target encoding is a popular technique to treat categorical features as numerical ones.
# The mean-target... |
69b848ed2eeae8f3090a9c35b2cdf12bc4dd29e5 | Rita626/HK | /Leetcode/237_刪除鏈表中的節點_05170229.py | 1,671 | 4.21875 | 4 | #題目:请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, ... |
4e485050a23b744142df8dc609002818dd9044c9 | Eduardo-Chavez/Unidad2Evaluacio-n | /Iniciales_login.py | 194 | 3.9375 | 4 | usuario = input ("Ingresa tu usuario: ")
contra = input ("Ingesa tu contraseña: ")
if usuario == "utng" and contra == "mexico":
print ("Bienvenido")
else:
print ("Datos incorrectos")
|
2991c345efe646cedda8aeaeeebe06b2a4cc6842 | drmason13/euler-dream-team | /euler1.py | 778 | 4.34375 | 4 | def main():
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
test()
print(do_the_thing(1000))
def do_the_thing(target):
numbers = range(1, target)
answer =... |
0c9c7fbf5ea0ed3591fd4aee2c9ac9de4b2392a6 | paulbradshaw/scrapers | /festivaltweetsjson.py | 1,713 | 3.65625 | 4 | #!/usr/bin/env python
import json
import csv
import requests
import urllib
import scraperwiki
jsonurlgh = 'https://raw.githubusercontent.com/paulbradshaw/scraping-for-everyone/gh-pages/webpages/cheltenhamjazz-export.json'
jsonurl = 'https://paulbradshaw.github.io/scraping-for-everyone/webpages/cheltenhamjazz-export.j... |
1ce80703b6e762b4913a7c906fc23143363e2bae | paulbradshaw/scrapers | /westminstercouncilevents.py | 1,660 | 3.578125 | 4 | #!/usr/bin/env python
import scraperwiki
import urlparse
import lxml.html
import urllib2
import datetime
#more on datetime here: https://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/
now = datetime.datetime.now()
currentmonth = now.month
currentyear = now.year
currentday = now.day
print str(n... |
01c12a1ab03ab87a404dbd42b9a755be0ed03173 | maymashd/BFDjango | /week 1/Informatics mcc/Cycle While/D.py | 151 | 3.5625 | 4 | import math
n=int(input())
i=1
ok=False
while i<=n:
if i==n:
ok=True
i=i*2
if (ok==True):
print("YES")
else:
print ("NO")
|
e2e7128884e11dbc5dba935b8986c987663633db | maymashd/BFDjango | /week 1/Informatics mcc/Array/B.py | 140 | 3.609375 | 4 | import array
n=int(input())
a=input()
arr=a.split(" ")
for i in range(0,len(arr)):
if (int(arr[i])%2==0):
print(arr[i],end=' ') |
5ff1f253950b663e79b8d4450e458aa43937d802 | maymashd/BFDjango | /week 1/Informatics mcc/Cycle For/K.py | 105 | 3.5 | 4 | import math
cnt=0
n=int(input())
for i in range(1,n+1):
a=int(input())
cnt=cnt+a
print(cnt)
|
27662057212e19516566758c0cdde3eb883a90a2 | valeriuursache/scratchpad | /module 3/cat_strings.py | 637 | 3.71875 | 4 | if __name__ == "__main__":
#Concatenation
#You can concatenate two strings together using +
leia = "I love you."
han = "I know."
print(leia + ' ' + han)
ship = "Millinium Falcon"
# Python starts at 0, slices TO the end index (not included)
print("'" + ship[10:] + "'")
bold_state... |
6f1aa43d0614cd211b0c92a48b182cf662e230fa | nmaswood/Random-Walk-Through-Computer-Science | /lessons/day4/exercises.py | 720 | 4.25 | 4 | def fib_recursion(n):
"""
return the nth element in the fibonacci sequence using recursion
"""
return 0
def fib_not_recursion(n):
"""
return the nth element in the fibonacci sequence using not recursion
"""
return 0
def sequence_1(n):
"""
return the nth element in the sequ... |
5f31e4cdf81801c19d737535ca94fb49ceab59fb | dangriffin13/Project_Euler | /euler21_amicable_numbers.py | 662 | 3.578125 | 4 | import math
t = int(input())
def sum_of_divisors(number):
s = 0
stop = int(math.floor(math.sqrt(number)))
for i in range(2,stop):
if number%i == 0:
s += i + number/i
return int(s+1)
amicable_numbers = []
for i in range(100001):
y = sum_of_divisors(i)
if sum_of_diviso... |
cd4d8070eeaa1eff50473cb6d89f3cedbf973b66 | LawlessJ/Object_Oriented_Programming_Project | /Script.py | 2,987 | 3.703125 | 4 | from datetime import datetime
class Menu:
def __init__(self, name, items, start_time, end_time):
self.name = name
self.items = items
self.start_time = datetime.strptime(start_time, "%I %p")
self.end_time = datetime.strptime(end_time, "%I %p")
self.times = [self.start_time, self.end_time]
def... |
51ed6228cc6ff33b400a250782b2b0d9b16daf09 | RohilH/Convolutional-Neural-Network-using-TensorFlow | /cnnTensorFlow.py | 2,468 | 3.515625 | 4 | from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.utils import to_categorical
import numpy as np
# (X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = np.load("data/x_train.npy")
X_trai... |
bed140408d860cdaa01ba616ac984a3beb4029ae | benoitantelme/python_ds_ml_bootcamp | /05-Data-Visualization-with-Matplotlib/02-Matplotlib Exercises.py | 3,412 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# ___
#
# <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
# ___
# # Matplotlib Exercises
#
# Welcome to the exercises for reviewing matplotlib! Take your time with these, Matplotlib can be tricky to understand at first. These are relatively simp... |
d460b9928fa6276cd94ab510d3c24b7aa8932a34 | shanefay/MachineLearning | /assignment2/estimate_scorer.py | 2,528 | 3.515625 | 4 | from sklearn.metrics import make_scorer
from sklearn.model_selection import train_test_split, cross_validate
def split_estimate(estimator, X, y, metrics, test_size=0.3):
"""Score an estimated model using a simple data split.
A 70/30 split of training to testing data is used by default.
Args:
esti... |
4d0f3b2e8eb544407de5ed9cd04ef2347628ff19 | Inlinesoft/POC.ECS.Python.App | /utilities/email.py | 2,975 | 3.59375 | 4 | import smtplib
import definitions
class Email:
"""
Send out emails (with or without attachments) using this class.
Usage:
With attachment
email = Email(server_name)
email.send_mail(send_from, send_to, subject, text, files)
Without attachment
email = Email()
email.send_mail(send_fr... |
2512b1f39ae0d570fae3dda36f2950254a085549 | jfernand196/Ejercicios-Python | /funcion_all.py | 146 | 3.71875 | 4 | # verificarf que todos los items iteravles cumplan una condicion
lista = [2, 4, 6, 7]
print(all(x > 4 for x in lista))
h = "juan"
print(type(h)) |
60dab56c8c06bc13f3c182ec1dbb11832298c6d2 | jfernand196/Ejercicios-Python | /farmeteos de string y float.py | 190 | 3.734375 | 4 | palabra = "!aprendiendo python!"
print("%.6s" % palabra)
print("%.12s" % palabra)
real = 2.6578
print("valor es: %f" % real)
print("valor es: %.2f" % real)
print("valor es: %.13f" % real) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.