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 |
|---|---|---|---|---|---|---|
7d6a397767236554fe50d29a043682d9ac471a6c | ddilarakarakas/Introduction-to-Algorithms-and-Design | /HW3/q4.py | 1,373 | 4.21875 | 4 | import random
swap_quicksort=0
swap_insertion=0
def quick_sort(array, low, high):
if low<high:
pivot = rearrange(array, low, high)
quick_sort(array, low, pivot - 1)
quick_sort(array, pivot + 1, high)
def rearrange(array,low,high):
global swap_quicksort
p = array[high]
left = l... |
9296fd59a704249ee95301165cde09776da0c8ce | moummou2018/ProjetPython | /src/dao/database.py | 6,507 | 3.96875 | 4 | # Content : Database.py
# Class used to manipulate the database (table creation, insertion .. )
# Author : Dimitri SAINGRE
import sqlite3
class Database:
def __init__(self, path):
"""
Constructor of Database class.
Path : String - path to the database file
"""
try:
... |
1ab168d9dbfd0735ecafe315dc64bf9a97b713f0 | CpBruceMeena/Tensorflow | /ZTDL/Linear_regression.py | 835 | 3.6875 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_csv('C://Users//LENOVO IDEAPAD 320//OneDrive//Desktop//height_weight.csv')
print(df.head())
df.plot(kind = 'scatter',
x = 'Height',
y = 'Weight',
title = "Initial Weight and Height")
plt.plot([55, 78], [75, 2... |
424a1bf2730884ff1d1fa37448b212471a082d0b | talrus/Dz | /CodeWars/Count_of_positives _sum_of_negatives.py | 460 | 4.09375 | 4 | '''
Given an array of integers.
Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.
If the input array is empty or null, return an empty array.
'''
def count_positives_sum_negatives(arr):
leng = len(list([x for x in arr if x > 0])) # g... |
83fc85141188c94784ed0678cc4e2db5054f7e74 | juceyjing/startPython | /pytext.py | 742 | 3.6875 | 4 | # -*- coding: UTF-8 -*-
# def printme(str):
# #打印传入的字符串到标准显示设备上
# print str
# return
# printme("woshishei")
# printme("wozaidiayici")
# def changeNum(a):
# a=10
# print a
# return
# b=2
# changeNum(b)
# print b
# def printme(str):
# print str
# return
# printme(str="mystr")
# def printme(name,age):
# print "... |
fc8b2a770b2ff6d461c693440217598d6a0474fe | geek-ninja/hackerrank_solutions | /hackerrank/drawing_book.py | 187 | 3.671875 | 4 | # Drawing book problem
n=int(input())
p=int(input())
if p%2==0:
x=p/2
else:
x=(p-1)/2
y=(n-p)//2
if x<y:
print(int(x))
elif n==6 and p==5:
print(1)
else:
print(int(y)) |
39465ec55e10a5484989b30a26a40a377935c3d4 | khy0425/StudyProject | /section06.py | 2,839 | 3.875 | 4 | # Section 06
# 파이선 함수식 및 람다 (lambda)
# 함수 정의 방법
# def 함수명(parameter):
# code
# 함수 호출
# 함수명(parameter)
# 함수 선언 위치 중요
# 예제 1.
def hello(world):
print("Hello", world)
hello("Python")
hello(7777)
# 예제2
def hello_return(world):
val = "Hello" + str(world)
return val
str = hello_return("Python !!!")... |
109ad25c94a59f989f6ff3bf007f6b53fae7ad77 | JuanDiazUPB/LogicaProgramacionUPB | /Laboratorios/Lab1604/Ejercicio 4.py | 367 | 3.703125 | 4 | def primo(num):
for i in range(2, num):
if num % i == 0: # Si el residuo es 0:
return False # El número no es primo
return True # Si no, es primo
numero = int(input("Introduzca un número: "))
if primo(numero):
print("Es primo (solo tiene dos divisores)")
else:
print("... |
4808f515c0d7ff4ee0718a4db417814b4b533411 | JuanDiazUPB/LogicaProgramacionUPB | /Laboratorios/Lab1903/Ejercicios for 8.py | 451 | 3.65625 | 4 | print('Ejercicio 8: Escribir un programa que permita al usuario ingresar dos años y luego imprima todos los años en ese rango, que sean bisiestos y múltiplos de 10.')
anioInicio = int(input("Año inicial: "))
anioFin = int(input("Año final: "))
for anio in range(anioInicio, anioFin+1):
if not anio % 10 == 0:
... |
e9e348225e5ddbc6535e5afe669b9893cb25e7ce | JuanDiazUPB/LogicaProgramacionUPB | /Taller algoritmos/Ejercicio 5.py | 346 | 3.640625 | 4 | n1 = float(input('Introduzca la nota 1: ')) * 0.15
n2 = float(input('Introduzca la nota 2: ')) * 0.2
n3 = float(input('Introduzca la nota 3: ')) * 0.15
n4 = float(input('Introduzca la nota 4: ')) * 0.3
n5 = float(input('Introduzca la nota 5: ')) * 0.2
notas = [n1, n2, n3, n4, n5]
nfinal = sum(notas)
print('\nLa ... |
42d6ade9eec3f1abb794bf4f544026fb83451bfe | JuanDiazUPB/LogicaProgramacionUPB | /Laboratorios/Lab1604/Ejercicio 1.py | 470 | 4.1875 | 4 | def validacion(email):
for x in email:
if direccion.endswith("@gmail.com") or direccion.endswith("@hotmail.com") or direccion.endswith("@outlook.com"):
# endswith valida la ultima parte de la cadena
return True
return False
direccion = input("Ingresa tu email: ")
if va... |
3af76e9c582cdcfce7c7645e9bc6b217436f72ad | JuanDiazUPB/LogicaProgramacionUPB | /Taller algoritmos/Ejercicio 3.py | 280 | 3.828125 | 4 | n1 = int(input('Introduzca el número 1: '))
n2 = int(input('Introduzca el número 2: '))
suma = n1 + n2
resta = n1 - n2
multiplicacion = n1 * n2
division = n1 / n2
print('\nSuma =', suma, '\nResta =', resta, '\nMultiplicación =', multiplicacion, '\nDivisión =', division) |
ba41ebf1190a33e98050448914a931b4142633ec | JuanDiazUPB/LogicaProgramacionUPB | /Laboratorios/Lab1903/Ejercicios for 4.py | 255 | 3.78125 | 4 | print('Ejercicio 4: Pedir al usuario que ingrese un número entero positivo e imprimir todos los números correlativos entre el ingresado por el usuario y uno menos del doble del mismo.')
n = int(input("Número: "))
for n in range(n, n*2):
print(n) |
9b9758c901cffba2ee6d81d1935fbf17240be16f | JuanDiazUPB/LogicaProgramacionUPB | /Taller algoritmos/Ejercicio 24.py | 279 | 3.515625 | 4 | vproducto = int(input('Introduzca el valor del producto: '))
vventa = vproducto + (vproducto * 0.19)
if vventa >= 150000:
print('Valor superior a 150000 pesos, restando 5% al valor...')
vventa = vventa - (vventa * 0.05)
print(f'El valor de la venta fue: {vventa}')
|
5ae438c8e11e0beec40d4cf82e70089af88bd3de | wffeige/algorithm015 | /Week_02/1_两数之和.py | 1,540 | 3.546875 | 4 | # 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
#
# 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
#
#
#
# 示例:
#
# 给定 nums = [2, 7, 11, 15], target = 9
#
# 因为 nums[0] + nums[1] = 2 + 7 = 9
# 所以返回 [0, 1]
#
# Related Topics 数组 哈希表
# 👍 8962 👎 0
class Solution(object):
def twoSum(self, nums, target):
... |
d1f0a3f7f236471c875f3e8301a374721d4bfc16 | wffeige/algorithm015 | /Week_02/242_有效的字母异位词.py | 1,473 | 3.96875 | 4 | # 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
#
# 示例 1:
#
# 输入: s = "anagram", t = "nagaram"
# 输出: true
#
#
# 示例 2:
#
# 输入: s = "rat", t = "car"
# 输出: false
#
# 说明:
# 你可以假设字符串只包含小写字母。
#
# 进阶:
# 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
# Related Topics 排序 哈希表
# 👍 248 👎 0
""":cvar
# 做题4步
1. clarification 重新确... |
157c69a85b334193f9fb1be43313ddffaf2a14cc | AndreRamos7/aprendendo_openCV | /houghLines_teste/recortador_novo.py | 1,698 | 3.90625 | 4 | # Python program to illustrate HoughLine
# method for line detection
import cv2
import numpy as np
# Reading the required image in
# which operations are to be done.
# Make sure that the image is in the same
# directory in which this python program is
img = cv2.imread('../diversos/imagens/img.jpeg')
# Convert t... |
5ec3a1f5e8cd5494823c7b12d0355073bbd6402e | filipcima/2020-mpzz | /relations_properties.py | 3,778 | 3.9375 | 4 | def reflexive(R, A):
"""Returns True if a relation R on set A is reflexive, False otherwise."""
for a in A:
if (a, a) not in R:
return False
return True
def test__reflexive():
A = [1, 2, 3]
cases = [
([(1, 2), (2, 1)], A, False),
([(1, 1), (1, 2), (2, ... |
1c824370a0d56999fbe3436725167bfee86493b6 | JonMer1198/developer | /programstarter.py | 1,133 | 3.609375 | 4 | from math import *
from sympy import *
import numpy as np
a,b,c,x = symbols('a,b,c,x')
#f = a*x**2 + b*x + c
#f = a*x**4
f = 3.0 / ((2.0*x)+2)
#f = Function('f')
x = Symbol('x')
#fprime = f(x).diff(x) - f(x) # f' = f(x)
F = integrate(f,x)
F = str(F)
# y = dsolve(fprime, f(x))
y = Symbol('y')
eqn = Eq(((3.0)/(2.0)*(np... |
523374b3dca758cdbe8cf481147adc13e6b07ae0 | WillCorrigan/advent-of-code | /day 3/day 3 part 2.py | 748 | 3.609375 | 4 | filename = "C:\\Users\\wcorr\\Desktop\\Advent of Code\\day 3\\data.txt"
with open(filename) as f:
content = f.readlines()
split_routes = [coord.strip() for coord in content]
def SlopeMovement(x_increase, y_increase):
number_of_trees = 0
x_coord = 0
y_coord = 0
while y_coord < len(split_routes):
... |
86e9f379c621d09bbe5419d61b2e574fa2a0de74 | WillCorrigan/advent-of-code | /day 6/day 6 part 2.py | 491 | 3.53125 | 4 | filename = ".\\data.txt"
with open(filename) as f:
content = f.read().split("\n\n")
content = [elem.split("\n") for elem in content]
total = 0
for string_list in content:
list_length = len(string_list)
joined_string = ''.join(string_list)
checked_letters = []
for letter in joined_string:
... |
77ce249775fc9a69f8e02df404d3a03c57173af6 | DashaChis/New_one | /hw14/hw14.py | 631 | 3.59375 | 4 | import re
def get_data(filename):
raw = ''
with open(filename, encoding='cp1251') as f:
raw = f.read()
print(raw[:50])
return raw
def preprocess(text):
tokens = re.split('[^\w-]+', text)
tokens = [word.lower() for word in tokens]
tokens = [re.sub(word, word+' ', word) for word in ... |
86b3ef54e414a4c1dbee10839449bd68bb08e60b | Tatha911/am205_g_activities | /compiled_lang/src/06_matrix_mult.py | 6,473 | 3.796875 | 4 | import numpy as np
import numpy.random as random
import time
# **********************************************************************************************************************
def main():
"""Program to test matrix / vector multiplication in Python"""
# Create a large matrix and a large vector
n: int... |
09f49cb6a35e6ae2775966b1ea39cb543e4b103c | Feinasia/yzu_python | /lesson05/DefDemo06.py | 340 | 3.734375 | 4 | def add(x):
return x + 1
def sub(x):
return x - 1
def operate(func, x): # 函式拿來當參數
return func(x)
x = 10
x = operate(sub, x) # 函式拿來當參數
print(x)
y = 10
y = operate(add, y) # 函式拿來當參數
print(y)
z = [add, sub] #函式陣列
for i in z:
y = 10
y = operate(i, y)
print(y)
|
61c003780fc8ee2b869b76f3bcf7349437bcbc34 | phillipgray/6001x | /PS3P2.py | 700 | 4.09375 | 4 | def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
secretWordList = []
for ch... |
4f3563d5c7111592dd9e51f5c16c0013794826f9 | phillipgray/6001x | /L5P2.py | 297 | 4.09375 | 4 | def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
if exp == 0:
return 1
elif exp == 1:
return base
else:
#print "loop # " + str(exp)
return base * iterPower(base, exp - 1)
#print iterPower(5,3) |
2b924dd456311cdf5d90b79118a68aabc72dffad | phillipgray/6001x | /PS2P2.py | 965 | 4.09375 | 4 | balance = 3926
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
monthlyPayment = 10
monthlyUnpaidBalance = 0.0
testBal = 1.0
def balcheck(balance, annualInterestRate, monthlyPayment):
"""
This function takes a balance (float), annual interest rate (float),
and monthlyPayment (float) and calcu... |
4480983fd6504b80463e5f23f9b9dc1207ddda7b | salomechamma/Hackbright_challenges | /hacker_rank/array_left_rotation.py | 802 | 3.5625 | 4 | def array_left_rotation(a, n, k):
new_array = a[k:] + a[:k]
return new_array
n, k = map(int, raw_input().strip().split(' '))
a = map(int, raw_input().strip().split(' '))
answer = array_left_rotation(a, n, k);
print ' '.join(map(str,answer))
# def check_binary_search_tree_(root):
# return check_bst(root,... |
9b1bf0655dd075db143e352b5265ef1f77e7cff8 | FMSchnetler/PythonCodebase | /Euler/Solved/problem1.py | 353 | 3.875 | 4 | # Multiples of 3 and 5
# Problem 1
# 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.
sum = 0
for n in range(1, 1000):
if n % 3 == 0 or n % 5 == 0:
sum += n
print(... |
aecafe77c50f5f305aef2b824c3caf8751418d87 | ra-g-hul/machineLearning | /HMM/HMM.py | 2,850 | 3.53125 | 4 | '''
@author: raghul
Once the program has identified the model file, it stores the initial model, observation
model and transition model as lists. For each observation sequence, we compute the probabilities.
Once all probabilities have been calculated, we find the most probable state sequence.
'''
from pprint import pp... |
0f12448b1de969eb182653aff42c682245330a44 | cpnota/autonomous-learning-library | /all/agents/_agent.py | 1,355 | 3.953125 | 4 | from abc import ABC, abstractmethod
from all.optim import Schedulable
class Agent(ABC, Schedulable):
"""
A reinforcement learning agent.
In reinforcement learning, an Agent learns by interacting with an Environment.
Usually, an Agent tries to maximize a reward signal.
It does this by observing en... |
e16b2bb94140ea19399a08b3027931bf3f881e7a | lukezitella/chess | /chess/main.py | 58,648 | 3.6875 | 4 | import arcade
import chessGame
import chessDraw
from consts import *
class controller(arcade.Window):
""" Main application class. """
def __init__(self, width, height):
super().__init__(width, height)
arcade.set_background_color(arcade.color.WHITE)
def setup(self... |
63acf79a1ea01221216e3441333fd7982a063940 | Fenrir12/bpnn-ai-intro | /src/MLP_v0.py | 6,789 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import src.numtofeature as ntf
class MLP:
def __init__(self, n_input, n_hidden, n_output, n_layer):
'''Initializes weight matrices with respect to specified number of neurons
for input, hidden and output layer. Also specifies the number of hidden ... |
fa6192cee5ee11b819b8037ad641333ded8f9422 | Bpara001/Python_Assgn | /03 Functions/varargs_start.py | 445 | 4.1875 | 4 | # Demonstrate the use of variable argument lists
# TODO: define a function that takes variable arguments
def addition(*args):
result = 0
for arg in args:
result +=arg
return result
def main():
# TODO: pass different arguments
print(addition(5,10,20,30))
print(addition(1,2,3))
# T... |
d6341107fbabb904caa5815d819a1bafdf2a6b03 | babiswas/Python-Notes | /test_1.py | 678 | 3.859375 | 4 | class A:
value=2
def __init__(self,a,b):
self.a=a
self.b=b
def __str__(self):
return str(self.a)+' '+str(self.b)
@property
def seta(self):
return self.a
@property
def setb(self):
return self.b
@seta.setter
def seta(self,a):
self.a=a
@setb.setter
def ... |
098aab17601732f9480ee82d1b7df88786e1a676 | babiswas/Python-Notes | /dtest4.py | 857 | 3.734375 | 4 | from collections import defaultdict
class Graph:
def __init__(self,n):
self.graph=defaultdict(list)
self.V=n
def add_edges(self,u,v):
self.graph[u].append(v)
def find_all_path(self,u,v):
path=[]
visited=[False]*self.V
self.find_all_path_util(visited,path,u,v)... |
7ca3b61755b382f8547f7cc5fff5d94aa64aa6fe | babiswas/Python-Notes | /Test_18.py | 1,413 | 3.828125 | 4 | from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.vertices=vertices
self.graph=defaultdict(list)
def addedges(self,u,v):
self.graph[u].append(v)
def BFS(self,u):
queue=[]
visited=[False]*self.vertices
queue.append(u)
visi... |
a9d6a52056a1ea8fefd0584854f9e78694a85668 | danielroseman/barnet-school-holidays | /dates.py | 933 | 3.546875 | 4 | import csv
import datetime
def open_data():
return open('data.csv')
def get_dates():
with open_data() as f:
reader = csv.reader(f)
return [(l[0], datetime.datetime.strptime(l[1], '%Y-%m-%d').date(), l[2])
for l in reader if len(l) >= 3]
def get_today():
return datetime.date.today()
def get... |
93fdd65ab4f1904b1b415cfa77495607ab3e5b69 | LapTQ/basic_stuff | /character_frequency/frequency.py | 3,196 | 4.03125 | 4 | class Frequencies:
"""Calculate frequency."""
def __init__(self, data):
"""Calaculate frequency based on a dictionary."""
self._data = data
self._total = self._get_total()
self._result = self._result()
def __getitem__(self, key):
"""Get information about... |
db0fc4cfa98a083dba146d85d2fe1283a9cf3ff7 | LapTQ/basic_stuff | /sub.py | 700 | 3.75 | 4 |
def subset(S, i, sub):
"""Produce a nother subset of S from ith element and given subset sub."""
if i == len(s): # if the last element was reached
print(sub)
else:
subset(S, i + 1, sub) # clone subset of super-subset
subset(S, i + 1, [*sub, S[i]]) # new su... |
a79d0cd63239a2faaee62fe756a78a715bb3d6a4 | kklt92/Intro-to-AI | /Sudoku/SudokuStarter.py | 12,008 | 4.15625 | 4 | #!/usr/bin/env python
import struct, string, math, copy
counter = 0
class SudokuBoard:
"""This will be the sudoku board game object your player will manipulate."""
def __init__(self, size, board):
"""the constructor for the SudokuBoard"""
self.BoardSize = size #the size of the board
self.... |
55eebcb080203b4a93da7018291a4481fd5eb328 | Naitik-bhalala/Codevita--TCS-python-solution- | /codevita/codevita_1.py | 562 | 3.5 | 4 | # find min number of coins required to form any value betwwen 1 to n
#coins are 5,2,1 rupees
coin = int(input("number of coin:"))
list=[ [0,0,0] ,
[0,0,1],
[0,0,2],
[0,1,1],
[0,1,2],
[0,2,1],
[0,2,2],
[0,3,1],
[0,3,2],
[1,1,2],
[1,2,1] ]
if(coin%5<5):
a=int(coin/5)
b=(a-1)*5
d=... |
b9a3bc8f090a35f0a82281027c10a16bba55e677 | NanoRoss/Python-Automation | /Conceptos_Basicos/4_Listas_Tuplas_Diccionarios.py | 1,664 | 4.03125 | 4 | #Lista = ["Mariano","Marcelo","Mauricio","Anita"]
#Tupla = ("Mariano",123,True,"Carlos")
#diccionario_PaisCapital= {"Alemania":"Berlin","Argentina":"Buenos Aires","Francia":"Pais"}
#---------------------------------------------------------------
#Listas
Lista_1 = ["Mariano","Marcelo","Mauricio","Anita"]
print(List... |
7f4dbed7347b3a6dfe7e7a4602c519170f19303e | osidoti/armory-inventory | /inventory.py | 11,639 | 3.625 | 4 | """
Orion Sidoti
inventory.py
Main module for the Flaming Blades Inventory
"""
# imports
import item
import sys
import time
import os
import errno
import operator
# Global constants
MAX_SAVES = 10
# add a single item, taking user input for each property
def addItem(invn):
print("Type of item:\n1 - Clothing or Protec... |
75c47d1ab716b1ed743c627621bd21583eecf859 | ibipul/map-reduce-projects | /Assign1/a1_p2a_islam.py | 2,775 | 3.609375 | 4 | from pprint import pprint
from random import random
import re,string
from pyspark import SparkContext
sc = SparkContext('local', 'Problems 2a')
def word_cleaner(line):
regex = re.compile('[%s]' % re.escape(string.punctuation))
return regex.sub(' ', line)
#################################
# Word Count implemen... |
1c39db8f769764be96e75a7fa8ac4a8840a69609 | mariworld/ds-algos-practice | /singly_linked_list.py | 785 | 3.734375 | 4 | class Node():
def __init__(self, val=None, next=None):
self.val = val
self.next = None
def __str__(self):
return f"{self.val}"
class SinglyLinkedList():
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def push(self, value):
... |
c96cca4372519e446c655a5e573a15bbdad155eb | aouyang1/InsightInterviewPractice | /min_stack_guang.py | 887 | 3.78125 | 4 | class MinStack:
"""
[1, 4, 5, 5, 7, 0, 8]
[1, 4, 5, 5, 7, 8]
"""
def __init__(self):
self.__stack = []
self.__min = []
def push(self, x):
self.__stack.append(x)
if self.min_top() is not None:
if x <= self.min_top():
self.__min.append(x... |
d767516aec4e602a12dea526d43b94a53d8199b9 | aouyang1/InsightInterviewPractice | /merge_austin.py | 950 | 4.03125 | 4 | """
>>> A = [1, 3, 5, 7]
>>> B = [2, 4, 6, 8]
>>> merge(A, len(A), B, len(B))
>>> print A
[1, 2, 3, 4, 5, 6, 7, 8]
>>> A = [1, 2, 10]
>>> B = [3, 4, 6, 8, 12, 15, 19, 200]
>>> merge(A, len(A), B, len(B))
>>> print A
[1, 2, 3, 4, 6, 8, 10, 12, 15, 19, 200]
"""
def merge(A, m, B, n):
""" Merge Sorted Array """
... |
1e932d4f79ca43f053cf5c124785d90b5fd65d71 | aouyang1/InsightInterviewPractice | /reverse_between_austin_NOTDONE.py | 780 | 3.84375 | 4 | """
>>> from DataStruct import Node
>>> head = Node(1)
>>> head.append_data([2, 3, 4, 5, 6, 7])
>>> head.print_values()
1
2
3
4
5
6
7
>>> head = reverse_between(head, 1, 7)
>>> head.print_values()
7
6
5
4
3
2
1
"""
def reverse_between(head, m, n):
""" Reverse Linked List II """
if not head:
return
... |
1a4a6bb55a2fb1b4389deac0cbd0fdba61fdd8cf | aouyang1/InsightInterviewPractice | /remove_duplicates_from_sorted_array_guang.py | 795 | 3.734375 | 4 | def testRemoveDuplicates():
case_1 = [1, 1, 4, 5, 6, 6, 6]
case_2 = [3, 9, 10]
assert removeDuplicates(case_1) == 4
# assert case_1 == [1, 4, 5, 6]
assert removeDuplicates(case_2) == 3
# assert case_2 == [3, 9, 10]
def removeDuplicates(A):
"""
for each element in the list do
if... |
ebc602e16327edd731863cc61d485a874f08e20a | aouyang1/InsightInterviewPractice | /search_range_austin.py | 1,159 | 4.0625 | 4 | """
>>> search_range([1, 2, 4, 5, 7, 7, 7, 8, 8, 8], 8)
[7, 9]
>>> search_range([1, 2, 4, 5, 7, 7, 7, 8, 8, 8], 3)
[-1, -1]
"""
def midpoint(start, end):
return (end-start)/2 + start
def search_range(A, target):
""" Search for a Range """
# find a single target
ptr_l, ptr_r = -1, -1
imin, imax ... |
38ca3b844e84ff98842414284d7438adf13bf243 | aouyang1/InsightInterviewPractice | /min_stack_austin.py | 924 | 4 | 4 | """
>>> stack = MinStack()
>>> stack.push(5)
>>> stack.push(1)
>>> stack.push(2)
>>> stack.push(3)
>>> stack.push(7)
>>> stack.push(4)
>>> stack.top()
4
>>> stack.pop()
>>> stack.top()
7
>>> stack.get_min()
1
>>> stack.pop()
>>> stack.get_min()
1
>>> stack.pop()
>>> stack.get_min()
1
>>> stack.pop()
>>> stack.get_min()... |
6b9269da48a19f8c6ada789ec184ee86c75cd08b | kovardhan/kovardhan | /SIMPLY3.py | 558 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 9 20:15:57 2021
@author: k
"""
from SIMPLY import *
p=[]
name=str(input("please enter your name: "))#my name is kovardhan.R.R
rollno=str(input("please enter the rollno: "))
name=list(name)
rollno=list(rollno)
print(name,rollno)
def huffmanoutputs(a,t=""):
... |
3737e6a24ba6fac797618c75dd4aedeace5f5984 | ghk829/kaggle | /study/notebook/2_26/practice.py | 252 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 16 16:44:35 2018
@author: 80504
"""
with open("words.txt",'r') as f:
line = f.readline();
while line !="":
word = line.rstrip()
print(len(word));
line = f.readline();
|
b14861d7631d0fa22f082bfc1e970bd9b1ba54c6 | MakeSureToKnock/Basics | /Exp3.py | 484 | 4.03125 | 4 | #Ask for a word using input() and convert it to binary and hex
word = input('Enter a word: ').split()
del word[1:]
string = word[0]
ordList = []
hexList = []
binList = []
for i in range(len(string)):
value = ord(string[i])
ordList.append(str(value))
hexValue = hex(value)
hexList.appen... |
504e64c3d0be1d03c044c54594c9af6785539da2 | samsnarrl22/Beginner-Projects | /Song Variables.py | 1,116 | 4.28125 | 4 | # Storing attributes about a song in Variables
# First create variables for each of the characteristics that make up a song
title = "Ring of Fire"
artist = "Jonny Cash" # These variables are strings which can be seen due to the ""
album = "The Best of Johnny Cash"
genre = "Country"
time_in_seconds = 163 # time_in_se... |
752f7f1371239211fcc2a0fe21f11e8f2f0307f8 | mehdi-ichka/algorithms | /Python algo/strings/5-palindrome.py | 325 | 3.78125 | 4 | import re
class Solution:
def isPalindrome(self, s: str) -> bool:
s = re.sub(r'[^a-zA-Z0-9]*', '', s).lower()
for i in range(len(s)):
if s[i] != s[len(s)-1-i]:
return False
return True
s = "A man, a plan, a canal: Panama"
sol = Solution()
print(sol.isPalindrom... |
cc25ba6121253a03e3e0a95f25c43579e000d889 | BobKat99/RPiPWM- | /ultrasonic.py | 1,241 | 3.765625 | 4 | #import libaries
import RPi.GPIO as GPIO
import time
#set up the mode
GPIO.setmode(GPIO.BCM)
#set up pin
TRIG = 23
ECHO = 17
LED = 20
#set up input output
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.setup(LED, GPIO.OUT)
#function to calculate the distance
def distance():
GPIO.output(TRIG, True)
... |
984863b3ccb43eb11025cd1aae499deee7d6acec | sicp/ikoma-sicp | /oza/2/2-17,23.py | 1,132 | 4.125 | 4 |
# last_pair
#class mytuple:
#
# def __init__(self, t):
# self.tpl = t
#
# def car(self):
# return self.tpl[0]
#
# def cdr(self):
# return self.tpl[1:]
#
# def last_pair(self):
# # return (self.tpl(-1),)
# l = len(self.tpl)
# return (self.tpl[l-1],)
#
# def __str__(self):
# return str(self.tpl)
#
#t = mytuple((... |
1de918317b8fa6fce28fc20b1e415148372d9ca6 | hummans/poker-game | /tests/test_hands.py | 8,138 | 3.6875 | 4 | #!/usr/bin/env python2
"""
Test Hands
==========
Test that the Hands functions correctly identify hands.
"""
import sys
import os
# Adds the path of poker_game to test file.
sys.path.append(os.path.join(os.path.dirname(__name__), '..'))
import unittest
from poker_game import hands
class TestHands(unittest.TestCase)... |
b8da14adbb161f5a671ca765c72354aff8a0db0e | revanthp/DSA | /python/array.py | 1,954 | 3.78125 | 4 |
# find all pair of numbers that sum up to given value from 2 arrays.
def find_all_pairs(x, sum_):
# worst case:
# O(nlogn * n)
# space:
# O(1) for heap sort
# O(n) for merge sort
x_sorted = sorted(x)
left_index = 0
right_index = len(x_sorted) - 1
out = []
while left_... |
eccf8f98a117ee065e68b87c7832a2901a29d6bf | Tolgino/cryptocurrency-manipulation-detection | /data/market.py | 1,552 | 3.53125 | 4 | import matplotlib.pyplot as plt
import yfinance as yf
from datetime import datetime, timedelta
def pull_coin_history(coin, start, end, resolution):
"""
:param coin: The common abbreviation of the requested coin as a string.
:param start: "datetime" object indicating the starting point of the requested dat... |
b3ab609d58590710bb5c1dd15a99e0238267fde6 | subburamr/advent-of-code-2020 | /day-3/day_3.py | 1,467 | 4.0625 | 4 | """Day 3 solution."""
from collections import defaultdict
from typing import DefaultDict
def load_map(input_file):
"""Read a file line by line and store it in dict.
Parameters
----------
input_file : str
input file containing map
Returns
-------
DefaultDict[Dict]
Dict rep... |
cb9b61935cba53d62c80a87fdd2936c7bf080112 | kevinelong/bo | /main9.py | 3,284 | 3.609375 | 4 | import time
class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
class Size:
def __init__(self, width, height):
self.width = width
self.height = height
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
class Box:
def __init__(self, origin:Coordinate, box_size:Size):
self.origi... |
8fd32545198a7e63207d52fd8cb49d16f2864511 | sinanh/python_alistirmalar | /Stringler/lab_4.py | 304 | 3.921875 | 4 | import sys
def findUpper(s):
if s.isupper():
return True
return False
if __name__ == '__main__':
print("enter city name: ", sys.argv[0])
if findUpper(str(sys.argv)):
print('girilen kelimelerde buyuk harftir')
else:
print('girilen kelimelerde kucuk harftir')
|
95cdcb2eb072e84df6f96f022cc4e7801ed8375f | MissaelSanchezVillegas/Dise-oDeAlgoritmos | /Tarea 6/MCD.py | 390 | 3.8125 | 4 | #Algoritmo de Euclides (divide y venceras)
#parametros
A=84
B=33
def euclides(a,b):
print("A,B",a,b)
if(a==b):
return a
elif(a>b):
c=a//b
r=a-c*b
print("r,c",r,c)
if(r==0):
return b
else:
b=euclides(b,r)
return b
else:
c=b//a
r=b-c*a
if(r==0):
return a
else:
... |
5742ae44ffd94ee2fbc38485e3b2969d7f6a3f19 | MissaelSanchezVillegas/Dise-oDeAlgoritmos | /Ejercicios/quicksort.py | 765 | 3.609375 | 4 | #quicksort
from random import random
costo=0
def qs(array):
global costo
if(len(array)==2):
costo += 1
return sorted(array)
if(len(array)<2):
return array
mayores=list()
menores=list()
pivote=array.pop(len(array)-1)
for x in array:
if(x<pivote):
costo +=1
menores.append(x)
else... |
5656d54460e0742abd2340bbcd6e61024858e0d7 | Zaliann/practice | /практика 2/lab2-2.py | 1,023 | 4.4375 | 4 | # Целые числа и числа с плавающей точкой являются одними из самых распространенных в языке Python
number = 9
print(type(number)) # Вывод типа переменной number
float_number = 9.0
# Создайте ещё несколько переменных разных типов и осуществите вывод их типов
lenn = 2.4
snake = 4
stroch = "Площадь - произведение дли... |
9de7bdb51de0b8708c67f901ba9b1be8be22b8c1 | slnrao/learn_proj1 | /prac2/prac_git1.py | 741 | 3.671875 | 4 | '''
Created on 26 May 2018
@author: laxminarayan rao
'''
#import os
x = raw_input('enter name of the file :')
f = open(x,'w')
print 'enter data in to file:',x
while True :
data = raw_input()
if data in 'Qq' : break
f.write(data)
f.write('\n')
f.close()
import os
xsx = raw_in... |
efc3a3d11fa69279d4e1e750479dbed8832594d0 | godofwharf/AIND-Isolation | /game_agent.py | 28,049 | 3.546875 | 4 | """Finish all TODO items in this file to complete the isolation project, then
test your agent's strength against a set of known agents using tournament.py
and include the results in your report.
"""
import random
import copy
class SearchTimeout(Exception):
"""Subclass base exception for code clarity. """
pass
... |
58a58265c16c372605db585e00fb46679355c254 | NamDaoVuHoang/Bai-TH-1 | /src_py/KT14_2.py | 1,441 | 3.9375 | 4 | def quickSort(a_list):
quickSortHelper(a_list, 0, len(a_list)-1)
def quickSortHelper(a_list, first, last):
if first < last:
split_point = partition(a_list, first, last)
quickSortHelper(a_list, first, split_point - 1)
quickSortHelper(a_list, split_point + 1, last)
def partition(a_list... |
3d6b0865f5ac56ab156ef0f8c7bc7702f6167872 | NamDaoVuHoang/Bai-TH-1 | /src_py/KT16_2.py | 317 | 3.6875 | 4 | i = 2
while i < 100:
if i == 2 or i == 3:
print(i, " la so nguyen to")
j = 2
while j <= (i / j):
if not i % j:
break
j += 1
if j > i / j:
print(i, " la so nguyen to")
# i phải nằm ở vòng while ngoài
i += 1
print("Good bye!")
|
24cc451c8d1767fa3d4eea0fb3a919e24f9b95f4 | cph0r/gl_assessment | /main.py | 1,931 | 3.59375 | 4 | import random
from player import Player
from utils import displayRankings, initiateGame, simulateDiceRoll, skipTurn, sumOfLastPoints, takeInputs, updateRanks
from constants import *
def startGame():
players, maxPoints = takeInputs()
# Initialise values
player, unranked = initiateGame(players)
winners ... |
85b347059b48865c778c58db3b9152add9e01fe4 | rahul-testpress/PracticePython | /Password Generator.py | 406 | 3.921875 | 4 | import random
import string
strong_password_letters = string.ascii_letters + string.punctuation + string.digits
choice = input("Enter the type of password required : Press W for weak or S for strong : ").upper()
if choice == "W":
print("".join(random.sample(string.ascii_letters, 6)))
elif choice == "S":
print(... |
613b1e6acd914bd36a9e74162f34e523c7bac9c0 | rahul-testpress/PracticePython | /List Overlap.py | 410 | 3.84375 | 4 | import random
a = []
b = []
for i in range(0, 25):
# add random values to the lists
a.append(random.randint(0, 100))
b.append(random.randint(0, 100))
common_elements_list = set()
for i in a:
if i in b:
common_elements_list.add(i)
print("List 1 : {}".format(a))
print("List 2 : {}".format(b))
pri... |
4d6bfba54ebde4f3cf74de9228ba1ae1fa07d1aa | she-ze/ML | /draw sigmoid function/hello.py | 104 | 3.515625 | 4 | print("Hello python")
ls = list(range(5))
print(ls)
a = 'aaaabbbcc'
b = a.replace('a', "A", 2)
print(b)
|
c57b5b2d2a7e7b6948c222c5575dd5f067f6d3e7 | richardjs/dashwood | /src/dashwood/state.py | 3,352 | 3.8125 | 4 | '''State representation and operations
The most basic state representation is a 3-tuple, defined as:
[0] pieces on board
[1] inverse of pieces on board
[2] the next piece to be placed
[1] is not ~[0]. Rather, it is the inverse of the *pieces* on the board.
The inverse calculation is performed when the pie... |
2fe3308b11a2a1b02f46a64513509cf85d993ddc | Lucythefirst/Guessing-Game | /test.py | 612 | 3.515625 | 4 | import unittest
import guessing_game
class TestGame(unittest.TestCase):
def test_input(self):
result = guessing_game.run_guess(5, 5)
self.assertTrue(result)
def test_input_wrong_guess(self):
result = guessing_game.run_guess(0, 5)
self.assertFalse(result)
def te... |
daf89a4fb1d8756b4c32f7dc88e30274248c194a | olivasd/Intro-to-Computer-Networks | /Project 1/chatserve.py | 1,449 | 3.515625 | 4 | # Daniel Olivas
# CS 372 Program 1
# 10/29/2017
# chatserve.py
from socket import*
import sys
def main():
serverPort = sys.argv[1]
hostName = 'ChatServer'
serverHost = '127.0.0.1'
# create TCP welcoming socket
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((serverHost, int(serverPort)))
#begin ... |
6f9e688d2461ed73ad10347029c547bfa769740e | Andresdamelio/master-python | /06 - Herencia/ejercicio.py | 2,704 | 3.953125 | 4 | """
======================================================================
Ejercicio
======================================================================
"""
class Vehiculo():
def __init__(self, color, ruedas):
self.color = color
self.ruedas = ruedas
def __str__(self):
retur... |
fe7e22bfd1dac7b4c1bf88c09e7cf02eed311563 | Andresdamelio/master-python | /08 - Funcionalidades avanzadas/funcion-map.py | 1,707 | 4.15625 | 4 | # encoding: utf-8
"""
==============================================================================================
FUNCION MAP
==============================================================================================
"""
# Trabaja de forma similar a filter, a diferencia de que en lu... |
f66969d71e58004f000e966988c4ec81dd9679ad | Andresdamelio/master-python | /08 - Funcionalidades avanzadas/funcion-filter.py | 1,828 | 4.5 | 4 | # encoding: utf-8
"""
==============================================================================================
FUNCION FILTER
==============================================================================================
"""
# Tal como su nombre lo indica su funcion es filtrar, a par... |
80ff22bf321c958b2b71b97a0c2eada9d23a9bf3 | Andresdamelio/master-python | /02 - Entrada y salida/salida.py | 2,950 | 4.125 | 4 | """
======================================================================
Salida de datos
======================================================================
"""
v = "otro texto"
n = 10
print("un texto", v, "y un numero", n)
# Para evitar escribir muchos print, e ir colocando variables separadas por una com... |
b6a30271fa2adfcb89ae1b1fb658fdeae0dce67c | Andresdamelio/master-python | /08 - Funcionalidades avanzadas/compresion-listas.py | 2,669 | 4.5625 | 5 | # COMPRESION DE LISTAS
# Es una forma de optimizar las lineas de codigo al crear una lista de elementos
'''
======================================================================================================
CREANDO UNA LISTA CON LAS LETRAS DE UNA PALABRA
================================... |
88812cfba755cc4b06a8724ea3def8d51f18dd68 | JinHoChoi0104/Python_Study | /Inflearn/chapter05_02.py | 850 | 4.21875 | 4 | # Chapter05-02
# 파이썬 사용자 입력
# Input 사용법
# 기본 타입(str)
# ex1
# name = input("Enter Your Name: ")
# grade = input("Enter Your Grade: ")
# company = input("Enter Your Company name: ")
# print(name, grade, company)
# ex2
# number = input("Enter number: ")
# name = input("Enter name: ")
# print("type of number", type(num... |
a4261310d3f9f7b99f3089289ad508c5727b3786 | sarbjit87/sqlalchemy_tutorial | /one_to_many.py | 1,834 | 4 | 4 | """
Example for One to Many Relationship using SQLAlchemy
"""
from sqlalchemy import Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
Base = declarati... |
bdb3112e04f099545a59955017823b1937ba75b2 | Hokwan-Cho/python_study | /string.py | 1,003 | 4 | 4 | def add(a,b):
return a+b
print( add(3,4))
num = 3
if num > 1 :
print("num is greater than 1")
for a in [1,2,3] :
print(a)
a = 1E9
print(a)
a = '=' * 50
print(a)
print("test test")
print(a)
a = "Life is too short"
print(len(a))
print(a[3])
print(a[0] + a[1]+ a[2] + a[3])
print(a[0:4])
print(a[0:... |
222e80bb6e326c8c82ac20a4668fd215dc4a59b1 | Hokwan-Cho/python_study | /dictionary.py | 654 | 3.859375 | 4 | dic = {'name':'조호관', 'phone':'010-4686-7423', 'birth': '920423'}
print(dic)
print(dic['name'])
print(dic['phone'])
print(dic['birth'])
del dic['name']
print(dic)
print(dic.keys()) # 리스트가 아닌 객체 반환
dic['name'] = 'Hokwan Cho'
for k in dic.keys():
v = dic[k]
print(f"key is {k} , value is {v}")
# dic_ke... |
8e27ac9bb30f6f9b6da11cb8934400d722c38a87 | shenghaozou/taDebug | /main.py | 3,051 | 4.6875 | 5 | import project
import math
# Insert getMaximumLand(stateName1, stateName2, stateName3) function here
# Step1: Retrieve area values for all 3 states using getArea function and assign it to variables.
# Step2: Use max() function to calculate the max value and store it as a variable
# Step3: Return the max value th... |
563691b7acf4e91e96a8dd4b41928cf738d95ef0 | echocatzh/Multi-client-chat-room | /cipher_dh.py | 2,662 | 3.5625 | 4 | import random
def fastExpMod(b, e, m):
"""
e = e0*(2^0) + e1*(2^1) + e2*(2^2) + ... + en * (2^n)
b^e = b^(e0*(2^0) + e1*(2^1) + e2*(2^2) + ... + en * (2^n))
= b^(e0*(2^0)) * b^(e1*(2^1)) * b^(e2*(2^2)) * ... * b^(en*(2^n))
b^e mod m = ((b^(e0*(2^0)) mod m) * (b^(e1*(2^1)) mod m) * ... |
74ed4ee2073ef621dfc8c0ac410d41aebeb30905 | rajuneduri/chatbot | /Evening.py | 2,345 | 3.984375 | 4 | def eve_amount(choosen_integer):
if choosen_integer==3:
print("Ho! Great ,Please Select your rides.")
print()
eve_programs=['1.Roller coaster','2.Gaint Wheel','3.Planitary Model']
print()
for i in eve_programs:
print(i)
print("Please e... |
5b7e5fa9eee245f80870de864957a3bec381d311 | n-yuen/ares-communication-temp | /build.py | 2,317 | 3.796875 | 4 | #!/usr/bin/env python3
import sys
import os
from typing import List, Tuple
from struct_codes import STRUCT_CODES
def capitalizeFirstChar(s: str):
return s[0].upper()+s[1:] # when they tell you it's just like pseudocode
FILE_PATH = os.path.abspath("./data_order.csv")
PYTHON_GEN_PATH = os.path.abspath("./base/gen.p... |
4d0e3312dac1aefc7020b6588c1fdc5e1141c457 | KingaMilaszkiewicz/passwordStorage | /passwordStorage.py | 3,183 | 3.640625 | 4 | import sqlite3
import base64
import os
import PyQt5
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
conn = sqlite3.connect("passwords.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS... |
531092070347dea686f04750afe7906073c467b5 | fwangccnu/AILDE | /packages/result/extract4Hinfo.py | 3,113 | 3.640625 | 4 | #!/usr/bin/python
import decimal
def extract4Hinfo(Hno,infile,subdictionary):
'''
--------------------------------------------------------
'extract4Hinfo' is used to get a dictionary which is about Hydrogen number
usage: extract4Hinfo(Hno,infile)
input : Hno - the Hydrogen number you want to extract i... |
382d4c999a6bc5ddb098e20f3cc95c65fc83d578 | fwangccnu/AILDE | /packages/initialization/gen4replacelist.py | 2,394 | 3.546875 | 4 | #!/usr/bin/python
def gen4replacelist(hydrogen_list,fragment_file):
'''
--------------------------------------------------------
'gen4replacelist' is used to generate the file 'replacelist.prm' for SPECIFYING the REPLACE SITES and SUBSTITUENTS TYPE!
usage: gen4replacelist(hydrogen_list,fragment_file)
i... |
bf15aed8c32af17cfac1696c6d2b7e9dbeca65f1 | maxwell-schwartz/CoinProblem | /CoinProblem.py | 1,368 | 3.84375 | 4 | def makeChange(amnt):
'''Make change with the smallest number of coins'''
# All the values of coins
values = [1, 5, 10, 25]
# Dictionary to keep track of the smallest count for each value up to
# and including amnt
# Keep track of the combo of coins as well
full_chain = {val : {'co... |
d09c06804e8f4d640c171af5eba64669739c8e05 | Chasestanley000/Wav-to-Pulse-conversion | /convert_wav.py | 5,431 | 3.875 | 4 | #!/usr/bin/env python3
"""
read a wav file and convert it into a series of
high/low time values as a representation for beat lengths.
Once that information is extracted create an html file to vibrate to that pattern
"""
import argparse
import soundfile as sf
def convert_wav(wav_filename):
"""
:pa... |
60ec60bf0abba66cb556912ef1f3250f3ffccafa | HamplusTech/PythonFunctions | /EvenlyDivisibleElement.py | 260 | 4 | 4 | def evenlyDivisibleElement (x, y=list()):
'''This function prints out the list of integers that
evenly divide an integer from a list of integer'''
a = list()
for i in range(len(y)):
if x % y[i] == 0:
a.append(y[i])
return a
|
343b94d77dbed5972daa8dcbd2e0e93842a7bfa8 | eshaptelang/AMC10_2015 | /problem2.py | 885 | 3.84375 | 4 | # This is the second problem of the 2015 AMC 10. In this problem, we had to figure out how many squares and triangles
# there were if we were given 84 sides and 25 shapes. For this problem, we need to import numpy because it is a python
# package for scientific computing. Of course there are other ways to solve simulta... |
ea36bd5cdad3338f6d39f40aea0ff2ce643871b7 | eshaptelang/AMC10_2015 | /problem3.py | 743 | 4 | 4 | # This is the third problem of the 2015 AMC 10. In this problem, I had to figure out how many additional toothpicks we
# would need to get 5 steps, if 3 steps needed 18 toothpicks. I first found the equation 2 * steps + 2 equalled the
# amount of toothpicks added each time. Then I made a function to be able to find the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.