blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
7d8c3b9275e053030e3502e2eec85047990c3b7d | AnnanShu/LeetCode | /121-140_py/128-longestConsecutiveSequence.py | 1,106 | 3.921875 | 4 | '''
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
'''
## easiest way to solve this question
# Time complexity: O(n^3)
# class Solution:
# def longestConsecutive(self, nums: list) -> int:
# longest = 1
#
... |
a03c563dd977fcb466d5b9e31af8c8eb7bc31bfe | AnnanShu/LeetCode | /101-120_py/121-bestTimeToBuyAndSell.py | 932 | 3.875 | 4 | """
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
著作权归领扣网络所有。商业转载请联系官方授权,非... |
6d2651779dd79900da0b64a430f6d0d682ba3feb | AnnanShu/LeetCode | /141-160_py/154-_.py | 982 | 3.875 | 4 | from typing import List
class Solution:
def minArray(self, numbers: List[int]) -> int:
n = len(numbers)
def auxiliary_func(start, end, numbers):
if end - start > 1:
mid = (start + end) // 2
if numbers[start] >= numbers[mid]:
... |
2952cee470906607856723bf15837f7373ea62b3 | AnnanShu/LeetCode | /1-20_py/11_containerWithMostWater.py | 1,092 | 3.671875 | 4 | """Question Description
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which
together with x-axis forms a container, such that the container contains the mo... |
20a4c2cb4a925305615adc50fa8819a9c217a270 | AnnanShu/LeetCode | /300-400_py/312-Bollon.py | 1,065 | 3.625 | 4 | '''
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it
represented by array nums. You are asked to burst all the balloons. If the you burst
balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right
are adjacent indices of i. After the burst, the left a... |
f6dd2acfd8302028d4fb2178f836c75db5e0ce86 | AnnanShu/LeetCode | /800+_py/1642-FurthestBuilding.py | 597 | 3.5625 | 4 | import heapq
from typing import List
class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
i, n = 0, len(heights)
height_differs = [0] + [heights[i + 1] - heights[i] if heights[i] < heights[i+1] else 0 for i in range(n - 1)]
# print(height_di... |
cfc51aed6e8a10637b22720ed0b7d26c351eddcc | AnnanShu/LeetCode | /81-100_py/98-validateBST.py | 1,073 | 3.828125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# class Solution:
# def isValidBST(self, root: TreeNode) -> bool:
# if root.left and root.right:
# if root.left.val < root... |
26334cbc692965fc28aa71f21bfa93b2eff0bf95 | DaruriDheeraj/DheerajCodes | /Pattern.py | 245 | 3.890625 | 4 | n=int(input())
p=(3*n)+(2)
for i in range(1,p+1):
if i%3==0:
for j in range(5):
print('*',end="")
else:
print('*',end="")
for i in range(1,4):
print(end=" ")
print('*')
print()
|
e50a68bfc19991a2fb9d06b0a505dd4dc574e0d8 | xndong/ML-foundation-and-techniques | /K-NN/knn.py | 1,032 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed June 25 21:39:34 2019
@author: DongXiaoning
"""
import numpy as np
def minkowski_distance(x1,x2,distance = "euclidean"):
if distance =="euclidean":
sub = np.subtract(x1,x2)
square = np.dot(sub,sub)
return np.sqrt(square)
elif dist... |
cabd056459f49ee5fafe7532f0227b32f8f8e9dc | manangoel99/Snake | /3.py | 2,452 | 3.6875 | 4 | import pygame
displayheight = input("Enter Height of Screen")
displaywidth = input("Enter Width of Screen")
pygame.init()
#Make Surface and give name to it
displayheight = int(displayheight)
displaywidth = int(displaywidth)
gameDisplay = pygame.display.set_mode((displaywidth,displayheight))
pygame.display.set_caption('... |
f2c9a7845fa63ef89530d6acd1e8aeb843c80073 | Gabe-flomo/Filtr | /Filtr/externals/database.py | 878 | 3.828125 | 4 | import sqlite3
<<<<<<< HEAD
import pathlib
# create a database table
# add data to the table
# get data from the table
# update database
# add more tables
class Database():
''' this is a database object that when instanciated
should be the name of the database its representing.
For example:
... |
ba3b85ec95dc22ecb4c91ada9c2f61512e5359ea | Gabe-flomo/Filtr | /GUI/test/tutorial_1.py | 1,950 | 4.34375 | 4 | from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
''' tutorial 1: Basic gui setup'''
# when working with PyQt, the first thing we need to do when creating an app
# or a GUI is to define an application.
# we'll define a function named window that does this for us
def window... |
256c8ec9195f10e9f05c14a62db1188bd34bf16e | ShipraDureja/ml | /Assignment 3/perceptron.py | 2,758 | 3.75 | 4 | #!/usr/bin/env python3
"""
[Monday 13-15] ML Programming Assignment 3
Tarun Gupta, Shipra Dureja
Command to run this batch gradient descent model:
python3 perceptron.py --data <filepath> --output <output file>
Input: tsv File
Output: tsv File
"""
import argparse
import csv
import numpy as np
def main():
args = ... |
113f8e8555c1bd20ae4dc1629821cec54446701d | paniash/progs | /python/pi.py | 157 | 3.5625 | 4 | # Code to calculate the value of pi using Wallis' method
ssum = 1
for i in range(1,10000):
ssum = ssum*((4*i**2)/(4*i**2-1))
print("Pi:", 2*ssum)
|
29dc6bfe97e2fec5699b8af96c1122c5d8b25c02 | paniash/progs | /code/class.py | 2,027 | 3.625 | 4 | #%%
class Person:
def __init__(self, firstname, lastname, age, country, city):
self.firstname = firstname
self.lastname = lastname
self.age = age
self.country = country
self.city = city
self.skills = []
def person_info(self):
return f'{self.firstname} {se... |
04f58452e7c9580fafdc02b57386aa1c6d7c4b7e | paniash/progs | /python/bisec.py | 314 | 3.765625 | 4 | def f(x):
return x**2 - 1
def bisection(a, b, tol):
xl = a
xr = b
while (abs(xl-xr) >= tol):
c = (xl+xr)/2.0
prod = f(xl)*f(c)
if prod > tol:
xl = c
elif prod < tol:
xr = c
return c
answer = bisection(0, 3, 1e-8)
print("Num:", answer)
|
71cd81af30f614cab37548b0a1e01891c9eeec5c | ramarahmanda/Intern-kata.ai | /models/Marriage.py | 1,071 | 3.84375 | 4 | import time
class Marriage(object):
"""
Marriage class sebagai model
untuk mengetahui atribut dari
tabel marriage
"""
# constructor awal
def __init__(self, id, husbandId, wifeId, startDate, endDate):
self.id = id
self.husbandId = husbandId
self.wifeId = w... |
f610d516a540b1af6c50957a53b94b284a9b19fb | adityakumar13090123/learning | /algorithm_data_structure/tree/print_path_from_root_to_leaf.py | 742 | 3.828125 | 4 | class Node:
def __init__(self,key):
self.left = None
self.right = None
self.data = key
def print_path(root, path):
path.append(root.data)
if root.left is None and root.right is None:
print path
return
if root.left:
print_path(root.left, path)
pa... |
031444bf18fba06fb2569caf68309eeeec07908a | adityakumar13090123/learning | /algorithm_data_structure/tree/left_view.py | 818 | 3.84375 | 4 | from collections import deque
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def leftView(root):
if not root:
return
que = deque()
que.append('#')
que.append(root)
while... |
2c1005db3560d777334a90cdad0be940cb56eaa5 | judgyknowitall/DataBaseProject | /venvProject/apis/helpers/payment.py | 1,435 | 3.53125 | 4 | # Payment Helper funtions
# returns all current payments
def getAll_payments():
sqlCommand = 'SELECT * FROM payment'
return sqlCommand
# Used to create a new payment
def new_payment(amount, sid, tid, first=False):
# Not 1st item in payment table
if not first:
sqlCommand = 'INSERT INTO paymen... |
3fdc657e1eb169ecb0ea0add3bd40d32d493f875 | scwilbanks/tictactoe | /tictactoe.py | 1,907 | 3.9375 | 4 | """
Simple Tic Tac Toe game in Python
"""
def newgame():
"""
Returns empty playing field.
"""
return [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
def getmoves(game):
"""
Returns all possible moves.
"""
moves = set()
for i in range(9):
if game[i] == ' ':
... |
9885313c7b2542cdbd6612450fbac37d09c2dbf7 | DuanShengqi/tf2_notes | /class1/p39_softmax.py | 258 | 3.671875 | 4 | import tensorflow as tf
y = tf.constant([1.01, 2.01, -0.66])
y_pro = tf.nn.softmax(y)
print("After softmax, y_pro is:", y_pro) # y_pro 符合概率分布
print("The sum of y_pro:", tf.reduce_sum(y_pro)) # 通过softmax后,所有概率加起来和为1
|
75f4e3cd2ccfe294c9940f3cc7332c3626dcb139 | Muhammad-Yousef/Data-Structures-and-Algorithms | /Stack/LinkedList-Based/Stack.py | 1,303 | 4.21875 | 4 | #Establishing Node
class Node:
def __init__(self):
self.data = None
self.Next = None
#Establishing The Stack
class Stack:
#Initialization
def __init__(self):
self.head = None
self.size = 0
#Check whether the Stack is Empty or not
def isEmpty(self):
retur... |
e06407114fa163919d0c48f142f59832a88a87f9 | Muhammad-Yousef/Data-Structures-and-Algorithms | /LinkedLists/Circular-Singly-LinkedList/CircSinglyLinkedList.py | 2,945 | 3.96875 | 4 | class Node:
def __init__(self):
self.data = None
self.Next = None
class CircSinglyLinkedList:
def __init__(self):
self.head = None
self.size = 0
#Check whether the list is Empty or not
def isEmpty(self):
return self.head == None
#Traversing The List
d... |
43f674a715ad3f044bc2a5b406dc3b5edabe1323 | DoozyX/AI2016-2017 | /labs/lab1/p3/TableThirdRoot.py | 838 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Table of third root Problem 3
Create a table with third root so that the solution is a dictionary where the key is the integer and the value is the third root of the integer.
The keys should be numbers whose third root is also an integer between two values m and n.
or a given input, print ou... |
d82d4f8846df9e5431782f3d12d086179c2e05fa | SnowMasaya/python-algorithm | /python_algorithm/LinkedList/adding.py | 2,260 | 3.859375 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from LinkedList import LinkedList
def addLists(l1: LinkedList, l2: LinkedList, carry: int) -> LinkedList:
"""
Add two list
For example
7 -> 1 -> 6
+ 5 -> 9 -> 2
2 -> 1 -> 9
:p... |
ebdb3ad993c31e10d353e71e3753645ac7540bd0 | SnowMasaya/python-algorithm | /python_algorithm/LinkedList/find_intersection.py | 1,281 | 3.734375 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from LinkedList import LinkedList
import math
class Result(object):
def __init__(self, tail: LinkedList, size: int):
self.tail = tail
self.size = size
def find_inter_section(list1: LinkedList, ... |
cfc70b8c949faa9f65f4769241cb9209a92f6a29 | li-lauren/dicts-word-count | /wordcount.py | 839 | 3.625 | 4 | # put your code here.
import re
import sys
import collections
text = open(sys.argv[1]).read().lower()
text = re.split('\.| |\n|,|\?', text)
dict_words = {}
for word in text:
dict_words[word] = dict_words.get(word, 0) + 1
# using collections.Counter
cnt = collections.Counter()
for word in text:
cnt[word] += ... |
b2d47673c7c0fc43a1c5b6606ba4352ea18579ec | cclark31415/PrimeFinder | /PrimeFinder.py | 1,255 | 3.859375 | 4 | import numpy as np
import time
def formatTime(secs):
if secs <= 60:
return str(secs)
else:
days = secs//86400
hours = (secs - days*86400)//3600
minutes = (secs - days*86400 - hours*3600)//60
seconds = secs - days*86400 - hours*3600 - minutes*60
result = ("{0} day... |
9c40a0e1e7939411997ef1475c034faea20bdae3 | LyaminVS/2021_Lyamin_infa | /turtle2/ex24.py | 1,905 | 3.71875 | 4 | from random import randint
import turtle
time = int(input("Время: "))
number = int(input("Количество черепах: "))
size = float(input("Размер: "))
gas = bool(int(input("Реальность газа: ")))
const = int(input("Сила отталкивания (притяжения): "))
class Particle:
def __init__(self, turtle, x=0, y=0, speedx=50, spe... |
3a480a24ad9fa9ea7c2584808165483c7d6e9834 | LyaminVS/2021_Lyamin_infa | /turtle2/ex22.py | 876 | 3.5 | 4 | import turtle
inp = list(input())
turtle.shape('turtle')
turtle.speed(0)
n = 0
f = open('/Users/vasilij/pylabs/pythonProject/nums')
numbers = [line for line in f]
f.close()
turtle.penup()
turtle.goto(-300, 0)
turtle.pendown()
for j in range(len(numbers)):
numbers[j] = numbers[j].split(',')
for k in range(len(... |
6f6a521a987fe897b30815712a6ab76e07429448 | Deepak2094/DSS-REALESTATE | /Deliverables/Modules/format_Listings.py | 2,599 | 3.625 | 4 | """ This file conatins the user defined function to format the Listings for Landing Page """
import random
import pandas as pd
def random_phone_num_generator():
first = str(random.randint(100, 999))
second = str(random.randint(1, 888)).zfill(3)
last = (str(random.randint(1, 9998)).zfill(4))
while last... |
841cb2408de06c13197a969b3c8db35bfe9f4082 | balakrishnanfayas/Guvi-Beginner | /prime number.py | 154 | 3.703125 | 4 | a=int(input())
b=0
for i in range(1,a+1):
if(a%i==0):
b=b+1
if(b==2):
print("yes")
else:
print("no")
|
0f70c1c3d5e3d0a194e06e7d16386ecc915b2fbe | balakrishnanfayas/Guvi-Beginner | /armstrong number.py | 173 | 3.75 | 4 | a=int(input())
temp=a
su=0
while(temp>0):
r=temp%10
su+=r**3
temp//=10
if(a==su):
print("yes")
else:
print("no")
|
6c10408a7ec4d1b4dde9aa742ae0b59deaaa5a25 | moh-patel/Data_Structures | /selection_sort.py | 594 | 3.796875 | 4 | def selection_sort(arr):
size = len(arr)
pos = 0
for i in range(size):
for x in range(pos,size):
if arr[x] < arr[pos]:
arr[x],arr[pos] = arr[pos], arr[x]
pos +=1
arr = [78, 12, 15, 8, 61, 53, 23, 27]
if __name__ == '__main__':
tests = [
... |
f9587e80f66c5ca93035e07eb90dc691c3bc437d | utkarshshende2596/python | /Decorator.py | 1,284 | 3.828125 | 4 | from functools import wraps
def decorator_fun(outer_funtion):
def wrapper_fun(*args,**kwargs):
print(" wrapper Before calling in {}".format(outer_funtion.__name__))
return outer_funtion(*args,**kwargs)
return wrapper_fun
#
# def decorator_class(outer_funtion):
# def __init__(self,outer_funt... |
4e43b09bebbefcb122087287fb72dde1c4abf612 | atehortua1907/Python | /Platzi/Platzi.py | 724 | 4 | 4 | import turtle
#por cada lado del cuadrado (4) vamos hacia adelante 50 y giramos 90 grados a la izquierda
#y asi se completa el cuadrado
# window = ttl.Screen()
# david = ttl.Turtle()
# david.forward(50)
# david.left(90)
# david.forward(50)
# david.left(90)
# david.forward(50)
# david.left(90)
# david.forward(50)
# da... |
1dd372bee5aa27a63923a531ded0825523fd5c4a | atehortua1907/Python | /MasterPythonUdemy/8-Listas/8.6-FuncionesPredefinidas.py | 1,156 | 4.03125 | 4 | peliculas = ['Batman', 'Spiderman', 'El señor de los anillos', 'Titanic', 'Masacre en texas', 'Saw', 'El lobo de wall street']
numeros = [4, 6, 77, 1, 55, 0, 3]
#Ordenar
print(numeros)
numeros.sort()
print(numeros)
print(peliculas)
#Eliminar elementos por indices
peliculas.pop(2)
#Eliminar por nombre
peliculas.remo... |
d950d68588373bb0e8e5389fe045193884daff16 | atehortua1907/Python | /MasterPythonUdemy/2-Variables_TiposDeDatos/2.1-Variables-y-Tipos.py | 241 | 3.578125 | 4 | """
Python no es un lenguaje fuertemente tipado, por lo tanto la variable
toma el tipo según el valor asignado
"""
variable = "hola mundo"
print(type(variable))
variable = 4
print(type(variable))
variable = 4.50
print(type(variable)) |
0675a5be7d88ee7cdc9bad2d0d0d7affce72680b | atehortua1907/Python | /MasterPythonUdemy/15-POO/Herencia.py | 1,717 | 3.71875 | 4 | """
HERENCIA: Es la posiblidad de compartir atributos y Métodos
entre clases y que diferentes clases hereden de otras
"""
class Persona:
"""
nombre
apellidos
altura
edad
"""
# __nombre : "nombre"
# __apellidos
# __altura
# __edad
def getNombre(self)... |
35e995e46cedeb5c3450e78ffef467c632471e2b | atehortua1907/Python | /MasterPythonUdemy/6-EjerciciosBloque1/6.9-Ejercicio9.py | 177 | 4.1875 | 4 | """
Hacer un programa que pida numeros al usuario
indefinidamente hasta meter el numero 111
"""
num = 100
while num != 111:
num = int(input("Digite un número: ")) |
d5c1e62a45a8f54b456a5222850a37b3b0575df8 | atehortua1907/Python | /MasterPythonUdemy/10-EjerciciosBloque2/10.1-Ejercicio1.py | 967 | 4.46875 | 4 | """
Hacer un programa que tenga una lista de
8 numeros enteros y haga lo siguiente:
- Recorrer la lista y mostrarla
- Hacer funcion que recorra listas de numeros y devuelva un string
- Ordenarla y mostrarla
- Mostrar su longitud
- Busca algun elemento (que el usuario pida por teclado)
"""
... |
46943693bf861ad9813d5b91ca8c6b68dba1ab08 | atehortua1907/Python | /MasterPythonUdemy/5-EstructurasControl/5.1-Condicionales/5.1.4.-OperadoresLogicos.py | 331 | 3.8125 | 4 | """
Operadores Logicos:
and Y
or O
not NO
! Negación
"""
edad_minima = 18
edad_maxima = 65
edad_oficial = int(input("Digite su edad"))
#Operador logico 'and'
if edad_oficial >= 18 and edad_oficial <= 65:
print("Esta en edad de trabajar")
else:
print("No esta en edad de t... |
cfd922e85bdf9c79617f900fb9e3a0680d9ff577 | atehortua1907/Python | /MasterPythonUdemy/7-Funciones/7.2-ParametrosFunciones.py | 502 | 3.96875 | 4 | """
def muestraNombres(nombre, edad):
print(f"Tu nombre es: {nombre}")
if edad > 18:
print("Y eres mayor de edad")
nombre = input("Introduce tu nombre ")
edad = int(input("Digita tú edad "))
muestraNombres(nombre, edad)
"""
print("########## EJEMPLO 2 ##########")
def tabla(numero):
print(f"Ta... |
aba03341d4609c909283779c526fbeed0e0af013 | atehortua1907/Python | /MasterPythonUdemy/7-Funciones/7.10-KeywordArguments.py | 660 | 3.6875 | 4 | """
Es posible invocar una función enviando los parametros en un orden distinto
a lo definido, siempre y cuando se indique el keywordArgument
Esto puede ser útil cuando una función tiene muchos parametros y acordarse o tener
en cuenta el orden no es necesario
"""
def obtenerNombreCompletoYPais(nombre, ... |
3478ee499317157f62ae440fec80d10b05789b73 | vineeshvk/programming-practice | /spoj/1025-FASHION/solution_1025.py | 353 | 3.796875 | 4 | def max_hotness(men: list, women: list):
men.sort()
women.sort()
return sum([x * y for x, y in zip(men, women)])
if __name__ == "__main__":
t = int(input())
for x in range(t):
input()
men = list(map(int, input().split(" ")))
women = list(map(int, input().split(" ")))
... |
e922573da13fe4adcefd83f79d970fa15c1479e3 | vineeshvk/programming-practice | /leetcode/algo/search_insert_pos.py | 1,054 | 4.0625 | 4 | # https://leetcode.com/problems/search-insert-position/
# Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
# You must write an algorithm with O(log n) runtime complexity.
# Example 1:
# I... |
04b41f7b77ca27675c4e4e79f6bca57991bea1b3 | vineeshvk/programming-practice | /leetcode/algo/first_bad_version.py | 1,409 | 3.890625 | 4 | # https://leetcode.com/problems/first-bad-version/
# You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also b... |
c1a789494bbb8f449f3ef0fd4c8140f1ce8bb444 | vineeshvk/programming-practice | /spoj/54-JULKA/solution_54.py | 308 | 3.734375 | 4 | def apple_count(total, more):
half = total // 2
diff = more // 2
print(half,diff)
print(half + diff + (1, 0)[total % 2 == 0])
print(half - diff)
if __name__ == "__main__":
for x in range(10):
total = int(input())
more = int(input())
apple_count(total, more)
|
df07d5e34daa60a181066c9e607fd217b8ce0c50 | CloudKing-GrowLearning/Int-Python-Resources | /Resources/T6_DataFrame_in_Pandas/Unused/M2T6_video.py | 862 | 4 | 4 | import pandas as pd
file_name = 'some_file_path'
data = pd.read_csv(file_name)
#Access the dataframe by column
data['some_column_name']
#Access by a few column name
data[['one_colum_name', 'another_column_name']]
#Access row by index
data[some_index_value]
#Access splice of collumn(s)
data['some_column_name'][1:6]
data... |
bc3a61aa9248a1a06d0a2bbce9ff6359157e9501 | victor8619/Exercicios | /Dobro, Triplo e Raiz.py | 218 | 4 | 4 | num1 = int(input('Digite um número: '))
d = num1 * 2
t = num1 * 3
rq = num1 ** (1/2)
print(f'O dobro de {num1} vale {d}')
print(f'O triplo de {num1} vale {t}')
print(f'A raiz quadrada de {num1} vale {rq:.2f}')
|
2eea72d7cd946472b9d4599b434af0b609449dab | NaikMegha/Python | /inheritance.py | 1,107 | 3.8125 | 4 | class Vehicle:
def generic_purpose(self):
print("This is used for transportation")
class Car(Vehicle):
def __init__(self):
self.wheels = 4
self.roof = True
def specific_purpose(self):
print(f"Car has {self.wheels} wheels, and travel with family")
class MotorCycle(Vehicle... |
1f5e2128e0ba8ad9a1982f4d9a21e5d124707ec1 | fridgetheorem/ElevatorPitch | /Elevator_Calculations.py | 3,764 | 3.859375 | 4 | """
Performs calculations for the physics of an elevator which prioritizes
moving to the furthest floor in the queue
Author: Calum Offer
Date Created: March 10 2019
Date Last Modified: March 10 2019
"""
#Imports
import time
import math
# Sorts an inputted list from furthest from inputted bound to closest to... |
03d56008591c9d406b45df21409be60ceacfe8e3 | agusarridho/udacity_intro_to_ml | /naive_bayes/nb_author_id.py | 1,652 | 3.703125 | 4 | #!/usr/bin/python
"""
this is the code to accompany the Lesson 1 (Naive Bayes) mini-project
use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_prepro... |
3d5dcb5ce30f2383970481f757e389a496f60afa | mourke/PyProxy | /blocklist.py | 1,227 | 3.609375 | 4 | from typing import List, AnyStr
import validators
def is_valid_url_string(url):
return validators.url(url)
def read_blocklist():
f = open("blocklist.txt", "r")
lines = f.readlines()
items = []
for line in lines:
line = line[:-1] # remove line ending
if is_valid_url_string(line):
... |
81848d15e8ea738677a6f170f60529d91a87f0f6 | raulgonzalezcz/Thesis-UNAM | /tf.py | 4,850 | 3.90625 | 4 | # API requests library
import requests
# Get actual date library
from datetime import date, timedelta
# Objects for sklearn
import numpy as np
# Plot a graph, show information
import matplotlib.pyplot as plt
from mpldatacursor import datacursor
# Linear regression libraries
from sklearn import linear_model
from sklearn... |
dcdbd68cea46053d4c116d19d5ed64f0d26eca1f | obaodelana/cs50x | /pset6/mario/more/mario.py | 581 | 4.21875 | 4 | height = input("Height: ")
# Make sure height is a number ranging from 1 to 8
while (not height.isdigit() or int(height) not in range(1, 9)):
height = input("Height: ")
# Make range a number
height = int(height)
def PrintHashLine(num):
# Print height - num spaces
print(" " * int(height - num), end="")
... |
cba5053b8a30793641e74b6105e8d34865214f90 | alerickson0/DMZee | /pyscripts/files_md5_sums.py | 1,297 | 3.90625 | 4 | ## Purpose: Program to generate a file listing the md5 checksums of the files in the
## current directory and any sub-directories (if present)
## Python version written for: 3.7.3
## Pre-requisites: None
## Inputs: Current working directory
# Imports
import os
import os.path
import hashlib
# Function to return a list... |
014130aa0b43faecfbb0737cb47bf66bbf6bd318 | carriekuhlman/calculator-2 | /calculator.py | 2,425 | 4.25 | 4 | """CLI application for a prefix-notation calculator."""
from arithmetic import (add, subtract, multiply, divide, square, cube,
power, mod, )
# loop for an input string
# if q --> quit
# otherwise: tokenize it
# look at first token
# do equation/math for whatever it corresponds to
# return as a... |
f6e88a99e9f85e3a8261568d67f536be72dc0b87 | babakaskari/MachineLearning | /algorithm/test.py | 133 | 3.5 | 4 | def add(a, b):
return a + b
def chap():
print("HELLOOOOOO WOOOOOORLLLLLDDDDD")
def subtract(a, b):
return a - b
|
383389a6d7930baa978b1e7460d36bf8535db7a8 | bibek22/project-euler | /python/substring.py | 521 | 3.5625 | 4 | #!/usr/bin/python
import itertools as it
number = "0123456789"
everyPossible = list(it.permutations(number))
def getint(list, i, j):
return int("".join(list[i:j]))
sum = 0
for each in everyPossible:
if (getint(each, 1, 4) % 2 == 0) and (getint(each, 2, 5) % 3 == 0) and (getint(each, 3, 6) % 5 == 0) and (ge... |
e73b8fcc7afb658c128909f5a89fd6a4fbbb9ccd | bibek22/project-euler | /python/fibonacci-1000digit.py | 315 | 3.515625 | 4 | last = 1
sec_last = 0
index = 2
def fib():
# returns next fibonacci number as string every time.
global last
global index
global sec_last
index += 1
new = last + sec_last
sec_last = last
last = new
return str(new)
while len(fib()) < 10000:
pass
print index
print sec_last
|
74b9327643f370df1c17b2258d1f80e061e4780a | bibek22/project-euler | /python/primeMod.py | 3,380 | 3.9375 | 4 | #!/usr/bin/python
import math
def isPan(prime):
number = str(prime)
digits = []
for digit in number:
if (digit in digits):
return False
else:
digits.append(digit)
return True
primes = [2, 3]
last_prime = 3
def next_prime():
global last_prime
global pr... |
5db62530660f59585dab230139ec39cec444bd80 | bibek22/project-euler | /python/QuadraticPrime.py | 1,551 | 3.53125 | 4 | #!/usr/bin/env python3
def seive(n):
nums = [1] * n
primess = []
for i in range(len(nums)-2):
each = i + 2
if nums[each] == 1:
primess.append(each)
multiple = 2
next = multiple * each
while next < n:
nums[next] = 0
... |
caea0fd4c0e05c3ef50b981a4343a8ef94b070e4 | jakyzhu/computing_workshops | /workshop_1/GoT.py | 7,498 | 3.59375 | 4 |
# coding: utf-8
# # Introduction to Python
#
# ## Biostats Computing Workshop
#
# ### Motivational Example
# <img src="http://images1.villagevoice.com/imager/u/original/6699280/got21.jpg" style="width: 600px;">
# In[1]:
## SO MANY LIBRARIES
from bs4 import BeautifulSoup as bs ## Importing an Object!
from urllib2... |
d96c5ba83d9fbcb6eb92e037f30e4f173cbf56e9 | michaelduberstein/python-course | /lesson-2/homework/3.py | 1,813 | 3.578125 | 4 | """
Calculator
Make it so the main function passes all assertions just by changing the code in the decorators alone.
Remember PEP8 - do not submit code that does not adhere to the conventions.
Read about:
- decorators
- __repr__ vs __str__
- list arithmetic operators
- new-style format strings
- order of mu... |
c1a4f7a0101c6765c6bf989b6a17463317a57c07 | michaelduberstein/python-course | /lesson-1/PyExample/Ex1_1.py | 558 | 3.859375 | 4 | """
A) Write a program that shows the status of the current traffic-light
B) Extend the previous program to ask for user interaction
"""
from time import sleep
from random import randint
# traffic-light constants in seconds
# QUESTIONS: does the random generator include or exclude the limits?
MIN_WAIT = 5.0
MAX_WAIT ... |
7d7e0432cecd70cb6a669a2cea227e6b2c0c585e | meena-shiv/Data-Structures-using-Python | /linked list insert at first.py | 749 | 3.9375 | 4 | class node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.start=None
def insertFirst(self,data):
newNode=node(data)
if self.start==None:
self.start=newNode
else:
ne... |
6b0ac4439569140f0fcedaa7fd3d57a9e2afe1b2 | meena-shiv/Data-Structures-using-Python | /inorder to preorder BST.py | 320 | 3.515625 | 4 | def preorder(l,ind1,ind2):
if ind2>=ind1:
mid=int(ind1+((ind2-ind1)/2))
print(l[mid],end=' ')
preorder(l,ind1,mid-1)
preorder(l,mid+1,ind2)
for i in range(int(input())):
k=int(input())
l=[int(i) for i in input().split()]
preorder(l,0,k-1)
print()
|
374fe9434a08f458b61f08548d1ed8e1d5b548d2 | boy-tech/python | /52weekmoney_v5.0.py | 1,712 | 3.84375 | 4 | """
作者:boy-tech
功能:52周存钱挑战
5.0新增功能:根据用户输入的日期,判断是一年中的第几周,然后输出相应的存款金额
版本:5.0
日期:23/12/2019
"""
import math
import datetime
def save_money_in_n_weeks(money_per_week, increase_money, total_week):
"""
计算n周内的存款金额
"""
saved_money_list = [] # 记录每周账户累计
total_week_money ... |
3f511e4582a8d0253ad27898a56338bc4bf0af4f | blotenko/task_02 | /task_02.py | 308 | 3.765625 | 4 |
def int_Num_X2(num):
num = int(num)
print(num *2)
#########################
def float_Num_X2(num):
num = float(num)
print(num * 2)
######################
def str_X2(s):
s = str(s)
print(s * 2)
if __name__ == '__main__':
int_Num_X2(2)
float_Num_X2(2.2)
str_X2("22")
|
00348fcde01868d52f6dcb34099d62004ce1e97f | geep604/nthucs_spm_hw5_2019 | /vocAnalysis/parse.py | 5,227 | 4.09375 | 4 | # Author: Yu-Rong
# if you haven't installed nltk, execute this line to install nltk
#import os
#os.system("python3 -m pip install nltk")
import nltk
'''
Usage:
1. return the token count of an article
2. digit tokens should be removed, e.g, 1, 2, 3, 4,... 100, 101)
3. all tokens will be transformed to lower case
... |
dadf4636cbda6afac642e4e6306dece46f5b6c7a | brunopasseti/CodeWarsKatas | /Simple_Pig_Latin/code.py | 163 | 3.765625 | 4 | def pig_it(text):
words=text.split()
a = " ".join(word.replace(word[0], "", 1) + word[0] + "ay" if word.isalnum() else word for word in words)
return a |
61d8cb65ed02a9dbd905897290709080c49ba886 | benjiaming/leetcode | /validate_binary_search_tree.py | 1,596 | 4.15625 | 4 | """
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and righ... |
f7c50862b43c8c0386195cd4b01419c0ac6f7b21 | benjiaming/leetcode | /find_duplicate_subtrees.py | 1,636 | 4.125 | 4 | """
Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1
/ \
2 3
/ / \
4 2 4
/
4... |
2ae704df715aaa6f10628a2f9af0de20e35ee227 | benjiaming/leetcode | /test_reverse_linked_list.py | 596 | 3.78125 | 4 | import unittest
from reverse_linked_list import Solution, ListNode
class TestSolution(unittest.TestCase):
def test_reverse_linked_list(self):
solution = Solution()
node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(3)
node.next.next.next = ListNode(4)
... |
92f26b087c139fc829dbb81463c0492ecd63f184 | benjiaming/leetcode | /isomorphic_strings.py | 1,415 | 4.09375 | 4 | """
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character ... |
f2d07b36bb42c0d8b1ec205cb3fa338d18719363 | benjiaming/leetcode | /rotate_image.py | 1,571 | 4.1875 | 4 | #!/bin/env python3
"""
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =... |
83304448635210c35acbbed68d4b36c6b77f94d4 | Developer-Student-Club-Bijnor/Data_Structure_and_Algorithm | /Excercise/mergesort_exercise.py | 1,378 | 3.765625 | 4 | def merge(a: list, b: list, arr: list, key: str, descending: bool):
len_a = len(a)
len_b = len(b)
i = j = k = 0
while i < len_a and j < len_b:
if descending is False:
if a[i][key] <= b[j][key]:
arr[k] = a[i]
i += 1
else:
ar... |
31f07756faaa6a84752cc672f676c44554821b74 | Developer-Student-Club-Bijnor/Data_Structure_and_Algorithm | /DataStructure.py/Queue.py | 1,529 | 4.21875 | 4 | class Queue(object):
"""
Queue Implementation: Circular Queue.
"""
def __init__(self, limit=5):
self.front = None
self.rear = None
self.limit = limit
self.size = 0
self.que = []
def is_empty(self):
return self.size <= 0
def enQueue(self, item):
... |
6c6d29ea74cde8e59b2e3aa60810a71486a97408 | Developer-Student-Club-Bijnor/Data_Structure_and_Algorithm | /DataStructure.py/DisjointSet.py | 338 | 3.765625 | 4 | # MAKESET
class DisjointSet:
def __init__(self, n):
self.MAKESET(n)
def MAKESET(self, n):
self.S = [x for x in range(n)]
# FIND
def FIND(self, x):
if S[x] == x:
return x
else:
return FIND(x)
# UNION
def UNION(self, root1, root2):
... |
b048988bbaa1a55c3010042e642d232d7e1e4698 | SDSS-Computing-Studies/004c-while-loops-hungrybeagle-2 | /task2.py | 520 | 4.21875 | 4 | #! python3
"""
Have the user enter a username and password.
Repeat this until both the username and password match the
following:
Remember to use input().strip() to input str type variables
username: admin
password: 12345
(2 marks)
inputs:
str (username)
str (password)
outputs:
Access granted
Access denied
example:... |
72ee5bc64d38704e16b8a8ac08b4df6b6b81dd11 | shashwat-kotiyal/python_basic_prg | /Unpacking.py | 1,462 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 11 06:13:14 2021
@author: SKOTIYAL
"""
#Unpacking a Sequence into Separate Variables, N-element tuple or sequence that you would like to unpack into a collection of N variables
p= (4,5)
x,y= p
print(x,y)
#You need to unpack N elements from an iterable, but the ite... |
73ba6d6c26870ba1320d5c1ade9ac86fa564c174 | shashwat-kotiyal/python_basic_prg | /fun.py | 382 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 18 05:47:22 2021
@author: SKOTIYAL
"""
#required arg
# keyword arg
# default arg
def sum(a,b):
return a+b
def mul(a,b=1): #wrong (a=1,b),as once we placed default value all the arg after that should have default value
return(a*b)
print(sum(10,20)) #
print(sum... |
336cc4f1c7fa4cb5e4ae4c5dec65945499e14fd1 | shashwat-kotiyal/python_basic_prg | /shallowCopy.py | 807 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 19:11:45 2021
@author: SKOTIYAL
"""
import copy
l=[1,2,3,4]
l1=l
l1[0]='a'
print(l1,id(l1))
print(l,id(l))
print('='*10)
# here new list is not a copy is reference to origanal object,
# change in new object cause change in original object
mylist = [[1,2],[1,2,... |
e3b53d70a01a0cc03102530e472afdcca83cd6a7 | shashwat-kotiyal/python_basic_prg | /prime.py | 816 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 23 08:45:44 2021
@author: SKOTIYAL
"""
#An efficient solution is to use Sieve of Eratosthenes to find all prime numbers from till n
def sumOfPrimes(n):
prime =[True]*(n+1) #making list of n+1 elements
p=2
while(p*p <=n):
if(prime[p]== True):
... |
7779633f0c8bf9a73c3eafcc06e21beed0200332 | Nivedita01/Learning-Python- | /swapTwoInputs.py | 967 | 4.28125 | 4 | def swap_with_addsub_operators(x,y):
# Note: This method does not work with float or strings
x = x + y
y = x - y
x = x - y
print("After: " +str(x)+ " " +str(y))
def swap_with_muldiv_operators(x,y):
# N... |
43927a3adcc76846309985c0e460d64849de0fa7 | Nivedita01/Learning-Python- | /guess_game.py | 560 | 4.21875 | 4 | guess_word = "hello"
guess = ""
out_of_attempts = False
guess_count = 0
guess_limit = 3
#checking if user entered word is equal to actual word and is not out of guesses number
while(guess != guess_word and not(out_of_attempts)):
#checking if guess count is less than guess limit
if(guess_count < guess_lim... |
e5397915931ce970e0f35e4e1f6dd788eb93c200 | AdulIT/Week_2 | /summa_posledovatelnosti.py | 109 | 3.84375 | 4 | num = int(input())
sumSeq = num
while num != 0:
num = int(input())
sumSeq += num
print(sumSeq)
|
aa28c538b00a6bce45e3f6f1e90ace4ca31211d0 | AdulIT/Week_2 | /utrennyaya_probezhka.py | 112 | 3.6875 | 4 | x = float(input())
y = float(input())
days = 1
while x < y:
x = x + x / 10
days += 1
print(days)
|
fc2d226b6cbca1f64621b243a0c35c96ef7a06b5 | hasilrahman/assignment1 | /q6.py | 139 | 3.90625 | 4 | total = 0
list1=[11,3,44,32]
for ele in range(0,len(list1)):
total = total + list1[ele]
print("sum of all elements in given list:",total) |
cbebfaf0f6ada258500e293509e708cfd63a019e | hasilrahman/assignment1 | /q9.py | 210 | 3.515625 | 4 | l1=["ab","cd","ef","hr"]
x=map(lambda s:s[0]=='a',l1)
print(list(x))
x=filter(lambda s:s[0]=='a',l1)
print(list(x))
from functools import reduce
def add(x,y):
return x+y
l1=[12,32,55,54]
print(reduce(add,l1))
|
7c03d1890ed1439648e87f57548b42b9c8976fdf | rdumaguin/CodingDojoCompilation | /Python-Oct-2017/PythonOOP/Hospital/Hospital.py | 1,026 | 3.953125 | 4 | # OPTIONAL ASSIGNMENT - WIP
class Hospital(object):
def __init__(self, name, capacity):
self.patients = []
self.name = name
self.capacity = capacity # an integer indicating the maximum number of patients the hospital can hold.
def admit(self, id):
# add a patient to the list of ... |
12f9dbff51caec4d245d00d5d6cc71d0c3c88b5f | rdumaguin/CodingDojoCompilation | /Python-Oct-2017/PythonFundamentals/Lists_to_Dict.py | 1,020 | 4.21875 | 4 | name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
def zipLists(x, y):
zipped = zip(x, y)
# print zipped
newDict = dict(zipped)
print newDict
return newDict
zipLists(name, favorite_animal)
# C... |
c25a6d96c685066cf0ea04deb9354a7df04d95cb | rdumaguin/CodingDojoCompilation | /Python-Oct-2017/PythonOOP/MathDojo/MathDojo.py | 1,227 | 3.859375 | 4 | class MathDojo(object):
def __init__(self):
self.current_number = 0
def add(self, *args):
for num in args:
if isinstance(num, int) or isinstance(num, float):
self.current_number += num
elif isinstance(num, list) or isinstance(num, tuple):
... |
a3eb09f3fa7a633b94bfc80fc0bc5a869b6a81d8 | Irain-LUO/Scrapy_Study | /11 Selenium+Chromedriver获取动态数据--scrapy爬虫初学者学习过程/Selenium3-list operation.py | 1,232 | 3.984375 | 4 | # 常见的表单元素:
# input:type=''
# button:input[tpye='submit']
from selenium import webdriver
import time
driber_path = r'D:\Information\Working\pycharm\ChromeDriver\chromedriver.exe'# Chromedriver的绝对路径
driver = webdriver.Chrome(executable_path=driber_path)# 初始化一个driver驱动,并且制定Chromedriver的路径
# =======================... |
419da9aabcd7c29f48db6ca0dfc04611c9592417 | ann-peterson/contactclasses | /contact.py | 922 | 3.859375 | 4 | class Contact(object):
def __init__ (self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.mobile_number = ""
self.email = ""
def send_text(self,text):
print "To: %s - %s" % (self.mobile_number, text)
def display_name(self):
... |
c7c6588a74105ac76a5b8a1c286bd3ace15e418f | rajban94/Algorithms-Contest-Sudoku | /graph.py | 9,080 | 3.8125 | 4 | '''
Algorithms Contest: Sudoku - Graph
Author: Pratiksha Jain
Credit:
https://medium.com/code-science/sudoku-solver-graph-coloring-8f1b4df47072
'''
class Node :
def __init__(self, idx, data = 0) : # Constructor
"""
id : Integer (1, 2, 3, ...)
"""
self.id = idx
self... |
02bbd6b968500a74874764a567944ef3fbf4e281 | mahbub3330/Sorting-Algorithm | /selection sort/selection.py | 378 | 3.796875 | 4 | #-----------------------
#Selection sort
#-----------------------
def selection_sort(A):
for i in range(0,len(A)-1):
index = i
for j in range(i+1,len(A)):
if (A[index]>A[j]):
index=j
# print(index)
if index!=i:
A[i],A[index]=A[index],A[i]
A = ... |
3a213a57993bf2d4002b4fdfb2b179a1141913a7 | tme5/PythonCodes | /CoriolisAssignments/pyScripts/03_len.py | 752 | 3.953125 | 4 | #!/usr/bin/python
'''
Date: 17-06-2019
Created By: TusharM
3) Define a function that computes the length of a given list or string. (It is true that pyScripts has the len() function built in, but writing it yourself is nevertheless a good exercise.)
'''
def len(inp):
'''Get the length if string or li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.