blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0d692dcff6663286ed2d99cb8365bfb1f5c6bdc6 | bohdandrahan/Desing-patterns | /Composite.py | 1,339 | 3.703125 | 4 | #Composite design
class Component():
#Abstract class
def get_name(self):
return self.name
def get_price(self):
return self.price
def add_item(self, item):
pass
def remove_item(self, item):
pass
def print_price(self):
print("Price of " + str(self.get... |
1aab557606946286b65a4cd3a08bb28fa935882a | tommy-dk/projecteuler | /p53.py | 641 | 3.765625 | 4 | #!/usr/bin/env python
"""
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3 = 10.
"""
fact_c = { 0: 1, 1: 1 }
def factorial(n): return fact_c.has_key(n) and fact_c[n] or fact_c.setdefault(n, n * factoria... |
36f63b7813c0a2efc8d28082d87b1815875ed4c0 | tommy-dk/projecteuler | /p25.py | 439 | 3.734375 | 4 | #!/usr/bin/env python
import math
# See formulae here: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html?n=20
def getfibdigits(n):
phi = (1+math.sqrt(5))/2
return n * math.log10(phi) - math.log10(math.sqrt(5))
i = 1
while True:
if getfibdigits(i) >= 999:
print i
... |
8ac8d318abfb577f603b55d0d29faaf7a0ec4133 | tommy-dk/projecteuler | /p52.py | 624 | 3.765625 | 4 | #!/usr/bin/env python
"""
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
"""
import time
st = time.time()
def has_digits(n):
digit_keys = ... |
1e4e4b427aaca2e8f120cc5a621f170ff1f3468f | clebsonluiz/UAST-2020.1-REC-PAD | /game/model/entity/entity_animation.py | 5,155 | 3.984375 | 4 | from typing import List
from abc import ABC, abstractmethod
import pygame as pg
from .animation import Animation
class EntityAnimation(ABC):
"""
EntityAnimation Abstract Class
______________________________
Represents a animations of a entity in positioned at screen
Parameters
__________
... |
adf0513164654422955fe590c002c990476e4a9f | CiscoDevNet/netprog_basics | /programming_fundamentals/python_part_3/data_library_exercises.py | 1,867 | 3.671875 | 4 | #! /usr/bin/env python
"""
Learning Series: Network Programmability Basics
Module: Programming Fundamentals
Lesson: Python Part 3
Author: Hank Preston <hapresto@cisco.com>
data_library_exercises.py
Illustrate the following concepts:
- Commands from slides exploring data interactions
"""
# XML
print("Treat XML like ... |
ab7a7cd259c5c48ecaebb1b608d2728c2cb90801 | tusdasa/nhentai | /net/tusdasa/sp/SafeFileName.py | 2,492 | 4 | 4 | import os
#过滤不允许的字符
def safename(filename):
for i in range(len(filename)):
filename = filename.replace("/", "")
filename = filename.replace("\\", "")
filename = filename.replace(":", "")
filename = filename.replace("*", "")
filename = filename.replace("\"", "")
filena... |
f22a02151dfe5c36003059822d265f0696a0e7a3 | ettirapp/computational-topology | /Triangulation.py | 14,190 | 4.03125 | 4 | # Triangulation of a compact, connected 2-manifold without boundary
class Triangulation:
# a triangulation contains a list of vertices and a graph of triangles
def __init__(self):
# vertices are represented by characters and stored in a set
self.vertices = set()
# triangles are s... |
b8e08706a1d38ff34b31a774374a8a8f995aaa53 | omartrinidad/schiffsdiebe | /schiffsdiebe/instance_based/knn.py | 2,385 | 3.5 | 4 | from datasets import Examples
from utils import euclidean_distance
from collections import Counter
from scipy.spatial import distance
from sklearn.metrics.pairwise import pairwise_distances
import numpy as np
class kNN(object):
"""
Implementation of kNN algorithm
"""
def __init__(self, dataset):
... |
1387b65968c43dcfcc79c7966c1d9e8c54c9af32 | eads/exploreMapPy | /scriptCleanForContacts.py | 2,253 | 3.578125 | 4 | #!/usr/bin/env python
import xlrd # Library that processes excel files
import json # Library for processing / writing JSON
from slugify import slugify # Library to slugify strings
from pprint import pformat # Pretty print output
# File to be processed
IMPORT_FILE = 'ntpepData.xlsx'
OUTPUT_FILE = 'processe... |
48226fe4c0f69d50aae906205f3b9ee9eb8236ab | johnyeekim/codewars_python | /0003b Reversed Strings.py | 350 | 4.125 | 4 | ##Complete the solution so that it reverses the string passed into it.
##
##'world' => 'dlrow'
def solution(string):
# Pythonic way :)
return string[::-1]
# For beginners it's good practise
# to know how reverse() or [::-1]
# works on the surface
#for char in range(len(string)-1,-1,-1):... |
d4976864bab80517d2aa9c4bae3763c2adce85a2 | team12wtc/minesweeper.py | /ex1.py | 797 | 4.25 | 4 | # I am going to first list out all my variables and assign them values
hidden_number = 5
users_guess = int(input("Pls Enter A Value: "))
number_of_guesses = 1
times_guessed = 4
no_more_guess = False
# I am using a while loop so that im able to give my code more detailed instructions
while users_guess != hidden_n... |
4116d8990c3f6472337003e6181777577febacdb | simeonikratko/python_class | /zadacha1_grupa2.py | 258 | 3.921875 | 4 | a = input("Please enter the value of a: ")
b = input("Please enter the value of b: ")
c = input("Please enter the value of c: ")
def is_equal(a, b, c):
if a[-1] * b[-1] == c[-1]:
print('True')
else:
print('Flase')
is_equal(a, b, c) |
1a90a96e8a202bff717d63b549387799f11a61ab | Shylcok/Python_Algorithm | /算法/电话号码分身.py | 819 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# @Project : Algorithm_Python
# @Time : 0426
# @Author : Shylock
# @Email : JYFelt@163.com
# @File : 电话号码分身.py
# @Software: PyCharm
# ----------------------------------------------------
# import something
# 继MIUI8推出手机分身功能之后,
# MIUI9计划推出一个电话号码分身的功能
# :首先将电话号码中的每个数字加上8取个位,
# 然后使用对应的大写字母代... |
6e30721638419a82ad4243dbbe90b2c664c7be44 | Shylcok/Python_Algorithm | /数据结构/Grid.py | 990 | 3.875 | 4 | # -*- coding: utf-8 -*-
# @Project : Algorithm_Python
# @Time : 0506
# @Author : Shylock
# @Email : JYFelt@163.com
# @File : Grid.py
# @Software: PyCharm
# ----------------------------------------------------
# import something
from 数据结构.arrays import Array
class Grid(object):
def __init__(self, rows, c... |
07c9a03a55ecf8022512ae785a2c268000127616 | Shylcok/Python_Algorithm | /算法/QuickSort.py | 599 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @Project : Algorithm_Python
# @Time : 0313
# @Author : Shylock
# @Email : JYFelt@163.com
# @File : QuickSort.py
# @Software: PyCharm
# ----------------------------------------------------
# import something
# 迭代:
def quick_sort(arr):
if len(arr) < 2:
return arr
else... |
6e147821daea53be58464b789371ea696d1f3d0b | Pradhyo/project-euler | /problem9.py | 319 | 3.765625 | 4 | # Problem 9 from Project Euler
'''There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc (a<b<c). '''
number = 1000
answer = [a*b*(number-(a+b)) for a in range(1,number/3)
for b in range(a+1,(number-a)/2)
if a*a + b*b == (number-a-b)**2]
print answer |
d970306ed1c58a4283ac0dedb99f4ac4b545a33b | MaheenAnees/CS412-Algorithms-Project | /Naive Matrix Multiplication.py | 1,759 | 4.28125 | 4 |
######################################## F I N A L ##########################################
# Program to multiply matrices using nested loops
def naive_matrix_mult(M1, M2, result):
# iterate through rows of M1
for i in range(len(M1)):
# iterate through columns of M2
for j in range(len(M2[0])):
... |
c22d950ce2478273710e053afbb051cc4bb6bad7 | crzonca/NFL-Prediction | /NFLGraph.py | 11,542 | 3.65625 | 4 | import networkx as nx
nfl = nx.MultiDiGraph()
def create_games_graph():
"""
Creates a graph for storing team games and data.
:return: The graph with the league info for the season
"""
global nfl
nfl.add_nodes_from(create_all_nfl_teams())
return nfl
def create_all_nfl_teams():
""... |
439a17d1f4cffa37aae209ef37d7df1f8dcee2f7 | smability/python | /SigAvg.py | 1,522 | 3.640625 | 4 | #average filter algorithm 3.Dic.2018
import matplotlib.pyplot as plt
pm25 =[3,5,4,5,6,6,5,3,4,4]
def avgSig(sig,leng,ns):
#pm25Avg array
SigAvg =[]
#range definition from 0 to 5, j=sample
i=0
ran = int(ns) #number of sample
j=ran
while(j<=leng): #why <=len?
#reset 'sum' every loop... |
272861b8a5c39d23b2ec461e305053de851adb18 | jkgibson/MyMiscPythonScripts | /collatz.py | 560 | 4.21875 | 4 | def collatz(number):
if number % 2 == 0:
return number // 2
# print(str(number))
elif number % 2 == 1:
return 3 * number + 1
# print(str(number))
print('This program explores the Collatz sequence.')
print('Type in any number.')
try:
newI... |
be8619cb49ea1a71d31589750f17009442ebc5dd | shaoguangji/CS449 | /project2/FischerScore.py | 3,837 | 3.609375 | 4 | """ Created by Max 9/24/2017 """
import numpy as np
def fisher_score(mean_vectors, clustered_data):
"""
Calculates the fisher score as described by the Fisher Score PDF for the project.
NOTE: the W vector is always 1's because the data that is in each of the clusters is only has the selected features
... |
63f964bad852b252285dd972369dc9168907495c | dragonfly0524/python_study | /practice/class_instance_02.py | 1,189 | 3.828125 | 4 | class Shape():
def __init__(self,width,len):
self.width = width
self.len = len
def what_am_i(self):
print("I am a shape")
class Rectangle(Shape):
def __init__(self,width,len):
self.width = width
self.len = len
... |
1cf557cf5c5e496311d2e657b1c4e00a6a73bd58 | ishwardgret/NetworkTracker | /db.py | 3,848 | 3.625 | 4 | import mysql.connector
# Create a connection object
host='localhost'
user='root'
password='password'
database='LLADADDB'
def connection(host, user, password, database=None):
if database is None:
# print("For db creation")
myConnection = mysql.connector.connect(host=host, user=user, password=pass... |
79d76c40e4c809424eafbb37d6adc87068ba8f1a | suleymanguven/python_aritmetik_ve_ikili_operator | /aritmetikveikilioperator.py | 368 | 3.578125 | 4 | x=10
y=3
toplam=x+y
fark=x-y
carpim=x*y
bolme=(x/y)
bolum=x//y
kalan=x%y
kuvvet=x**2
print("Toplam: ",toplam)
print("Fark: ",fark)
print("Çarpım: ",carpim)
print("Bölme: ",round(bolme,2))
print("Bölüm: ",bolum)
print("Kalan: ",kalan)
print("x'in Y. kuvveti",kuvvet)
print(5**2)
print("Bu kodlar ... |
496bbc990b1a6b55f8afb42a357561ea4304ca1f | JulieRolla/PythonPractice | /Solutions/FileEx2.py | 6,341 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import argparse
import csv
#### This version of the code is that passes variables through from the bash script. Please see File.py for version where all directories, files, and variables are NOT passed from bash script
#### Bot... |
fe5bfc4b1245cd355fdc0fe7737deef63d3e04a2 | saipraveenande/assignment-1 | /Hello.py | 191 | 3.859375 | 4 | print("Hello world...!")
list=[5,9,42,85,13,75,34,92]
print(list)
list.sort()
print ("Ascending order:",list)
list.sort(reverse=True)
print("descending order:",list)
print ("Done!")
|
cbcc913750380ace19b6067ba8e22f3ffdda8edc | feifaninternet/xfan_python | /firstFile.py | 259 | 3.9375 | 4 | # for 循环的展示
for xfan in 'Python':
print(xfan)
if xfan == 'h':
print('Goodbye')
break
# 按照数组的下标
fruits = ['banana', 'apple', 'mango']
print(len(fruits))
for index in range(len(fruits)):
print(fruits[index])
|
b51d8750faf8e3e9feddfb50b0f37cf8f580bbb5 | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO8.py | 757 | 3.578125 | 4 | # Ejercicio 8.
# Cajas de cereal
# Un vendedor de una pagina de abarrotes en linea vende dos tipos de caja de cereal. CornFlakes
# de 750 gr y Trix de 500 gr. Escriba un programa que lea el numero de cajas de CornFlakes y
# cajas de Trix cuyo valor debe ser introducido por el usuario. Despues, su programa debe... |
f06080c380708afbdfb952c7453fc36820eaece8 | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO70.py | 1,778 | 3.96875 | 4 | # EJERCICIO 70
# Cifrado César.
# Uno de los primeros ejemplos de encriptacion fue usado por julio cesar, que necesitaba el enviarinstrucciones
# escritas a sus generales, pero el no queria que sus enemigos conocieran de sus planes en caso de que el mensaje
# fuese interceptado. Como resuñltado el desarrollo l... |
0b21b226ba63e9b94b4b6fb833abc4d02d52f88d | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO33.py | 915 | 4.03125 | 4 | # Ejercicio 33
# Pan de un día.
# Una panadería vende hogazas de pan por $ 3.49 cada una. El pan de un día tiene un descuento de 60
# por ciento. Escriba un programa que comience leyendo la cantidad de panes de un día
# pan que se compra al usuario. Entonces su programa debe mostrar el regular
# precio del pan... |
afa3d658e92d119273da706106d0c7d9445dff3f | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO42.py | 1,204 | 4.0625 | 4 | # Ejercicio 42
# Frecuencia a tener en cuenta.
# En la pregunta anterior, convertiste del nombre de la nota a la frecuencia. En esta pregunta
# escribirás un programa que invierta ese proceso. Comience leyendo una frecuencia
# del usuario Si la frecuencia está dentro de un Hertz de un valor listado en la tabla ... |
cf1e14a6d548e543a3fc24a7e3efa4c5be7a0eba | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO44.py | 1,331 | 3.84375 | 4 | # Ejercicio 44
# Fecha de nombre de vacaciones.
# Canadá tiene tres feriados nacionales que caen en las mismas fechas cada año.
# Fecha de vacaciones
# Día de año nuevo 1 de enero
# Canadá día 1 de julio
# Día de navidad 25 de diciembre
# Escriba un programa que lea un mes y un día del usuario. Si el mes... |
f7fcb889448fea973a14a95e97dd21b5238b8921 | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO7.py | 434 | 3.90625 | 4 | # Ejercicio 7.
# Suma de los primeros numeros n enteros positivos
# Escriba un programa que lea un numero positivo (n), insertado por el usuario y despues despliegue la suma de todos los enteros
# desde 1 hasta n. La suma de los primeros enteros n positivos puede ser calculado usando la formula.
n= int(input... |
427dd52c9c05c0691e1da85cf305a100fd75bb40 | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO28.py | 1,465 | 3.984375 | 4 | # Ejercicio 28
# Escalofríos.
# Cuando el viento sopla en clima frío, el aire se siente aún más frío de lo que realmente es porque el movimiento del aire aumenta la velocidad de enfriamiento
# de los objetos calientes, como personas. Este efecto se conoce como sensación térmica. En 2001, Canadá, el Reino Unido ... |
1542eee6dfc6cef1923e1995846db4a18acde0bf | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO86.py | 2,442 | 4.09375 | 4 | # EJERCICIO 86
# Los doce días de navidad.
# Los doce días de Navidad es una canción repetitiva que describe una creciente
# larga lista de regalos enviados al verdadero amor en cada uno de los 12 días. Se envía un solo regalo el
# el primer día. Se agrega un nuevo regalo a la colección cada día adicional, y lu... |
a8a34eee3a017817efa3a22b54a08643c80a730c | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO34.py | 323 | 4.09375 | 4 | # Ejercicio 34
# Escriba un programa que lea un numero entero introducido por el usuario.
# Su programa debe desplegar un mensaje indicando si su numero entero es par o impar.
entero = int(input('Ingrese un número entero: '))
b = entero % 2
if b == 0 :
print('Es par')
else:
print('Es impar')
... |
d14a3b681364655347f9a462fea95b8313edf521 | CHRISTIANCMARCOS/progAvanzada | /EJERCICIO9.py | 931 | 3.96875 | 4 | # Ejercicio 9
# Interes compuesto.
# Usted acaba de abrir una nueva cuenta de ahorros con el cual gana el 4% de interes al año.
# El interes que usted genera es pagado al final del año, y es agregado al balance de la cuenta de banco.
# Escriba un programa que comiene por leer la cantidad de dinero depositada en... |
6d2ef96adfc7152d684237296293d781b15ff901 | GeorgeKaniros/patsakis | /4.py | 1,937 | 3.703125 | 4 | def times(x):
x = str(x) + "*"
return x
def minus(x):
x = str(x) + "-"
return x
def plus(x):
x = str(x) + "+"
return x
def operation(y, clct, ar):
if clct == "*":
return ar * y
elif clct == "-":
return y - ar
elif clct == "+":
return ar + y
def... |
faf0310858f2e3da70eaeb497c94ad104dea7a0f | knight-furry/Python-programming | /heart_user.py | 393 | 4.0625 | 4 | def heart(hight,width):
mid = width//2
for r in range(hight):
for c in range(width):
if (r == 0 and c % mid != 0) or (r == 1 and c % mid == 0) or (r - c == mid-1) or (r + c ==width+1) :
print("*",end="")
else:
print(" ",end="")
print()
x = int(input("Enter the highet of heart : "))
y = int(input("En... |
dd5a5dcaeda5c1b2b2277de2d149249b8abf78e2 | knight-furry/Python-programming | /string.py | 217 | 3.5625 | 4 | s = " Datta "
print(s)
t = s.rstrip()
print(t)
t = s.lstrip()
print(t)
t = s.strip()
print(t)
t = s.find("Datta")
print(t)
k = "Datta is good boy but nilesh is very bad boy."
t = k.replace("good","bad",1)
print(t)
|
10b4e34aba0bfe0bdd5283e0ee3016a433a1ea07 | knight-furry/Python-programming | /sort.py | 189 | 4.0625 | 4 | x = int(input("Enter the size of list: "))
l = []
for i in range(x):
a = int(input("Enter element: "))
l.append(a)
print("The given list is: ",l)
l.sort()
print("The sorted list is: ",l)
|
0a63a60a5a855894e807ad1b6334c34505f3684c | knight-furry/Python-programming | /Random.py | 331 | 3.8125 | 4 | import random
value = 0
count = 0
while value != " " :
if count % 2 == 0 :
value = input("player1 : ")
value = random.randint(1,6)
print(value)
else:
value = input("player2 : ")
value = random.randint(1,6)
print(value)
count = count + 1
value = input("Do you want to play(y/n) : ")
if value == 'n' :
v... |
cd3029fc8a546a4f37642e9a58bc1c0e2c6e69ae | knight-furry/Python-programming | /143.py | 564 | 3.640625 | 4 | print("\n########################################\n")
for i in range(6):
for j in range(19):
if (i==0 and (j!=5 and j!=6 and j!=9 and j!=12 and j!=13 and j!=15 and j!=16 and j!=17)) or (i==1 and (j==6 or j==9 or j==12 or j==14 or j==18)) or (j==2) or (i==2 and (j==6 or j==12 or j==14 or j==18)) or (i==5 and (j<5 or ... |
1fd18e301035735d04fc612e3c13ddafd4772c7e | knight-furry/Python-programming | /binary_search.py | 565 | 3.84375 | 4 | def binarysearch(l,x,low,high):
if (high-low == 0):
return False
mid = (high+low)//2
if (x == l[mid]):
return True
if (x < l[mid]):
return(binarysearch(l,x,low,mid))
else:
return(binarysearch(l,x,mid+1,high))
n = int(input("Enter the size of list:"))
l = []
for i in range(0,n):
item = int(input("Enter ele... |
1795cb6b77cb1c60d7afa8a7d75e5f3b832d7050 | cvlg-dev/wy-til | /anything-python/advanced-python/chp02-02.py | 2,335 | 4.09375 | 4 |
class Car:
""" ## Pythonic 한 방식으로 코멘트를 달아주는 것이 좋다
Car class
Author : Lucas
Date : 20210331
"""
# 클래스 변수 : namespace는 없는데 접근은 가능함.
car_count = 0
def __init__(self, company, details):
self._company = company
self._details = details
Car.car_count += 1
... |
3520b15ce8718ddc7fd16367a1df82a7ba4bd091 | steelrider/tictactoe-python-bot | /python_tictactoe_bot.py | 6,035 | 3.90625 | 4 | from __future__ import print_function;
import copy;
import math;
from random import randint
class Node(): #each node is a node in the tree, it has a current state(data) and knows which symbol should be put next
def __init__(self,data,nextSym):
self.data = data;
self.nextSym = nextSym;
def makeEmp... |
4e7d12cdfaf9cb281557577dd33bb6514b0521e6 | gbf-labs/rh-backend | /Library/lib_MAC.py | 1,549 | 3.59375 | 4 | """
Functions that have something todo with MAC-addresses
"""
class MAC(object):
@classmethod #global class method
def ConvertMACToStandardFormat(cls,MacAddress):
"Convert Mac to Standard Format (aa:bb:cc:dd:ee:ff)"
MacAddress = MacAddress.replace(":","").lower()
MacAddress = MacAddress.replace("... |
6243c5be88738e54eec130f3175af7e78a3d6c9b | Qazzzie/domletters | /domletters | 1,310 | 3.859375 | 4 | #!/usr/bin/python3
# Made executable with chmod -x domletters.py
"""
Zach Santangelo
CS461P HW1
"""
from sys import stdin
import os.path
def is_valid_word(word):
for letter in word:
print(word)
if(letter.isalpha() == False):
return False
return True
def count_dom_... |
e54851f284a9635459105f99f724d5a78730ebb7 | yuki9965/my-algorithm | /test.py | 472 | 3.59375 | 4 |
def lengthOfLongestSubstring(s: str) -> int:
# 滑动窗口
temp = set()
left, right = 0, 0
maxlen = 0
while right < len(s):
c1 = s[right]
right += 1
while c1 in temp:
temp.remove(s[left])
left += 1
temp.add(c1)
if right - left > maxlen:
... |
ca6afa6e0ac5ffc77163b5e7819bc9d70d3ff517 | Parth-D-Shah/Word_Tree | /wordtree.py | 11,664 | 3.734375 | 4 | class WTNode:
def __init__(self,d,l,m,r):
self.data = d
self.left = l
self.right = r
self.next = m
self.mult = 0
# prints the node and all its children in a string
def __str__(self):
st = "("+str(self.data)+", "+str(self.mult)+") -> ["
if ... |
e4388e4d3985349176e4041fea40828d6784fd91 | ayushpriya10/pychk | /pychk/fetch_resources.py | 1,052 | 3.59375 | 4 | import json
import requests
import sys
def fetch_jsons(json_output=False):
print('[INFO] Fetching latest resource files.')
try:
insecure_deps = json.loads(requests.get('https://raw.githubusercontent.com/pyupio/safety-db/master/data/insecure.json').content)
print('[INFO] Fetched list of Insecu... |
66b5a2481e6b22674e7a212a49a4f01488d17f93 | ryancor/CryptoPals-Solutions | /Set1/Challenge7/convert.py | 526 | 3.546875 | 4 | import base64
from Crypto.Cipher import AES
KEY = b'YELLOW SUBMARINE'
def return_decodedB64_from_file(filename):
with open(filename, 'r') as fp:
content = fp.read()
convert_to_ascii = base64.b64decode(content)
return convert_to_ascii
def decrypt_AES_ECB(ciphertext, plaintext_key):
cipher = ... |
3b2c1695806cb6d1656a9dcd7294f1329794e598 | riddhindoshi/Build_resume | /make_website.py | 8,728 | 4.28125 | 4 | def read_file():
"""
This function would read the contents of the file in a stream and puts it in a list.
:return: A list of the content of file
"""
fstream = open("resume.txt", "r")
# list of lines from the input file
lines_list = fstream.readlines()
fstream.close()
return lines_lis... |
0689e3c9c6ea5e4f4cc00967f92066bc73e347aa | DerrickDDInAI/challenge-card-game-becode | /main.py | 809 | 4.03125 | 4 | # import modules
from utils.game import Board
from utils.player import Player
print("Hello'o dear user 😄")
print("Welcome to my card game world!")
Play_or_no_Play = input("Would you like to play? (Y/N): ").upper()
print(Play_or_no_Play)
while Play_or_no_Play != "Y" and Play_or_no_Play != "N":
Play_or_no_Play = in... |
7815d02f0065318e0a9458b0725828714f459f76 | Paulofalcao2002/Sudoku | /estrutura.py | 2,201 | 3.53125 | 4 | jogo = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def mostra_sudoku(matrix):
for i in range(len(matrix)):
if i % 3 == 0 and... |
ed7ee2160a28aab5f3b11053896aa48ee2dddfe3 | SebastianTrianaP/Analisis-de-algoritmos | /Problemas/Programacion dinamica/minMultiplicacionDeMatrices.py | 3,155 | 3.71875 | 4 | import math #-----------------Recursivo--------------------
def ParenthesesMaxMult(D):
return ParenthesesMaxMult_Aux(D, 1, len(D)-1)
def ParenthesesMaxMult_Aux(D, i, j):
if i == j:
return 0
else:
q = math.inf
for k in range(i, j):
print(i)
print(k)
v... |
2aaffa665fe7682e0833b833da576bb9e38cea7a | marzanchet/binarysearchpy | /main.py | 669 | 3.875 | 4 | def naive_search(l, target):
for i in range(len(l)):
if l[i] == target:
return i
return -1
def binary_search(l,target, low=None, high=None):
if low is None:
low = 0
if high is None:
high = len(l) -1
if high < low:
return -1
midpoint = (low + high) /... |
b84b0adfb593919015d95babe6ecdb821c8ae16c | cleona1401/python-codes | /taskA/TA-6.py | 653 | 4.1875 | 4 | les=[] #delared an empty list
num=int(input("enter no of elements to be inserted"))#take the no of elements that user wants to enter from user
for i in range(num): will iterate through the range given by user
elem=input() #will take input from user that many times
les.append(elem)#will append the in... |
af2b701f2306dab6c9910971133825d4171da650 | halyangx/Stop-Points-Extract-Algorithm-Based-on-Pandas | /utils/calculations.py | 4,493 | 3.546875 | 4 | import pandas as pd
import numpy as np
def _distance_difference(point1, point2):
return _haversine_np(point1['lon'], point1['lat'], point2['lon'], point2['lat'])
def _haversine_np(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal d... |
13190e92f4f341b35c7c1deac6f55149d93bfcd7 | letatanu/TSP | /NearestNeighbor.py | 1,329 | 3.765625 | 4 | from TSP import TSP
import math
class NearestNeighbor(TSP):
def __init__(self, points):
super(NearestNeighbor, self).__init__(points)
#initialize the start city is the first point.
startPoint = self.points[0]
self.points.remove(startPoint)
self.path = [startPoint]
'''Th... |
b099be5da1cd1e9b49328b85ef4dfeba288756ba | Telespielstube/Staubbeutel | /Temperature.py | 659 | 3.515625 | 4 | from Date import Date
class Temperature():
def __init__(self, DatabaseManager):
self.db = DatabaseManager
self.date = Date()
# Function to save temperature/ humididty values to DB Table
#
# temperature temerature value
# humidity humidity value
# station_id identifica... |
02a73a4253eb63c3d694b48f2b67eec4d46ee249 | Kz-Pr1d3/leetcode-solutions | /src/easy/two_sum.py | 1,071 | 3.703125 | 4 | from typing import List
def two_sum_old(nums: List[int], target: int) -> List[int]:
check_num = 0
for j in range(len(nums)):
for i in range(len(nums)):
if i == check_num:
continue
check_sum = nums[check_num] + nums[i]
if check_sum == target:
... |
5c627ea01180928869a101caaf6b83f70f1ce8cb | hujuanzp/Exprience_AI | /BP/bp_test.py | 6,795 | 3.546875 | 4 | # -*-coding:utf-8-*-
import math
import random
import numpy as np
random.seed(0)
def rand(a, b):
return (b - a) * random.random() + a
def make_matrix(m, n, fill=0.0):
# 创建一个指定大小的矩阵,使用fill值填充
mat = []
for i in range(m):
mat.append([fill] * n)
return mat
# ②实现激活函数sigmoid及其一阶导数。公式见前面。
d... |
f569abb87fbd078086e8ce87c4b7324711c8470a | serhiihoriaiev/common | /tests_practice/task1.py | 5,396 | 4.15625 | 4 | import math
import re
def task_1_arr_intersection(arr1, arr2):
"""
Take two lists and write a program that returns a list that contains
only the elements that are common between the lists (without duplicates).
"""
return list(set([i for i in max([arr1, arr2], key=len) if i in arr1 and i in arr2]))... |
7fb74f7f5ebdfdeb75fc256ea56f3dd34764ad16 | jguerra7/geeksforgeeks-1 | /pairs_with_difference_k.py | 722 | 3.90625 | 4 | """
Pairs with difference K - GeeksForGeeks
Problem Link: https://practice.geeksforgeeks.org/problems/pairs-with-difference-k/0
Author: Shyam Kumar
Date: 15-09-2019
"""
from itertools import combinations
def pairs_with_difference(n,k,arr):
'This function uses combinations method to find all th... |
fdfb6b200a2f12c976ed7bcd3539358a7fdad4d4 | 3228689373/excercise_projecteuler | /largest_prime_factor.py | 1,141 | 3.859375 | 4 | import math
def is_prime(n):
'''
l = list(range(1,20))
>>> list(filter(lambda ele:is_prime(ele)==True,l))
[2, 3, 5, 7, 11, 13, 17, 19]
'''
if(n==1):
return(False)
if(n==2):
return(True)
uplimit = int(math.sqrt(n)) + 1
for i in range(2,uplimit+1):
... |
7dbf7acc3f9e7dcf3d8bc42c7e256329e88f14f1 | iptq/CSCI1913 | /lab3.py | 973 | 3.65625 | 4 | class Sieve(object):
def __init__(self, max):
if max < 0:
raise ValueError("max must be positive.")
self.numbers = [False, False] + [True] * (max - 2)
def findPrimes(self):
for i, v in enumerate(self.numbers):
if not v:
continue
for j in range(2 * i, len(self.numbers), i):
self.numbers[j] = Fal... |
4d68593e42b3c9253d1bb3327bec847c667933c1 | ligson/pstart | /pystudy/collection.py | 854 | 4.125 | 4 | # coding=UTF-8
'''
Created on 2013年10月14日
@author: ligson
'''
# 元组和列表十分类似,只不过元组和字符串一样是不可变的,即你不能修改元组。help(tuple)
# 元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。
def tupleTest():
tuple = ("122", "33", "ddd")
print len(tuple)
tuple = ("你好", tuple)
print len(tuple)
for st in tuple:
print st
... |
dc3840de8ff69f3bdd5ad0850f2652430a16ec6e | LucasR-Freire/Cryptography | /MyStreamCipher.py | 939 | 3.59375 | 4 | import random
class KeyStream:
def __init__(self, key=1):
self.next = key
def rand(self):
self.next = (1103515245*self.next + 12345) % 2** 31
return self.next
def get_key_byte(self):
return self.rand() % 256
def encrypt(key, message):
return bytes([messa... |
1844b8eda0e40d51c80ce404e739c143f3869e4b | tectronics/naas | /hg/source/Elementos.py | 1,312 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# Recupera tabela (nuclear) com elementos, energias , meia vida para localização dos elementos através das energias
import sys, string
from os.path import isfile
from os import chdir
import os
class Elementos:
def __init__(self, arquivo):
self.arquivo = arquivo
self.elem=[]
... |
9b5ac5322d92296d8bf5d3975414e53ff91155d8 | VineethSendilraj/TicTacToeBot | /ReTicTacToe.py | 5,688 | 3.59375 | 4 | class board:
def __init__(self):
self.key = {9:'Player 1 Wins', 6:'Potential win for player 1', 5:'Potential Block for player 1', 3:'First player 1 chip in the row',\
-4:'Player 2 Wins', -3:'Potential win for player 2', -2:'Potential Block for player 1', -1:'First player 2 chip in the row',\
... |
cca4025c8f748060ef281f4a89bddc4671e9b062 | Kotilia/homework | /first.py | 2,510 | 3.703125 | 4 | #Кот Илья Аи-182
from random import randrange
import time
from datetime import datetime
import random
#buble
my_list = [ randrange(0, 15) for i in range(10) ]
#Сортировка слиянием
def merge_sort(mass):
lenght = len(mass)
if lenght >= 2:
mid = int(lenght / 2)
mass = merge(merge_sort(mass[:mid]),... |
020ab1ce8752d29359bad417560647afee202162 | DracoHawke/python-assignments | /Assignment7/assignment7.py | 667 | 4.15625 | 4 | # Q.1 Create user defined dictionary
# A.1 ->
dict1 = {}
i = 'a'
while i != 'end':
key = input('enter the key value for dictionary: ')
value = input('enter the value for corresponding key: ')
dict1[key] = value
i = input('enter "end" to terminate input and print dictionary otherwise anything to continu... |
a4a6faab9f1c93fdcf578cc35cc157d569793415 | DracoHawke/python-assignments | /Assignment5/assignment5.py | 3,962 | 4.21875 | 4 | # Q.1 check if user input is leap year or not
# A.1 ->
print('enter the year to check')
year = int(input())
if year % 4 == 0:
print('year mentioned IS leap year')
else:
print('year input IS NOT a leap year')
# Q.2 check if square or rectangle
# A.2 ->
print('\n\n')
print('enter the 2 sides of the desired par... |
ec2faba21ea8ee3cb1bbd88a28af0f694bf73073 | DracoHawke/python-assignments | /Assignment3/Lists/answer2.py | 266 | 3.859375 | 4 | x = int(input("enter the number of entries you want to make into the list \n"))
list1 = []
for i in range(0, x):
a = input("enter list element\n")
list1.append(a)
list2 = ['google', 'apple', 'facebook', 'microsoft', 'tesla']
list1.append(list2)
print(list1)
|
a0ac9f51c5f01f52e3e02ff9ab7741452a791b88 | cloew/KaoDecorators | /kao_decorators/equality_via.py | 479 | 3.703125 | 4 |
def equality_via(*attrs):
""" Decorator to add equality comparisons to a class via the provided attributes """
def addEq(cls):
def equals(self, other):
if any([not hasattr(other, attr) for attr in attrs]):
return NotImplemented
else:
retur... |
2717db1ba87193adda73380a046d2922d3280106 | andrewhwest/Matched-Betting | /Script /balance_functions.py | 5,872 | 4.0625 | 4 | """Functions that were made during part 3 to calculate profit and keep track of balances
across various bookmakers accounts."""
import pandas as pd
# Functions to calculate profit
def add_profit_column(spreadsheet):
"""Creates a profit column to the right of bet result.
All values are initialised... |
058181a1e5428d5ba0f20b12d33159e69f91d4dc | Skorpionmaf/PA | /vari/2es1b_func.py | 1,504 | 3.640625 | 4 | import functools
import collections
# ritorna True se x e' primo
def is_prime(x):
numbers = [n for n in range(1, x+1)]
test = list(map(lambda n: x%n == 0, numbers))
return collections.Counter( test )[True] == 2 or x == 1
# ritorna la lista dei divisori di x che sono primi
def prime_divisori(x):
number... |
c90d4b2b24461368458b05fc6ed3227ba0b548ad | Skorpionmaf/PA | /f7_2.py | 512 | 3.6875 | 4 |
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
for i in range(2, n):
if n%i == 0:
return False
return True
def prime_list(n):
return [p for p in range(2, n) if is_prime(p)]
def golbach(n):
for x in prime_list(n):
if is_prime(n-x)... |
1de50d1bbb7fdb6e22df17a99d50c8b3801d642e | Skorpionmaf/PA | /anagram2.py | 1,384 | 3.53125 | 4 | import timeit
def words_dict_gen(path = './wordlist-anagram.txt'):
f = open(path, "r")
words_dict = dict()
for l in f:
w = l.strip()
w_l = "".join( sorted(list(w.lower())) )
if w_l in words_dict.keys():
words_dict[w_l].append( w )
else:
words_dict[w_... |
2e8b2b6ba318784bcf95b8926144bf1eceaba717 | Skorpionmaf/PA | /lab2/foglio2_2bis.py | 244 | 3.75 | 4 | import re
import collections
f = open('testo.txt')
g = ( line.strip() for line in f )
w = ( re.findall('[a-zA-Z]+|[;:,.]+', x) for x in g )
l = ( x for line in w for x in line )
c = collections.Counter(l)
print( c )
print( c.most_common(3) ) |
8fef2e0eb6a701d0e82ba7b071aa96e6284e3234 | Skorpionmaf/PA | /f7_3.py | 2,646 | 3.765625 | 4 |
class Matrix:
def __init__(self, matrix):
self.matrix = matrix
def __eq__(self, other):
if self.matrix == other.matrix:
return True
else:
return False
def copy(self):
return Matrix(self.matrix)
def dim_row(self):
return len( self.matri... |
74902441e4697d8c1845bfe73fa68a45e29c2574 | Skorpionmaf/PA | /lab2/foglio2_1d.py | 219 | 3.578125 | 4 | def fib(n_digits):
a, b = 0, 1
while len(list(str(a))) < n_digits:
tmp = b
b = b + a
a = tmp
yield a
if __name__ == '__main__':
l = (x for x in fib(1000))
print( max(l) ) |
a84e3d231b87bbb32c6baf6c4b2cabab3fbdb945 | YuraPopovych/Objects-Algorithms | /Exam/lazyEncrypt/lazyEncrypt.py | 689 | 3.59375 | 4 |
def lazy_encrypt(output, input, mapping_encrypt):
input_file = open("/home/yuriipopovych/Learning/python/Objects-Algorithms/Exam/lazyEncrypt/{0}".format(input))
output_file = open("/home/yuriipopovych/Learning/python/Objects-Algorithms/Exam/lazyEncrypt/{0}".format(output), "w")
for line in input_file:
... |
37baaf1e606dde5a3a58a0384c0fa8fbbce7fc8e | YuraPopovych/Objects-Algorithms | /FinalProblemSet/nameGenerator/nameGenerator.py | 1,001 | 3.640625 | 4 |
def generate_name(file, targetName):
splittedTargetName = targetName.split(" ")
firstName = splittedTargetName[0].capitalize()
secondName = splittedTargetName[1].capitalize()
firstNameFirstLetterPosition = ord( firstName[0] ) - 64
secondNameFirstLetterPosition = ord( secondName[0] ) - 38
heroNa... |
ed215906d8df7661098af1b5125dd85adc9273a9 | YuraPopovych/Objects-Algorithms | /Objects/problem_5_1_5_2.py | 583 | 3.625 | 4 |
class Artist:
def __init__(self, name, label):
self.name = name
self.label = label
class Song:
def __init__(self, name, album, year, artist):
self.name = name
self.album = album
self.year = year
self.artist = artist
TailorSwift = Artist("Taylor Swift", "Big M... |
0284cc95d2463390e40149fd22024ec69e30c27d | YuraPopovych/Objects-Algorithms | /Objects/problem_5_1_8.py | 511 | 3.5625 | 4 |
class Burrito:
def __init__(self, meat, to_go, rice, beans, extra_meat = False, guacamole = False, cheese = False, pico = False, corn = False ):
self.meat = meat
self.to_go = to_go
self.rice = rice
self.beans = beans
self.extra_meat = extra_meat
self.guacamole = gu... |
f488a5c79deb102f44b7bd3e8cc5650a0eedf8ac | luca16s/HackerRank | /Python/0009-ListComprehensions.py | 1,379 | 4.28125 | 4 | """----------------------------------------------------------------"""
"""------------------------------TASK------------------------------"""
""" Let's learn about list comprehensions! You are given three """
""" integers X,Y and Z representing the dimensions of a cuboid """
""" along with an integer N. You hav... |
08ffe4f18a1eadb2a8acbc4b71da38692ab6e183 | mozgit/CUSO-python-course | /testing-exercises/MySolutions/test_center.py | 2,397 | 3.921875 | 4 | import unittest
class CenterStringTest(unittest.TestCase):
def test_center(self):
"""Unittest for string.center()"""
print 'Basic functionality'
test_cases = [('1', ' 1 '),
('12', ' 12 '),
#in oddnumberof additions, center
... |
2031ba2be6ab08dce1e0b86e5ad401589ec28b8f | SebastianG343/LaboratorioFuncionesRemoto | /is_prime2.py | 387 | 3.5625 | 4 | def perfect_number():
x=0
k=0
l=[]
n=int(input("Digite un numero"))
for i in range(0,n):
if n%i==0:
x+=1
i.append(l)
print(l)
for len in (l):
k+=1
if k==n:
print("Es perfecto")
... |
51481db60410571dbe28e25ddfe52f2232b75b56 | Alruk-art/Vebinars | /Вебинар по числам.py | 1,072 | 3.796875 | 4 | l=("hello world computer yes").split()
#l=l.split();
#print(l)
llen=len(l)
a=set(l)
print (a)
print (l,llen)
for i in l:
print (i, len(i))
l=("1 3 5 7 9").split()
print('"1 3 5 7 9" после split ', l)
l = list(range(21))
print (type(l))
l=list(map(int, l))
print (l)
print (type(l))
a=0
for i in l:... |
a4fadd20b3c5d07554288367af7126ae134bc25b | philippeitis/py-polynomial | /polynomial/binomial.py | 1,578 | 3.875 | 4 | """This module defines different types of binomials and their methods."""
from polynomial.core import (
Polynomial,
Monomial,
FixedDegreePolynomial,
FixedTermPolynomial
)
class Binomial(FixedTermPolynomial, valid_term_counts=(0, 1, 2)):
"""Implements single-variable mathematical binomials."""
... |
0df7d130b440973bfd33673a02d7162564ef429b | Sababagherinia/algorithm_design | /single source path.py | 1,100 | 3.90625 | 4 | #alireza bagherinia,alireza khorsand,pouya sanaii
"""bellman ford algorithm for finding the shortest path to a vertex from a single sort
this alghorithm handles negative weights"""
def bellmanFord(graph, source):
distance, predecessor = dict(),dict()
for node in graph:
distance[node],predecessor[n... |
91c4f7368519351cb491a6739bda15f55e894a1b | philipzhou2009/coding | /python/03xx/0322/solution01.py | 1,169 | 3.78125 | 4 | # https://leetcode.com/problems/coin-change/
from typing import List
logger = print if True else lambda *arg: None
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
tmp = getCoins(coins, amount)
return -1 if tmp == "inf" else tmp
# pass
def getCoins(coins: Li... |
ac1f1052d93fc0b8be0226b1574c1de2dd7b603c | philipzhou2009/coding | /python/09xx/0986/solution01.py | 1,450 | 3.734375 | 4 | # https://leetcode.com/problems/interval-list-intersections/
from typing import List
logger = print if True else lambda *arg: None
def myFunc(input: List[int]):
return input[1]
class Solution:
def intervalIntersection(
self, A: List[List[int]], B: List[List[int]]
) -> List[List[int]]:
... |
ff1db14daca6330007377102afc43acaa2d21591 | philipzhou2009/coding | /python/06xx/0633/solution02.py | 638 | 3.8125 | 4 | # https://leetcode.com/problems/sum-of-square-numbers/
from typing import List
import math
verbose: bool = False
logger = print if verbose else lambda *arg: None
class Solution:
def judgeSquareSum(self, c: int) -> bool:
logger("c=", c)
j = int(math.sqrt(c)) + 1
resultB = False
... |
c600d135f163068a4b68c1923e39b9de9951ed8f | philipzhou2009/coding | /python/00xx/0034/solution01.py | 1,406 | 3.75 | 4 | # https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
from typing import List
logger = print if False else lambda *arg: None
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
result = func(nums, target, 0)
logger("result=%s" % r... |
abc61f1b21cb329ad635d4b1a10562ac552ae61c | philipzhou2009/coding | /python/03xx/395/solution01.py | 1,159 | 3.5 | 4 | # https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/
logger = print if False else lambda *arg: None
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
sLen = len(s)
i = 0
maxLen = 0
while i < sLen:
newStr = s[i:]
... |
bedb95d06cda34ec2991fec540ba09797f9d6625 | philipzhou2009/coding | /python/00xx/0042/solution02.py | 916 | 3.796875 | 4 | # https://leetcode.com/problems/trapping-rain-water/
from typing import List
logger = print if True else lambda *arg: None
class Solution:
def trap(self, height: List[int]) -> int:
result = getResult(height)
logger("result=", result)
return result
def getResult(height: List[int]) -> ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.