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 |
|---|---|---|---|---|---|---|
d3aaa4d69f605f2b613c7004be9e9a958573eed6 | Otemory/stepik-python-course | /while_task1.py | 513 | 4.03125 | 4 | """
Напишите программу, которая считывает со стандартного ввода целые числа, по одному числу в строке,
и после первого введенного нуля выводит сумму полученных на вход чисел.
"""
a = int(input())
mass = []
while a != 0:
mass.append(a)
a = int(input())
print(sum(mass))
###
a = int(input())
summa = 0
while a != 0... |
3b7ec94545d7c15d8bf98d174a299a52a31463c8 | Otemory/stepik-python-course | /area_calc.py | 689 | 3.84375 | 4 | figure_name = input()
if figure_name == "треугольник":
a, b, c = float(input()), float(input()), float(input())
if a > 0 and b > 0 and c > 0:
p = (a + b + c) / 2
s = (p * (p - a) * (p - b) * (p - c)) ** 0.5
# print(float(s))
else:
print("Wrong")
elif figure_name == "прямоугол... |
a107c3834adc8198e06f4186af08bb0e8af1b3f7 | monirach/tic-tac-toe-game | /MonicaCruthird Coding Challenge.py | 2,437 | 3.921875 | 4 | #import library
from tkinter import *
import random
#initialize window
root = Tk()
root.geometry('400x400')
root.resizable(0,0)
root.title('DataFlair-Rock,Paper,Scissors')
root.config(bg ='seashell3')
#heading
Label(root, text = 'Rock, Paper ,Scissors' , font='arial 20 bold', bg = 'seashell2').pack()
... |
ed87c9d8dd85f9a3f838938bdab13bef6c14edad | KsenijaM/sympy | /sympy/tensor/tensor_fields.py | 20,858 | 3.65625 | 4 | #-*- coding: utf-8 -*-
"""
Module tensor_fields contains functions for working with the tensor fields:
calculation of the differential and the gradient of the function,
curl and divergence of a vector field,
the calculation of the Li derivative and the external differentiation of differential forms.
Functions are w... |
0be7492d19c18661ff19071171e23d3222105c82 | MolarFox/PythonPractice | /password_gen/pass_gen.py | 4,746 | 3.640625 | 4 | # A password generator - OOP approach
# MolarFox 2021
import sys
import random
# Defines ascii character ranges as nested tuples
CHAR_RANGES = (
(65, 90), # uppercase alphas
(97, 122), # lowercase alphas
(48, 57), # numbers
(58, 64) # symbols only some, for simplicity
)
class PassGen:
"""... |
1d3f9dfe02defa4bdfbdc585a44675ea9ebf7564 | ZhanlinWang/hpc_work | /lec3/sqrtx.py | 542 | 3.78125 | 4 | #!/bin/python
'''
Module for approximating sqrt.
More ...
'''
'Why not come here'
x = 100.
def sqrt2(x):
'''
more details
'''
from numpy import nan
if x==0:
return 0.
elif x<0:
print "*** Error, x must be nonnegative."
return nan
assert x>0. and type(x) is float, "Unrecognized input"
s = 1.
kmax = 100
... |
a2dbeaa008f0421d645babd5bc9d147ce264586b | Marlon97/Curso_python_u | /seccion10_listas/listas.py | 133 | 3.890625 | 4 | l1 = [1,2,3,4,5]
l2 = list(range(6,11))
print(f"lista 1 : {l1}")
print(f"lista 2 : {l2}")
l1.extend(l2)
print(f"lista 1 final: {l1}") |
f3c0af726b3fe9fefea8a503c16e3179e19e73df | MelJack1966/improved-engine | /lab 5.py | 582 | 4.0625 | 4 | def kinetic_energy(mass,velocity):
return 0.5 * mass * velocity**2
def main():
activate = input('Do you wish to calulate mass and velocity to kinetic energy? Enter yes or no: ')
while activate == 'yes':
mass = float(input('Enter the mass of the object: '))
velocity = float(input('Ent... |
27854acb2547caf5ae7a5c30c864d276a1573883 | AGrosserHH/Neural_Network_Base | /hiddenlayer.py | 3,012 | 3.6875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 6 18:16:07 2016
@author: Andi
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 1 19:58:14 2016
@author: Andi
"""
from neuron import Neuron
class HiddenLayer():
def __init__(self):
self.__listOfNeurons=[]
self.... |
835620805720fc0049feea6df4222ecc1f829bef | Rushikeshh-patil/ProjectEuler | /pandigital_number.py | 472 | 3.734375 | 4 | def check_prime(num):
if num > 1:
for i in range(2,num//2):
if num % i == 0:
return False
return True
else:
return True
def check_pandigital(num,s):
n=str(num)
len(n)==s
master_numbers = '1234567890'
return not (master_numbers[:s]).strip(n)... |
3b6503176ffff2b9386a50038922d4ca244cb35b | garciaae/median50 | /timefunctions/timefunctions.py | 404 | 3.984375 | 4 | """Contains functions for checking computing times"""
import time
def chronometer(funcion):
"""Counts how long does it take to compute a function"""
def function_to_run(*args):
"""Inner function"""
start_time = time.time()
funcion(*args)
end_time = time.time()
time_ela... |
4fc40f1064a92dd699856a796a18dd7167e3be42 | GerhardKling/SimplePyGame | /wall.py | 572 | 3.6875 | 4 | """Builds Wall class"""
import pygame as py
class Wall(py.sprite.Sprite):
def __init__(self, x, y, width, height, color):
"""Construction of wall"""
# Call constructor from superclass
super().__init__()
# Make a BLUE wall, of the size specified in the parameters
... |
6789ae8138e4fb95bb2dfa3bb237f94f992f3576 | rohansmike/Testing | /QUESTION.py | 395 | 3.984375 | 4 | inp=0
wish='B'
product=1
sum=0
while wish!='q':
wish=input("enter q to quit or any other key to continue>>")
if wish=='q':
break
else:
inp=int(input("enter value"))
if inp%2==0:
sum=sum+inp
else:
product=product*inp
print("the sum of even... |
c5ac548c3ba202860c4604dca50f300137217dca | YoungKwong/python_learning | /lxf_python/lxf_4_3_python1.py | 468 | 3.75 | 4 | print('计算去年到今年你成绩提升 or 下降的百分点')
name = input('请输入你的名字:')
s1 = float(input('请输入你去年的成绩:'))
s2 = float(input('请输入你今年年的成绩:'))
if s2>s1:
r = (s2-s1)/s1 *100
print('Hi! %s, 你成绩提升了%.1f %%' % (name, r))
elif s2<s1:
r = (s1-s2)/s1 *100
print('Hi! %s, 你成绩下降了%.1f %%' % (name, r))
else:
print('Hi! %s, 你的成绩没有... |
ee02488082f6aca754c159448ed6bf880a93b3e9 | MamounMohamed/Assignment-2-CloudComputing | /srcPro.py | 361 | 3.5 | 4 | first = set()
second = set()
with open("Beyondsleep.txt",encoding = 'utf-8') as file:
for line in file:
for word in line.split():
first.add(word)
with open("pride&prejudice.txt",encoding = 'utf-8') as f:
for l in f:
for w in l.split():
second.add(w)
for w in fir... |
0f05cfa31bf3ef2f9d28e65b2fa7c1167a2864cf | ajaykumar-bollepalli/AdvancedPythonWS | /MyModules/contacts.py | 910 | 3.671875 | 4 | import re
def isValidName(name):
pattern = '^[A-Za-z\s]*'
if re.search(pattern,name):
return True
return False
def isValidMobile(mno):
pattern = '^[6-9]\d{9}$'
if re.search(pattern, mno):
return True
return False
path = "MyFiles/contact.txt"
def createContact(name, contact):... |
0548fe77199eba5898a4cb343fba6b2af608770f | arunsub94/ShowMeTheDataStructures | /Project2_Udacity/problem_1.py | 4,789 | 3.6875 | 4 | # LRU CACHE IMPLEMENTATION
class Node:
def __init__(self, value, key):
self.value = value
self.key = key
self.next = None
self.previous = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value, key):
#... |
af8fa552a59ad87335869e8f33fb5bad7686824d | 0p3r4t0r/KGI-STEAM | /kgisteam/courses/maths.py | 1,364 | 4 | 4 | from math import sin as sin_rads
from math import cos as cos_rads
from math import tan as tan_rads
# BEGIN funcitons that can be used in the forms.
from math import radians, sqrt
def sin(theta):
return sin_rads(radians(theta))
def cos(theta):
return cos_rads(radians(theta))
def tan(theta):
return tan_r... |
ef542374f5ff30ec565deca0fc34b45606b8b1ad | C-CCM-TC1028-102-2113/tarea-4-SamyEa12 | /assignments/10.1AlternaCaracteresContador/src/exercise.py | 262 | 3.84375 | 4 | def main():
#escribe tu código abajo de esta línea
n=int(input())
for i in range(1, n+1):
if i%2==0:
x="%"
elif i%2!=0:
x="#"
print(str(i)+"-"+str(x))
pass
if __name__=='__main__':
main()
|
56987b36b796816bbf61315b11be60fc6bed2aee | ljkhpiou/test_2 | /ee202/draw.py | 642 | 4.1875 | 4 | import turtle
myPen = turtle.Turtle()
myPen.shape("arrow")
myPen.color("red")
#myPen.delay(5) #Set the speed of the turtle
#A Procedue to draw any regular polygon with 3 or more sides.
def drawPolygon(numberOfsides):
exteriorAngle=360/numberOfsides
length=2400/numberOfsides
myPen.penup()
m... |
728316a3e4a51e7dee92b550f69f0e30427939d0 | Ivaylo-Kirov/PTtdd | /tests.py | 987 | 3.828125 | 4 | import unittest
from functions import sum, subtract, find_matching_substrings
class TestFunctions(unittest.TestCase):
def test_ints(self):
self.assertEqual(sum(2, 2), 4)
def test_doubles(self):
self.assertEqual(sum(1.4, 2.2), 3.6)
def test_subtract_ints(self):
self.assertEqual(sub... |
0f7fd4ba5c597c0ef2882d0d1f6027b6f1eff183 | Maximilean/Final_project | /Project/project_calc_demo,py.py | 1,091 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from math import *
# Вычисление многочлена Тейлора
f = input('f(u) = ')
u0 = float(input('u0 = '))
u = sp.Symbol('u')
n = int(input('n = '))
u1 = float(input('Введите левую границу - '))
u2 = float(input('Введите правую границу - '))
z=0
g=0
p=1
dig... |
01888447331e3dec3551590cef7c624d250d59a2 | paddyamey/Games | /CountingTo21/game.py | 5,836 | 4.03125 | 4 | import random
def check_factor(number, factor):
"""
:param number: integer
:param factor: integer
:return: boolean
"""
if number % factor == 0:
return True
else:
return False
def closest_multiple(number, number_m):
"""
:param number: integer
:param number_m: i... |
0cdc38ee8630c529d682d743be69549325d5d077 | pondycrane/algorithms | /om_api/file_system/file_system.py | 3,559 | 3.5 | 4 | import abc
import typing
import unittest
class NodeInterface(abc.ABC):
def __init__(self, name, permission):
self.name = name
self.permission = permission
self.children = []
self.data = None
def accept(self, visitor, *args, **kwargs):
"""
To get subdirectory or ... |
16f6c2882e5ed8316b9a645377825f43378d38fb | pondycrane/algorithms | /python/tree/diameter_of_binary_tree.py | 1,115 | 4.0625 | 4 | import collections
import typing
import base.solution
import lib.ds_collections.treenode as treenode
class Solution(base.solution.Solution):
def diameter_of_binary_tree(self, root: typing.List[int]) -> bool:
root = treenode.TreeNode.deserialize(root)
if not root: return 0
best = 0
... |
778a75b990b5458a60eb64691b837c59d5803901 | pondycrane/algorithms | /python/topsort/course_schedule.py | 1,852 | 3.53125 | 4 | import collections
from typing import List
import base.solution
class GNode:
def __init__(self, val):
self.val = val
self.incoming_count = 0
self.children = []
"""
You are given a list of course dependencies, find the courses need to take.
Input: list of dependences. [a, b] means class a ... |
0ab438f6325289a505d4b94278e4bcc193a8f450 | pondycrane/algorithms | /python/tree/lowest_common_ancestor_of_a_binary_tree.py | 1,786 | 3.953125 | 4 | from typing import List
import base.solution
from lib.ds_collections.treenode import TreeNode
class Solution(base.solution.Solution):
def lowest_common_ancestor_of_a_binary_tree(self, root: List[int], p: int, q: int) -> TreeNode:
root = TreeNode.deserialize(root)
def find_node(node, num):
... |
34e9d1771fedd300ffc21fbac51db72647063b55 | pondycrane/algorithms | /python/tree/recover_binary_search_tree.py | 1,488 | 3.828125 | 4 | import collections
import itertools
from typing import List
import base.solution
from lib.ds_collections.treenode import TreeNode
class Solution(base.solution.Solution):
def recover_binary_search_tree(self, root: List[int]) -> TreeNode:
root = TreeNode.deserialize(root)
"""
Record... |
66d1d1564fc2c15163fc70f1997206ca7e730185 | pondycrane/algorithms | /python/array/group_anagrams.py | 1,037 | 3.78125 | 4 | import collections
import typing
import base.solution
class Solution(base.solution.Solution):
def group_anagrams(self, strs: typing.List[str]) -> typing.List[typing.List[str]]:
res = collections.defaultdict(list)
for word in strs:
res[''.join(sorted(word))].append(word)
... |
2b8fd64b7d9d7acb168de5827a1c7292a66a6eda | pondycrane/algorithms | /python/dp/optimization/best_production_plan.py | 866 | 3.59375 | 4 | import collections
from typing import List
import base.solution
class Solution(base.solution.Solution):
"""
T: O(N)
S: O(N)
"""
def best_production_plan(self, forecast: List[List[int]]) -> int:
# Overriding the input values are frawned upon
a = forecast[0][:]
b = forecast[... |
0b57619f0973cc13ecf7bdaa9651429d8b773ea5 | pondycrane/algorithms | /python/tree/preorder/split_bst.py | 2,025 | 3.796875 | 4 | import collections
from typing import List
import base.solution
from lib.ds_collections.treenode import TreeNode
class Solution(base.solution.Solution):
def split_bst(self, root: List[int], V: int) -> List[List[int]]:
root = TreeNode.deserialize(root)
def preorder(node):
if no... |
53394cf19e2e19c432aee5068b6a973f64b204fa | pondycrane/algorithms | /python/tree/binary_tree_level_order_traversal.py | 1,630 | 3.8125 | 4 | import collections
import typing
import base.solution
from lib.ds_collections.treenode import TreeNode
class Solution(base.solution.Solution):
"""
My solution
"""
def binary_tree_level_order_traversal(self, root: typing.List[int]) -> TreeNode:
root = TreeNode.deserialize(root)
if root ... |
56c2def7eaa5fa327e1f69ce6d8fe7284c5ae71e | pondycrane/algorithms | /python/dfs/binary_tree_traversal.py | 1,989 | 3.734375 | 4 | import collections
import base.solution
import lib.ds_collections.treenode as treenode
class Solution(base.solution.Solution):
def binary_tree_traversal(self, arr: list) -> None:
root = treenode.TreeNode.deserialize(arr)
res = []
def dfs(node, index):
if not node:
... |
3b0221418f76acd7593b9d9b085b998e0616bf2a | pondycrane/algorithms | /python/tree/binary_tree_inorder_traversal.py | 1,549 | 3.796875 | 4 | import collections
import typing
import base.solution
from lib.ds_collections.treenode import TreeNode
class Solution(base.solution.Solution):
"""
Iterative
"""
def binary_tree_inorder_traversal(self, root: typing.List[int]) -> typing.List[int]:
root = TreeNode.deserialize(root)
s, t, ... |
42176e871d525a5a07a95823fbe958b49a1424ca | FALCON-084/test30 | /test30/get_text_format_in_pdf.py | 1,336 | 3.96875 | 4 | f =open('final_text_appended.txt','r')
text = raw_input('enter the text you want to know stats for:')
guesses = []
lines =[]
line = f.readline()
while(line!=''):
lines.append(line)
if(line.find(text)!=-1):
guesses.append(line)
line = f.readline()
if(len(guesses) ==0):
print("there are no guesses... |
d02a694bb4c4a4a9cb9924d86d793c56caf1b549 | jasrusable/APG4005F | /assignment_2/plot.py | 466 | 3.53125 | 4 | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def plot_list_of_points(list_of_points):
x, y, z = [], [], []
for point in list_of_points:
x.append(point.x)
y.append(point.y)
z.append(point.z)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')... |
ca71aaad0b160455a35ab27cdab204f6fe740f98 | CepheusSun/python | /DemoClass/han_nuo_ta_game.py | 382 | 3.890625 | 4 | # -- coding: UTF-8 --
from __future__ import print_function, division
def hanoi(n, a, b, c):
if n == 1:
print('Move', n, 'from', a, 'to', c)
else:
hanoi(n - 1, a, c, b)
print('Move', n, 'from', a, 'to', c)
hanoi(n - 1, b, a, c)
def main():
num = int(raw_input())
hano... |
9bc9f80d12eb6d2b244533b39bbe85c1ad765927 | CepheusSun/python | /DemoClass/what_is_the_last_day.py | 863 | 3.90625 | 4 | # -- coding: UTF-8 --
from __future__ import print_function, division
def count_day_of_month(year, month):
if month in (1, 3, 5, 7, 8, 10, 12):
return 31
elif month in (4, 6, 9, 11):
return 30
elif (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return 29
else:
... |
78d5544f2bebfef17632c677ae6400fcd4383a2b | ptgl/py-challenge | /prob3.py | 223 | 3.515625 | 4 | #!/usr/bin/python
# Open a file
import re
file = open("dataProb3.txt", "r+")
str = file.read();
print "demo"
print re.findall("[A-Za-z]", str)
print "--".join(re.findall("[A-Za-z]", str))
# Close opend file
file.close() |
b9f50aa0e85cbde0993b207f76a187ab7b06df6e | LizaMatyukhina/case_6 | /case6.py | 2,947 | 3.734375 | 4 | """Case-study #5 Tessellation
Developers:
Romanenko Alina(45%), Rashidova Aigerim(35%), Matyukhina Liza(40%)"""
from turtle import *
from ru_local import *
def get_num_hexagons():
""" Finding side length of hexagons. """
try:
n = int(input(NUMBER, ))
if 3 < n < 21:
d = 500 / n
... |
7d6db7421938167596b1f349a188861616cf2fa8 | sophieOEgriffith/code_in_place2020 | /Assignment1/TripleKarel.py | 885 | 3.90625 | 4 | from karel.stanfordkarel import *
"""
File: TripleKarel.py
--------------------
When you finish writing this file, TripleKarel should be
able to paint the exterior of three buildings in a given
world, as described in the Assignment 1 handout. You
should make sure that your program works for all of the
Triple sample w... |
55f207314404108cf6668f92ad01c0a6b46de023 | Kingslayer124856/Sandbox | /password_entry.py | 201 | 4.0625 | 4 | """Cassandra King"""
password = input("Password: ")
while len(password) <= 3:
print("Password should be longer then 3 characters.")
password = input("Password: ")
else:
print('*' * len(password)) |
8133725baf70305fdff8699d315a074e1f38d74c | xniu7/jhuclass.genome.project | /pdc3/merger.py | 1,460 | 3.828125 | 4 | from operator import itemgetter
# compare (a1,a2) with (b1,b2)
def leq(a1,a2,b1,b2):
return a1<b1 or ( a1==b1 and a2<=b2)
# compare (a1,a2,a3) with (b1,b2,b3)
def leq3(a1,a2,a3,b1,b2,b3):
return (a1<b1 or (a1==b1 and leq(a2,a3,b2,b3)))
# pop S, and get the last element of poped tuple
def pop(S):
s = S.pop(0... |
905d9ee2896acad5e335ba67bf7dc8c3126349e9 | aalbor/actipython | /agenda.py | 1,677 | 3.671875 | 4 | #!/usr/bin/env python
def agend():
var = []
var2 = ["Nombre:","Telefono:","Correo:"]
for l in range(3):
var.append(raw_input(var2[l]))
return var
def expxml(listado):
file = open("agenda.xml","w")
file.write("<?xml version='1.0' encoding='iso-8859-1'?>\n"... |
b58752c3157a7c7646604912727cd80874c439d7 | ms995/Python-for-Filmmakers | /bitwise/subtract.py | 632 | 3.71875 | 4 | # arithmetic operation of
# subtraction of pixels of two images
import cv2
import numpy as np
# path to input images are specified and
# images are loaded with imread command
image1 = cv2.imread('input1.jpg')
image2 = cv2.imread('input2.jpg')
# cv2.subtract is applied over the
# image inputs ... |
08435281ef189434c121be0f66540830b0e2f006 | NectariosK/email-sender | /email_sender.py | 2,438 | 4.375 | 4 | #This piece of code enables one to send emails with python
#Useful links below
'''
https://www.geeksforgeeks.org/simple-mail-transfer-protocol-smtp/
https://docs.python.org/3/library/email.html#module-email
https://docs.python.org/3/library/email.examples.html
'''
'''
import smtplib #simple mail transfe... |
499f115d74d2ac6e1537a59c1020d6e76758948f | kabilasudhannc/simple_higher_lower_game | /main.py | 1,688 | 3.734375 | 4 | from art import logo, vs
from game_data import data
import random
from replit import clear
score = 0
def calc_score():
global score
return score + 1
def format_questions(questions):
question_1 = f"Compare A: {questions['A']['name']}, a {questions['A']['description']}, from {questions['A']['country']}."... |
81dc52c40b9c0031c82b0876313801ad674c8cc2 | ililiiilil/Algorithms-Python- | /BaekJoon/BOJ2751-2.py | 742 | 3.828125 | 4 | import sys
arr = []
n = int(sys.stdin.readline())
for _ in range(n):
arr.append(int(sys.stdin.readline()))
def quick_sort(arr, start, end):
if start >= end:
return
pivot = start
left = start + 1
right = end
while left <= right:
while left <= end and arr[left] <= arr[... |
f2a825411a84cd4816ce234afde03b2059d09d91 | ililiiilil/Algorithms-Python- | /BaekJoon/BOJ10886.py | 216 | 3.515625 | 4 | n = int(input())
cnt = 0
for i in range(n):
a = int(input())
if a == 1:
cnt += 1
else:
cnt -= 1
if cnt > 0:
print("Junhee is cute!")
else:
print("Junhee is not cute!")
|
0289ac120e33944a3e480f186218335a6eb5fd62 | vspetrov/algo2 | /primm.py | 2,555 | 3.8125 | 4 | #!/usr/bin/python
class Edge:
"""The class describes an edge of a graph"""
global_counter = 0
max_cost=0
Vertices = []
def __init__(self, _vertices, _cost):
self.id = Edge.global_counter
Edge.global_counter += 1
self.my_vertices=_vertices
self.cost=_cost
def __st... |
35e912a1338ba19fff2180bd0e88403c7cc64452 | skycc86/google_foobar | /doomsday_fuel.py | 5,652 | 3.53125 | 4 | """
Doomsday Fuel
=============
Making fuel for the LAMBCHOP's reactor core is a tricky process because of the exotic matter involved. It starts as raw ore, then during processing, begins randomly changing between forms, eventually reaching a stable form. There may be multiple stable forms that a s... |
f69ea6b613ea76a1fb0a59212597c34e1c2bd05a | RoxannaW/Data-science-bootcamp | /Curso/Week_5/day1/theory/python/1_arg_parse.py | 912 | 3.859375 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-x", "--x", type=int, help="the base")
parser.add_argument("-y", "--y", type=int, help="the exponent")
parser.add_argument("-v", "--v", default=0, type=int, help="the result will be multiplied by 'v'")
args = vars(parser.parse_args())
def exponen... |
8d705f8c3f09cc9d23ea966fec7adf2613ad0132 | BrunoSDomingues/Renderizador | /parte1/functions.py | 1,719 | 3.71875 | 4 | # Implementação do Algoritmo de Bresenham disponível em http://www.roguebasin.com/index.php?title=Bresenham%27s_Line_Algorithm#Python (com modificações pontuais)
def get_line(x1, y1, x2, y2):
dx, dy = x2 - x1, y2 - y1
steep = abs(dy) > abs(dx) # Checa se a linha desenhada é íngreme
if steep: # Se a linha... |
2a97e8c7a58a3a748444edcc2ea33bc65b4bd4f7 | acmatku/ku-ipc-2016 | /02-Medium/Hydroelectric_Dams/Python/hydrotopia.py | 3,745 | 3.890625 | 4 | '''
ACM@KU Intramural Programming Competition 2016
Author: Stefan Mendoza
Problem: Medium - Hydroelectric Dams
'''
import sys
class Water():
def __init__(self, x, y):
self.row = x
self.column = y
"""
Determines whether water can move right through a generator
"""
def canBePumped(... |
644b66e70812f736de74552dd312e3eb604b12b0 | eliad1998/HandsonCryptography | /2_Break_ECB_CBC_PKCS7/aesoracles.py | 2,732 | 3.625 | 4 | from Crypto.Cipher import AES
# def padpkcs7(msg):
# """THIS IS A DUMMY FUNCION, you should implement padpcks7 in the exercise."""
# return "0123456789abcdef".encode('hex')
"""
:param an integer
@:returns ascii string represented by that integer
"""
def intToHexByte(x):
hexX = hex(x)
strHex = str(hex(x))[2:]... |
1393415fbd8121b3d79970bd4d477a4e96fc574b | ashawkey/naive | /naive/differentiation.py | 2,698 | 3.671875 | 4 | import numpy as np
from . constants import *
"""
This is bad. I use continuous function instead of discrete array to represent a function.
The differentiation cannot be automatically extended to high order. Have to hard-code the formula...
ref: https://en.wikipedia.org/wiki/Numerical_differentiation
"""
def diff_forw... |
4f7f57ae709bc63c3f679eb0cffbbb65c7847225 | raviMukti/training-python-basic | /src/WhileLoop.py | 86 | 3.609375 | 4 |
data = ""
while data != "x":
print("Masukan Data")
data = input("Input X :") |
e0d3302b71739f6e5210d6c0e377afe0ecb27329 | raviMukti/training-python-basic | /src/Dictionary.py | 290 | 4.3125 | 4 | customer = {"name":"Ravi", "umur":25, "pekerjaan":"Programmer"}
name = customer["name"]
age = customer["umur"]
job = customer["pekerjaan"]
print(f"Hello My Name is {name} i am {age} years old, and im a {job}")
for key in customer:
value = customer[key]
print(f"{key} : {value}") |
b72d9fb2b7c71a26dd497a6dfeeb9cfe40d1683e | raviMukti/training-python-basic | /src/ArgumentList.py | 417 | 3.703125 | 4 | def calculateNumber(*listNumber):
total = 0
for number in listNumber:
total += number
print(f"List {listNumber} - Hasil : {total}")
calculateNumber(10)
calculateNumber(10, 20)
def sayHelloAndCalculateNumber(name, *listNumber):
total = 0
for number in listNumber:
total += number
... |
30c86606a400fc76c0af74ebe64fa051b656e5bb | nikodemkowalski/Turtle_race | /main.py | 2,297 | 4.03125 | 4 | import turtle
from random import randrange
from time import sleep
turtles = 7
racers = []
class Racer(object):
def __init__(self, color, pos):
self.color = color
self.pos = pos
self.t = turtle.Turtle()
self.t.pensize(2)
self.t.turtlesize(1.5)
self.t.shape('turtle')
... |
b59026d78029f61462009ef68968572443d3b230 | felipe-menelau/triangle-challenge | /challenge/main.py | 521 | 3.6875 | 4 | def solve(triangle = []):
if not triangle:
raise RuntimeError('Should have a triangle')
bottom_up_navigation_range = reversed(range(len(triangle) - 1))
for i in bottom_up_navigation_range:
for j in range(len(triangle[i])):
triangle[i][j] += max(triangle[i + 1][j], triangle[i + ... |
463e8bb04c5728ff3b642fcb4d8e074ba5c06ad1 | jameshamm/lol-item-verifier | /lol_item_verifier/search/edit_distance_matching.py | 1,677 | 3.984375 | 4 | """Matches search terms based on how many characters need to be
modifed to change from one word to another
"""
def lev(a, b):
if len(a) < len(b):
return lev(b, a)
# len(a) >= len(b)
if len(b) == 0:
return len(a)
previous_row = range(len(b) + 1)
for i, c1 in enumerat... |
9df674cca8204c5a3bfca1a0f21452e86fc29f8e | dwbelliston/python_structures | /binary_tree/node.py | 933 | 4.03125 | 4 | #!/usr/bin/env python3
class BNode(object):
'''
binary tree node
'''
'''When the tree is modified (`set`, `remove`), be sure to update the
`parent`, `left`, and `right` references.'''
def __init__(self, key, value, parent=None, left=None, right=None):
'''A node in the BTree'''
... |
83f8ffda385cb89239279a207000f697a3312463 | dwbelliston/python_structures | /sorting_analytics/sorters/selection.py | 884 | 4.0625 | 4 | import operator
def selection_sort(list_data):
# Start at right, place at (n - i) eg: 9, 8, 7 etc..
# # end at -1 so it hits 0
for i in range(len(list_data) - 1, -1, -1):
# start with the place index (far right) as largest
largest_val_index = i
for j in range(0, i):
... |
8d64c60833a9b781e2b4e1243e1e987f08030c41 | dwbelliston/python_structures | /generators/example.py | 683 | 4.4375 | 4 | # Remember, an Iterable is just an object capable of returning its members one at a time.
# generators are used to generate a series of values
# yield is like the return of generator functions
# The only other thing yield does is save the "state" of a generator function
# A generator is just a special type of iterator... |
57e43e611cda66cae7d1ddadcae0a9663475e2db | BimuratMukhtar/IntroML | /Labs/Lab3/lab3.py | 1,337 | 3.921875 | 4 | import numpy as np
# Part 1 - Pegasos Algorithm
def pegasos(feature_matrix, labels, T=5, eta=0.1, lam=0.1):
"""Runs the pegasos algorithm on a given set of data.
Arguments:
feature_matrix(ndarray): A numpy matrix describing the given data.
Each row represents a single data point.
... |
659353987c09bd24b9695fb569593619c6d0add1 | KristineYW/DS-Unit-3-Sprint-2-SQL-and-Databases | /module1-introduction-to-sql/chinook_queries.py | 757 | 3.6875 | 4 | import os
import sqlite3
# construct a path to wherever your database exists
#DB_FILEPATH = "chinook.db"
DB_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "chinook.db")
connection = sqlite3.connect(DB_FILEPATH)
print("CONNECTION:", connection)
cursor = connection.cursor()
print("CURSOR", cursor)
query = "... |
f822f5ba42f9a020c5cb4571a6282716c4308864 | S1DAL3X/Python | /ROT47.py | 1,345 | 3.625 | 4 | #скрипт для шифрования и дешифровки текста алгоритмом ROT47
sub = list(' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-=_+[]{}/?\!@#$%^&*()~,.:')
result = []
def rot47_coder(text):
for label in text:
position = sub.index(label)
newPos = position + 13
if newPos > len(sub):
... |
76a06ca204f7c486c3e36716f0f88dd9129dd2cd | djiang-ucc/Criterion-c | /works.py | 4,473 | 3.515625 | 4 | from tkinter import *
from tkinter import ttk
import sqlite3
from PIL import ImageTk,Image
#Creates a window of a particular size
root = Tk()
root.title("Find a gas station near you")
root.geometry('800x650')
#Dropdown Box
def selected(event):
MyLabel = Label(root, text=clicked.get()).pack()
#East Toronto Ga... |
61745c15865ab7ea6d6f7b972a19beacc558a4ca | hunterkkx/Game_Lost_forest | /Scenes.py | 13,301 | 3.703125 | 4 | from random import randint
from sys import *
import sys
sys.path.insert(0,'/mystuff/LOSTFOREST')
from Battle_system import *
class Scene(object):
def __init__(self):
Scene.collection = []
def enter(self):
print "nothing happens here"
exit(1)
class Engine(object):
def __init__ (self,... |
24d69d7df270af8673070ef7079cbcd3254d9bd7 | valakkapeddi/enough_python | /comprehensions_and_generators.py | 1,353 | 4.6875 | 5 | # Comprehension syntax is a readable way of applying transforms to collection - i.e., creating new collections
# that are modified versions of the original. This doesn't change the original collection.
# For instance, given an original list like the below that contains both ints and strings:
a_list = [1, 2, 3, 4, 'a',... |
edafe52fecd74b9c3e4e58c15e53495fdc97ce4b | YannThorimbert/Thorpy | /examples/userchoices.py | 1,286 | 3.734375 | 4 | import thorpy
"""
In this example, a box opens in which the user can choose between turning the
background blue or red (or do nothing).
"""
def set_blue():
background.set_main_color((0,0,255))
background.unblit_and_reblit()
def set_red():
background.set_main_color((255,0,0))
background.unblit_and_rebl... |
e98c4474b18145207376b45123fc00c63e2461ec | YannThorimbert/Thorpy | /examples/advancedmenus.py | 2,976 | 3.625 | 4 | """Script showing several ways to launch things.
Note: never call set_launcher(launching, launched) if <launched> can be launched
by another element and <launching> is NOT in the same menu.
"""
import thorpy, pygame
application = thorpy.Application((500,500), "Advanced menus")
# ****************** First launcher : b... |
00e23232ce9ab79eea6b6c3b263aac13505c88d3 | r4hu1-s4hn1/passowrd_generator | /generator.py | 787 | 3.890625 | 4 | import random
from string import *
import os
# setting up charsets
lower=ascii_lowercase
upper=ascii_uppercase
numbers=digits
special_characters=punctuation
charset=[lower,upper,numbers,special_characters]
#users interaction
print("l -> for lowercase\nu -> for uppercase\nn -> for numbers\ns -> for special characters\... |
23d25bffa0606570c321b1a978058f7359f5597b | krishna-raj007/Voice-Based-Email | /Source/text_to_speech.py | 4,965 | 3.578125 | 4 | from gtts import gTTS
import speech_recognition as sr
import os
## @var srObj
# Speech recognition object to use its methods for reading input at microphone.
# \hideinitializer
#
srObj = sr.Recognizer()
##
# @brief Text to Speech
#
# @details the function converts text to voice.
#
# @param[in] text sentence to... |
6323f075e63578f6510ba88eb506a72d7892cf94 | JerzyBytniewski/Python-portfolio | /Portfolio 06 Multiple Choice Quiz.py | 1,156 | 3.8125 | 4 | from Question import Question
question_prompts = [
"Why can you do in Python?\n(a) Teach machines\n(b) Make a surgical intervention\n(c) Spagetthi\n\n",
"Why it is a pleasure to programing in Python?\n(a) Because you are a snake raiser\n(b) Because its logo is a masterpiece of graphic design\n(c) Because i... |
e745417e1c9749475e88e3c2fb0d76369bb0792c | mjrutherford-du/ducs-misty-ir-f2018 | /socketTypes.py | 2,811 | 3.578125 | 4 | import json
'''
These are mini classes for the structure of the return message from each socket type.
So can just put the response into the class and deal with it that way.
Not sure if we will want/need to utilize these but this is a more object oriented approach.
Also, each response has a type so could just p... |
861db59c044985dc0b8e4d71dbff92d480b40ef1 | Jones-Nick-93/Class-Work | /Binary Search Python.py | 1,284 | 4.25 | 4 | #Nick Jones
#DSC 430 Assignment 7 Time Complexity/Binary Search
#I have not given or received any unauthorized assistance on this assignment
#YouTube Link
import random
'''function to do a binary search to see if 2 #s from a given list sum to n'''
def binary_search(array, to_search, left, right):
# termina... |
813656fc229612e2b78fe9d611491bb3e18626cf | vishalkumarmg1/Competitive-Coding-4 | /Problem_2.py | 1,105 | 3.859375 | 4 | # 234. Palindrome Linked List
# code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
... |
e41b72f54d45718b0680fbbb7f61a3d0761f527f | Ameen-Samad/number_guesser | /number_ guesser.py | 1,426 | 4.15625 | 4 | import random
while True:
secret_number = random.randrange(1, 10, 1)
limit = 3
tries = 0
has_guessed_correctly = False
while not has_guessed_correctly:
user_guess = int(input("Guess a number: "))
print(f"You have guessed {user_guess}")
limit = limit - 1
tries = trie... |
9cf28b2c1a37f648cdbad456d0ee713b321ec676 | 27182818284590452/Python-Blockchain | /sha256.py | 213 | 3.515625 | 4 | # small script to the hashfunction used!
# import sha256
from hashlib import sha256
# text to hash
text = "This is the hashcode!"
hash_result = sha256(text.encode()).hexdigest()
# print result
print(hash_result) |
69a0998962bf5b24af2872af665f39be973998f2 | doubleo46/library | /functions/jsonDetails.py | 1,185 | 3.71875 | 4 | """
Program to identify the level of each key in a json
"""
import json
# Opening JSON file
f = open('data.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
json_details = {}
def getDetailJson(json_details, data,key, level):
print("key: ", ... |
8255151dcdd4845e1f96dcf07a250860d0341ecc | 1rick/julian_calendar | /julian-calendar.py | 775 | 4.0625 | 4 | #!/usr/local/bin/python3
"""convert gregorial calendar date to julian.
Following the formula given here: http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html.
Next to do is turn it into a Google date range search."""
from time import gmtime, strftime
searchterm = input("type search term: ")
d1 = input("type date 1... |
8e4a01561515f02d2cc7ef58cb7a38ce15bd5694 | VishnuMankar/rep1 | /Rock paper scissors.py | 1,414 | 4.09375 | 4 | user_name = input('Please enter your name : ')
print(f'Hey {user_name} welcome to the game')
user_score = 0
computer_score = 0
import random
plays = ['rock' , 'paper' , 'scissors']
keep_playing = True
while keep_playing == True :
c_plays = random.choice(plays)
user_plays = input('what is your move: rock , pa... |
307e85576dc78d29ecf9077c70776c3498e1a60c | LizaPersonal/personal_exercises | /Programiz/sumOfNaturalNumbers.py | 684 | 4.3125 | 4 | # Python program to find the sum of natural numbers up to n where n is provided by user
def loop_2_find_sum():
num = int(input("Enter a number: "))
if num < 0:
num = int(input("Enter a positive number"))
else:
sum = 0
# use while loop to iterate until zero
while num > 0:
... |
c2c6f67a9b28aed58419e949dd1071d714a4ec92 | LizaPersonal/personal_exercises | /Programiz/celsiusFahrenheit.py | 512 | 4.125 | 4 | def celsius2fahrenheit():
celsius = float(input("Enter value in celsius: "))
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius, fahrenheit))
def fahrenheit2celsius():
fahrenheit = float(input("Enter value in fahrenheit: "))
celsius = (fa... |
90c864f595292f9a93b8961f570155ce53ae0524 | EdwardDixon/floods | /floodstats.py | 712 | 3.890625 | 4 | #!/usr/bin/python
import pandas as pd
mydf = pd.read_csv('data/number-of-severe-floods-in.csv', names = ["Year", "Severity"], skiprows=1)
print("Dataframe content:")
print(mydf)
print("Select minimum value row:")
min = mydf['Severity'].min()
min_df = mydf.loc[mydf['Severity'] == min ]
print(min_df)
print("Select ... |
cb79398545b91a49f2985f907bec218b5d69e1bc | xndong1020/python3-deep-dive-01 | /8. Tuples as Data Structures and Named Tuples/01.tuple.py | 750 | 3.921875 | 4 | new_york = ("New York", "USA", "8,500,000")
print(type(new_york)) # <class 'tuple'>
# new_york[0] = 'Huston' # TypeError: 'tuple' object does not support item assignment
# actually tuple doesn't need brackets
new_york = "New York", "USA", "8,500,000"
city, country, population = new_york
print(city) # New York
prin... |
de9ffb959b1c8e0ff2c70f0577e1628d50d4dfb3 | ayyolmao/bf-interpreters | /brainfuck_starter.py | 2,074 | 3.78125 | 4 | import sys
# parse : String --> String List
# Returns parsed version of program from given file as a list of tokens.
# Whitespace and other characters in the file which are not brainfuck instructions are ignored.
# Raises a ValueError if the program is a malformed brainfuck program.
def parse(file_path):
def get_... |
2b6f8931fb9ff725617005620c05139321afe34b | vinodgawde/Book-store | /Book.py | 385 | 3.640625 | 4 | class Book:
def __init__(self,b_rno,b_name,b_details,b_auther,b_price):
self.book_rno=b_rno
self.book_name=b_name
self.book_details=b_details
self.book_auther=b_auther
self.book_price=b_price
def __str__(self):
return str(self.book_rno)+"\t"+self.book_name+"\t"+se... |
35ab0ae28ae798f5fd4317432d082e164b5815ef | zenthiccc/CS5-ELECTIVE | /coding-activities/2ndQ/2.5-recursive-binary-search.py | 1,311 | 4.15625 | 4 | # needle - the item to search for in the collection
# haystack - the collection of items
# NOTE: assume the haystack is ALWAYS sorted, no need to sort it yourself
# the binary search function to be exposed publicly
# returns the index if needle is found, returns None if not found
def binary_search(needle, haystack):
... |
62f3573ece7b3e41afd902cb9defede24cbb010b | y7cs228/NLP | /collocations.py | 1,391 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 19 20:43:29 2016
@author: Gopala Krishna
"""
#Importing Necessary Libraries
import string
import pandas as pd
#Function that cleans the given text
def preprocessing(text):
exclude = set(string.punctuation)
text = ''.join(ch for ch in text if ch not i... |
83d65c089070c6f21e96aa047a68e694a0690823 | guilhermeleobas/maratona | /leetcode/59.py | 936 | 3.53125 | 4 | class Solution:
def fill(self, matrix, N, begin, val):
# left-right
# [begin, N-begin)
for j in range(begin, N-begin):
matrix[begin][j] = val
val += 1
# up-down
# [begin, N-begin)
val -= 1
for i in range(begin, N-begin):
mat... |
f88096e5472da81bb73226fca45a5ae557e3c060 | guilhermeleobas/maratona | /leetcode/206.py | 453 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def apply(self, prev, curr):
if curr is None:
return prev
next_ = curr.next
curr.next = prev
return self.... |
b8978c8d742e28d901c4929e6bd3c87712256de2 | guilhermeleobas/maratona | /Codeforces/educational4/c.py | 977 | 3.84375 | 4 |
class stack:
def __init__ (self):
self.data = [];
def push (self, e):
return self.data.append (e);
def pop (self):
return self.data.pop();
def empty (self):
return len(self.data) == 0;
def top (self):
return self.data[len(self.data) - 1];
... |
40ee1218976d6a91edbe44364dafd2860e5f2263 | JohnsonLi/SoftDev2 | /22_/pie.py | 757 | 3.71875 | 4 | def inc(x):
return x + 1
f = inc
# print(f(10))
def adder(a, b):
return a + b
def caller(c):
print(c(2, 4))
print(c(3, 5))
# caller(adder)
def outer(x):
def contains(l):
return x in l
return contains
# contains_15 = outer(15)
# del outer
# print(contains_15([1,2,3,4,5]))
def repea... |
06abc2b9b6fe9c00603f4d2efdc9577312f24795 | ashu6711/Development | /Invoice_record.py | 4,755 | 3.875 | 4 | def invoice1():
#two list to store the name and quantity of the product bought by the customer
CART=[]
CART_QUANTITY=[]
#importing read_file having function read which returns the 2D list where the data of the inventory is stored and storing it in 'List'
import read_file
List=read_file.read()
... |
c5a7ac790a3fb07e4877843c769d4f4717972af0 | hyerynn0521/CodePath-SE101 | /Week 3/price_check.py | 812 | 3.875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'priceCheck' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING_ARRAY products
# 2. FLOAT_ARRAY productPrices
# 3. STRING_ARRAY productSold
# 4. FLOAT_... |
e3b267c428b62ae5e579a8d9b2446a85443ba889 | hyerynn0521/CodePath-SE101 | /Week 1/fizzbuzz.py | 683 | 4.46875 | 4 | #
# Complete the 'FizzBuzz' function below.
#
# This function takes in integer n as a parameter
# and prints out its value, fizz if n is divisible
# by 3, buzz if n divisible by 5, and fizzbuzz
# if n is divisible by 3 and 5.
#
"""
Given an input, print all numbers up to and including that input, unless they are divisi... |
52673f2e5435fb7d724b5028a3f64c61398d3c47 | hyerynn0521/CodePath-SE101 | /Week 5/longest_word.py | 816 | 4.4375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'longestWord' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING_ARRAY words as parameter.
# This function will go through an array of strings,
# identify the largest word, and retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.