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 |
|---|---|---|---|---|---|---|
3653fe48556a383890fdb3e92313fdcde819e6a9 | Rivarrl/leetcode_python | /leetcode/1-300/108.py | 795 | 3.625 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 108.py
# @Time : 2020/7/3 6:18 下午
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[108. 将有序数组转换为二叉搜索树](https://leetcode-cn.com/problems/convert-sorted-array-to-binary... |
3eb5d4bf274df63f590c40ab940d97b054ab4a2d | Rivarrl/leetcode_python | /leetcode/301-600/450.py | 1,414 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 450.py
# @Time : 2020/12/1 1:02
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[450. 删除二叉搜索树中的节点](https://leetcode-cn.com/problems/delete-node-in-a-bst/)
"""
... |
9d582677548d28e761d235799d9614784d33c5bc | Rivarrl/leetcode_python | /classes/RedBlackBST.py | 7,170 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : RedBlackBST.py
# @Time : 2019/11/1 16:59
# @Author : Rivarrl
# ======================================
RED = True
BLACK = False
class Node:
"""
红黑树节点
"""
def __init__(self, key = None, val = None, size = 0, color = None, ... |
68705d78e3f1b3c7354adca3138bb20ebd887905 | Rivarrl/leetcode_python | /leetcode/1-300/57.py | 2,193 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 57.py
# @Time : 2020/11/4 0:01
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[57. 插入区间](https://leetcode-cn.com/problems/insert-interval/)
"""
@timeit
d... |
c84d05da4eb57cdd99cae706e7e907c94b2197c6 | Rivarrl/leetcode_python | /leetcode/301-600/336.py | 1,268 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 336.py
# @Time : 2020/5/8 18:25
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[336. 回文对](https://leetcode-cn.com/problems/palindrome-pairs/)
"""
@timeit
... |
e5d7842f0556046293023b5ddde0443362f26e4d | Rivarrl/leetcode_python | /leetcode/901-1200/912.py | 907 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 912.py
# @Time : 2020/3/31 0:05
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
@timeit
def sortArray(self, nums: List[int]) -> List[int]:
def quick_sort(arr, i, ... |
acdafa79ee36ec5cd295ca0160502f5c6875b203 | Rivarrl/leetcode_python | /basic/num_sort.py | 6,586 | 4.0625 | 4 | # -*- coding:utf-8 -*-
# 排序算法汇总
# 交换
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
# 选择排序
def selection_sort(arr):
n = len(arr)
for i in range(n):
k = i
for j in range(i+1, n):
if arr[j] < arr[k]:
k = j
swap(arr, i, k)
return arr
# 冒泡排序
def ... |
cbe7d55ac9cb644658fcb804ca6842273a997a90 | Rivarrl/leetcode_python | /leetcode/901-1200/905.py | 1,034 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 905.py
# @Time : 2019/11/11 1:02
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
@timeit
def sortArrayByParity(self, A: List[int]) -> List[int]:
"""
[905.... |
f6ac63e3f3505878829d8d45c189bc7b4002b932 | Rivarrl/leetcode_python | /leetcode/301-600/390.py | 1,154 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 390.py
# @Time : 2019/11/14 9:31
# @Author : Rivarrl
# ======================================
from algorithm_utils import timeit
class Solution:
"""
[390. 消除游戏](https://leetcode-cn.com/problems/elimination-game/)
"""
@tim... |
0b6967c9964241cec02e741b652ee108af93bf40 | Rivarrl/leetcode_python | /leetcode/301-600/543.py | 1,003 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 543.py
# @Time : 2020/3/10 0:04
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[543. 二叉树的直径](https://leetcode-cn.com/problems/diameter-of-binary-tree/)
"""
@... |
f49e7fcad7200e81ea299da3c11b0f06d2a013ba | Rivarrl/leetcode_python | /leetcode/1-300/130.py | 1,468 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 130.py
# @Time : 2020/8/11 0:00
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[130. 被围绕的区域](https://leetcode-cn.com/problems/surrounded-regions/)
"""
def so... |
8634bc42668dd859313ccf5813b98840e185aeac | Rivarrl/leetcode_python | /leetcode/msjd/03-01.py | 1,388 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 03-01.py
# @Time : 2020/11/13 1:28
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class TripleInOne:
"""
[面试题 03.01. 三合一](https://leetcode-cn.com/problems/three-in-one-lcci/)
"""
... |
9421e016f342948d08d614e274130afd3d9ba605 | Rivarrl/leetcode_python | /leetcode/1-300/210.py | 1,272 | 3.5 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 210.py
# @Time : 2019/11/12 10:23
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[210. 课程表 II](https://leetcode-cn.com/problems/course-schedule-ii/)
"""
@tim... |
5fcab5430503588f02a212137a8d3dcbe443f6a7 | Rivarrl/leetcode_python | /leetcode/1-300/233.py | 1,273 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 233.py
# @Time : 2019/11/23 0:50
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[233. 数字 1 的个数](https://leetcode-cn.com/problems/number-of-digit-one/)
"""
@t... |
fba845f2c3e77c2e7afc9b0e7becbc575fb36d04 | Rivarrl/leetcode_python | /leetcode/1-300/60.py | 1,008 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 60.py
# @Time : 2020/9/5 16:09
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[60. 第k个排列](https://leetcode-cn.com/problems/permutation-sequence/)
"""
@timeit... |
c190766aa8c60b831f3f7428ccaf90f660c1eeae | Rivarrl/leetcode_python | /leetcode/1-300/94.py | 848 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 94.py
# @Time : 2020/9/14 0:40
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[94. 二叉树的中序遍历](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/)
"""... |
5a62bd3a2828f231e32c8776ffe2bfd7e36aa181 | Rivarrl/leetcode_python | /leetcode/LCP186+/5384.py | 783 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 5384.py
# @Time : 2020/5/2 22:31
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[5384. 拥有最多糖果的孩子](https://leetcode-cn.com/problems/kids-with-the-greatest-number-of-c... |
959b36e51024378fabeb8f1fb1c366479d78d968 | Rivarrl/leetcode_python | /leetcode/leetcode_nm.py | 43,235 | 3.578125 | 4 | # -*- coding:utf-8 -*-
from algorithm_utils import *
# leetcode 中等题
def reverseBetween(head, m, n):
"""
92. 反转链表 II
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
:param head: ListNode
:param m: int
:param... |
74e062a29a607b612b784b81ca16b81e78977085 | Rivarrl/leetcode_python | /leetcode/1-300/206.py | 666 | 3.875 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 206.py
# @Time : 2020/3/2 14:10
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[206. 反转链表](https://leetcode-cn.com/problems/reverse-linked-list/)
"""
def rev... |
d7f76eec003b27842ff62faa22754a0ddcb05012 | allefant/land | /src/queue.py | 4,245 | 4.09375 | 4 | import array
class LandQueue:
"""
A queue data structure is used if the elements need to be kept sorted. It
allows to quickly pick the minimum element. If you need arbitrary access
to the elements, use a LandArray instead. If you need arbitrary removal and
insertion, use a LandList. If you need arb... |
e33a8c837a61afd1c98d8dfb2d30e55c9c3a5c55 | kacperkus/ruby-course | /last-prime-number++.py | 462 | 3.84375 | 4 | prime_numbers = []
is_palindrome = False
def palindrome(prime_number):
prime_number = str(prime_number)
if prime_number == prime_number[::-1]:
prime_numbers.append(prime_number)
for number in range(999, 1, -1):
for n in range(2, number):
if number % n == 0:
is_palindrome = Fal... |
010ddab00dca3b5b341c858288ecbcdba0fb9db8 | jmawloo/Applied-Data-Science | /1. Intro to Data Science/Pandas.py | 9,944 | 3.546875 | 4 | import pandas as pd
#SERIES DATA STRUCTURE
#pd.Series? Works in iPython to display help. Type help(pd.Series) for regular Python.
people = ["Bill","Chris","Martha", None] # The null type is cast into object.
print(pd.Series(people)) # Autosets datatype.
numbers = [1,2,3,None] # none becomes NaN, as well as all float... |
d489d7ef62bc4dc8443b96b58a7675e746c8b113 | jmawloo/Applied-Data-Science | /2. Applied Plotting, Charting & Data Representation in Python/Week3 (Charting Fundamentals).py | 9,030 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 31 10:24:21 2018
@author: Jeff
"""
import matplotlib.pyplot as plt
import numpy as np
# Subplots: Display different graphs on specified number of rows and columns.
plt.figure()
plt.subplot(1, 2, 1) # Number of rows, number of columns, axis to start in (left-hand side).... |
d17be230eb0ca7005ced1d6e0602891697736a64 | jmawloo/Applied-Data-Science | /3. Applied Machine Learning/Assignment1.py | 8,206 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 29 15:40:26 2018
@author: Jeff
Remove comments on answer function calls to run the function.
"""
"""
For this assignment, you will be using the Breast Cancer Wisconsin (Diagnostic) Database to create a classifier that can help diagnose patients. First, read through the ... |
1244c71fb68f95c05ff9d03055656f970c99d588 | glasses4days/skills-oo | /skills-oo.py | 876 | 4.03125 | 4 | class Student(object):
def __init__(self, first_name, last_name, address):
"""Initialize student attribute"""
self.first_name = first_name
self.last_name = last_name
self.address = address
class Question(object):
def __init__(self, question, correct_answer):
"""Initi... |
9a30c47aa96f7381e9de64f4aa9b50e1a03951d1 | IjonTichy/PythonTidbits | /flatten.py | 213 | 3.515625 | 4 | def flatten(listToFlatten):
for item in listToFlatten:
if isinstance(item, (tuple, list, set)):
for item2 in flatten(item):
yield item2
else:
yield item
|
59ec6f56b3ff2a45ee765dfe1750244c0bcdea24 | IjonTichy/PythonTidbits | /soda.py~ | 559 | 3.578125 | 4 | #!/usr/bin/python
def snowball():
numS = None
while not numS:
try: numS = int(raw_input("Amount of students attending: "))
except AttributeError: print "NaN"
soda24packs = numS/24
soda6packs = (numS - (soda24packs * 24)) / 6
singleSodas = numS - (soda24packs * 24) - (soda6packs * 6)
print "You'll need:\n%s 24... |
d1904a7c6087b317004da4881dbee7bbec00cbbd | ketanv3/blockchain-evm | /blockchain.py | 2,050 | 3.625 | 4 | from block import Block
from hashlib import sha256
from collections import deque
class Blockchain():
# Set the parameters for the blockchain
def __init__(self, block_size, genesis_block_secret):
self.block_size = block_size
self.genesis_block_hash = sha256(genesis_block_secret.encode('u... |
478dce4941efd02f308f07b0bcc6f43bae9c2ba1 | elias-santos87/Projeto-Acerte-o-numero | /Projeto Acerte o número.py | 1,342 | 4.0625 | 4 | # Projeto Acerte o Número
# Crie um programa simples que gere números inteiros aleatórios entre 1-50,
# que peça um número do usuário e verifique se o valor inserido é igual ao aleatório.
# O programa deve ser repetido 15 vezes. Se o usuário digitar um número fora do intervalo válido
# o programa deverá ser encer... |
913baeb65cd9cc7e6d4f4f9130cb49fa45f94b3b | ReneAlfredo/exercise01-Python | /exercise01-result.py | 2,647 | 4.03125 | 4 | # Alumno: René Alfredo Arévalo Ayala
# Carné: 20192110
# Indicación
"""
cliente:
quiero escribir un programa python que reciba de input del usuario
un nombre, un producto, costo
y se guarde en una lista con diccinarios, el registro es un diccionario
y va a ser guardado en una lista
programador:
... |
a527679a64dc7d04b2ea22690a4f16171cfb4b44 | hyorard/dataStructure | /BST.py | 4,794 | 3.875 | 4 | # -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
class Node:
def __init__(self, key):
self.key = key
self.parent = self.left = self.right = None
def __str__(self):
return str(self.key)
class Tree:
def __init__(self):
self.root = None
self.size = 0
de... |
e42ebe1c645a9e9671308aa0447ed57b009d3907 | avaucamps/dynamic_neural_network | /ConvolutionLayer.py | 3,990 | 3.734375 | 4 | import numpy as np
from utils import relu, relu_derivative
class ConvolutionLayer:
def __init__(self, n_filters, filter_size, learning_rate, stride=1):
"""
Creates a Convolutional Layer.
Arguments:
- n_filters: the number of filters the layer should have.
- filter_... |
102f4ac832229adec08352b85f0fe932575d5a3a | speccy88/Digital-Logic | /eq.py | 1,914 | 4.03125 | 4 | # -*- coding: latin-1 -*-
def getEquation():
eq_raw = raw_input("Entrer l'équation:")
eq_validated = validateEquation(eq_raw)
return eq_validated
def evalEquation(eq,tail=None):
table = {'a':True,'b':False,'c':True}
finished = False
while not finished:
op, firstCase = getOp(eq)
if firstCase:
loc = eq.fin... |
4b610d707b407ef845cc19fde9da3eefc6115065 | BlakeBeyond/python-onsite | /week_02/08_dictionaries/09_03_count_cases.py | 1,065 | 4.5 | 4 | '''
Write a script that takes a sentence from the user and returns:
- the number of lower case letters
- the number of uppercase letters
- the number of punctuations characters (count)
- the total number of characters (len)
Use a dictionary to store the count of each of the above.
Note: ignore all spaces.
Example in... |
43c2d6a0f00fd227128346abb00dcd870f5c39c9 | BlakeBeyond/python-onsite | /week_05/sqlalchemy0/00_db_info.py | 580 | 3.5625 | 4 | '''
All of the following exercises should be done using sqlalchemy0.
Using the dvdrental schema, write the necessary code to print information about the film and category table.
'''
import sqlalchemy as db
from pprint import pprint
username = 'Blake'
URI = f'postgres+psycopg2://{username}@localhost:5432/dvdrental'... |
706908e68f8ff2b59e469d698c8df37912575c12 | BlakeBeyond/python-onsite | /week_04/intro_apis/02_numbers_BONUS.py | 907 | 3.65625 | 4 | '''
BONUS:
* fetch information of all the prime numbers from 1-1000
* cycle through the different endpoints the API provides (trivia, math, date, year)
in a way that they change in binary chunks, e.g.:
- the info on the first 2 numbers are of type trivia
- info on the next 4 numbers are of type math
- the next ... |
68a19b536b3ba06cd7ae5107106d15dd175682e5 | BlakeBeyond/python-onsite | /week_02/08_dictionaries/09_02_combine_dicts.py | 334 | 4.34375 | 4 | '''
Create a new dictionary using the three dictionaries below.
Then print out each key-value pair.
'''
dict_1 = {1: 1, 2: 4}
dict_2 = {3: 9, 4: 16}
dict_3 = {5: 25, 6: 36, 7: 49}
new_dict = {}
def add_dict(d):
for k, v in d.items():
new_dict[k] = v
add_dict(dict_1)
add_dict(dict_2)
add_dict(dict_3)
p... |
8cc1be4731414968bd86deec1d6fec4b1623e822 | BlakeBeyond/python-onsite | /week_01/03_basics_variables/06_population.py | 739 | 3.625 | 4 | '''
In the U.S., if there is:
- One person who is born every 6 seconds
- One person who dies every 12 seconds
- One person who immigrates every 40 seconds
Write the necessary code to display the total population
for the next 3 years (without a leap year).
Let's say the current population is 380,123,456.
'... |
d7af1592985a4677bc8929c35905f045b25ca842 | BlakeBeyond/python-onsite | /week_02/06_tuples/02_word_frequencies.py | 628 | 4.40625 | 4 | '''
Write a function called most_frequent that takes a string and prints
the letters in decreasing order of frequency.
For example, the follow string should produce the following result.
string_ = 'hello'
Output:
l, h, e, o
For letters that are the same frequency, the order does not matter.
'''
my_dict = {}
sorted... |
e8f1c5cd3e440886e0fa8f594d1092fb58fb509a | cp105/dynamic_programming_101 | /dp101/knapsack01.py | 1,896 | 4.4375 | 4 | """
The knapsack problem is a problem in combinatorial optimization: Given a set of items,
each with a weight and a value, determine the number of each item to include in a collection so that
the total weight is less than or equal to a given limit and the total value is as large as possible.
It derives its name from t... |
9fc836c34e00b7a81d5eb4ce51cce1bdc4946590 | trynke/chess | /chess.py | 4,306 | 3.8125 | 4 | def print_chess_board(k, l, m, n):
board = [[0 for i in range(0, 8)] for j in range(0, 8)]
for i in range(0, 8):
if i % 2 == 0:
for j in range(0, 8):
if j % 2 == 0:
board[i][j] = "\033[0;37;47m "
else:
board[i][j] = "\... |
602ca2908f11f4861651c63725e016206b7ce5f5 | 8I4cK/HangedMan | /fruit_list.py | 899 | 3.9375 | 4 | import random
from letter import EnteredLetter
class FruitList:
def __init__(self):
self.__fruits = ['banana', 'jabuticaba', 'pitanga', 'mirtilo', 'morango', 'abacaxi', 'cereja']
self.random_word = ''
self.ended_word = False
self.entered_letter = EnteredLetter()
def chose_ra... |
730e81e9405070742830a4c7a3536ba66aed0677 | David-Carrasco-Vidaurre/trabajo04.CarrascoVidaurreDavid | /Calculadora09.py | 490 | 3.59375 | 4 | #calculadora nro9
#esta calculadora realiza calculos del potencial electrico
#declaracion de variables
constante_electrica,carga,distancia,potencial_electrico=0.0,0.0,0.0,0.0
#calculadora
carga=60
constante_electrica=9000000000
distancia=30
potencial_electrico=(carga*constante_electrica)//(distancia)
#mo... |
1b9a6199d8577760b8fc5c62bbf441934d485fa4 | David-Carrasco-Vidaurre/trabajo04.CarrascoVidaurreDavid | /Calculadora14.py | 401 | 3.515625 | 4 | #calculadora nro14
#esta calculadora realiza calculos de la velocidad angular
#declaracion de variables
velocidad_angular,constante_pi,frecuencia=0.0,0.0,0.0
#calculadora
constante_pi=3.1416
frecuencia=100
velocidad_angular=(2*constante_pi*frecuencia)
#mostrar datos
print("constante_pi=",constante_pi)
p... |
0dc48299e7c23085ecae55f4b64fb365fbb42689 | King-Yung/budget-app | /# Budget APP.py | 8,331 | 4.0625 | 4 | # Budget APP
# Create new category
# Withdrawing funds from each category
# Depositing funds to each of the categories
# Computing category balances
# Transferring balance amounts between categories
database = dict()
class Budget:
def __init__(self, category, amount):
self.category = category
se... |
54d8254a298523c43e83be46cf72234aa41ff20a | RdecKa/HashCode2021 | /practice_problem/solution.py | 1,141 | 3.671875 | 4 | import sys
# Read which input to choose
selectedInput = "a"
if len(sys.argv) > 1:
candidate = sys.argv[1]
if len(candidate) == 1 and candidate in "abcde":
selectedInput = candidate
else:
print(f"! Invalid input {candidate}, using default")
print(f"Selected input: {selectedInput}")
# Read i... |
ba87b15776b7e536b9a2f6b1ae288cf5358f1f55 | RaoulAlcalaRuiz/bi-finance | /classes/average_list.py | 1,262 | 3.5 | 4 | from .average import Average
from .computer_date import ComputerDate
class AverageList:
def __init__(self, list, list_goal):
self._list = list
self._list_goal = list_goal
def compute_average(self, year):
new_list = []
i = 0
while i < len(self._list):
if (sel... |
8cb9ab38b6cd0d033e37514c5878f2f2835af56c | Meekol/BrainHackApp | /BrainhackShell.py | 6,040 | 3.984375 | 4 | import time
import tkinter as tk
from tkinter import ttk
events = [] #List of user's events that grows with each input
duration = [] #List of user's event duration corresponding with the event[] list with shared index
organizedSchedule = [] #List of 3 tuples: (Event, EventStartTime, EventEndTime)
wakeTime = -1 #User'... |
806102de666cf5a18f542bcc1bf1225bae6cf94b | thekrutarth/AutomatedEssayGradingSystem | /FeatureExtractor.py | 8,883 | 3.640625 | 4 | # File Name: FeatureExractor.py
# --------------------------------------
# Developers: Himanshu Thakur
# Krutarh Joshi
#
# --------------------------------------
# This module extracts various numerical
# features from the essays which will be
# used further to train the system to
# p... |
61c3f49c08463e23e91b8e0fbdeb8b8904686993 | tomobones/hort | /Code_Beispiele/etwas_oft_sagen.py | 151 | 3.703125 | 4 | wort = input("Was möchtest du sagen? ")
anzahl = input("Wie oft möchtest du es sagen? ")
for nummer in range(eval(anzahl)):
print(wort, end=" ")
|
1f4e1bc8af8ebc5a058db7cb88dc60d874d85e18 | tomobones/hort | /Code_Kinder/louie_02.py | 145 | 3.515625 | 4 | import turtle
t=turtle.Pen()
for x in range(100):
t.forward(x)
t.left(90)
t.left(91)
t.range(1000)
t.left(1000)
turtle.Screen().exitonclick()
|
2f38f4bc5978ba371014073dd189675134becea2 | lucho1021/python | /practic.py | 2,238 | 4.21875 | 4 | #puntoA
"""factorial = input ('ingresa un numero ')
factorial = int (factorial)
def calculafactorial(factorial):
if factorial==0 or factorial==1:
resultado=1
elif factorial > 1:
resultado=factorial*calculafactorial(factorial-1)
return resultado
print("el factorial de",factorial... |
1ed35d3fe9fa0fc6edb90e1f75aec3cba11e2cfd | leandroreiz/harvard-cs50 | /pset6/mario/more/mario.py | 304 | 4.09375 | 4 | from cs50 import get_int
# only accept numbers between 1-8
while True:
height = get_int("Height: ")
if height > 0 and height <= 8:
break
# loop to create the pyramids
for i in range(height):
print(" " * (height-(i+1)), end="")
print("#" * (i+1), end=" ")
print("#" * (i+1)) |
1d515e5d273325b9451dae9af16ce5f6a7f2fb80 | andreaduranvp/proyecto_satan_reload | /satan.py | 184 | 3.75 | 4 |
print("My awesome code in Python -----------------")
for i in range(1, 10):
print(str(i) + '.numbered')
# *
# **
# ***
# ****
# *****
# ******
# *******
# ********
# *********
|
f0612730e3090368de56ef91c9ca5614d088b9d1 | hjalves/project-euler | /problems1-25/problem3.py | 452 | 3.84375 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Project Euler - Problem 3
Largest prime factor
"""
def is_prime(n):
return all(n % i != 0 for i in range(2, int(n**0.5)+1))
def primes(max):
return filter(is_prime, range(2, max+1))
def factors(n):
return (p for p in primes(n) if n % p == 0)
def factori... |
abbe72def4dc0201a0570182323dd06d2cc8636f | hjalves/project-euler | /problems26-50/problem41.py | 628 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project Euler - Problem 41
Pandigital prime
"""
from itertools import permutations
def join(nl):
return sum(b * 10**p for p, b in enumerate(reversed(nl)))
def revpan(dig):
return reversed(list(permutations(range(1, dig+1), dig)))
def isprime(n):
return... |
21862b6235790c8f3a45a459dd806f765c4ea118 | hjalves/project-euler | /problems26-50/problem49.py | 920 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project Euler - Problem 49
Prime permutations
"""
from collections import defaultdict
from itertools import combinations
def split(n):
return map(int, str(n))
def is_prime(n):
return all(n % i != 0 for i in range(2, int(n**0.5)+1))
def primes(min, max):
... |
e58235aa8370fef5fbb37af73b9d183241820a38 | hjalves/project-euler | /problem66-alt.py | 527 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project Euler - Problem 66
Diophantine equation
"""
from itertools import count
def xsquare(d, y):
return 1 + d * y*y
def is_square(x):
return int(x**.5)**2 == x
def find_y_solutions(d, max):
return (y for y in range(1, max) if is_square(xsquare(d, y))... |
96f30e33b33c17252583722489a781a2ba550006 | hjalves/project-euler | /problems26-50/problem45.py | 641 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project Euler - Problem 45
Triangular, pentagonal, and hexagonal
"""
from itertools import count
def hexagonal(n):
return n * (2*n - 1)
def pentagonal(n):
return n * (3*n-1) // 2
def pentagonal_inv(p):
return int((24*p + 1)**0.5 + 1) // 6
def triangul... |
da113edb8ec75e390018ff194890c91dcc78f4ae | hjalves/project-euler | /problems1-25/problem7.py | 308 | 3.578125 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Project Euler - Problem 7
10001st prime
"""
from itertools import count, islice
def is_prime(n):
return all(n % i != 0 for i in range(2, int(n**0.5)+1))
def primes():
return filter(is_prime, count(2))
print(next(islice(primes(), 10000, 10001)))
|
61a7141bca80b77f239764dd654796180e309a00 | hjalves/project-euler | /problems26-50/problem27.py | 947 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Project Euler - Problem 27
Quadratic primes
"""
from itertools import takewhile, count
def is_prime(n):
return n >= 2 and all(n % i != 0 for i in range(2, int(n**0.5)+1))
def formula(a, b, n):
return n*n + a*n + b
def iter_formula(a, b):
return (formul... |
bc30b7534ec5b748c41fe615aa0b758b6300c571 | furyash/nscLab | /3.playFair/reciever.py | 2,852 | 3.609375 | 4 | import socket
port = 4545
format = 'utf-8'
size = 1024
client = socket.socket()
host = socket.gethostname()
client.connect((host,port))
message = client.recv(size).decode(format)
print(f"Encrypted Message recieved : {message}")
key = input("Enter key to decrypt : ")
print("\nDecrypting...")
## Play Fair Matrix Ca... |
6320b13d4429875567408b589248af5e1ae95aa7 | tiffynolan/Morse_GUI | /Morse_GUI.py | 2,844 | 3.828125 | 4 | import tkinter as tk #GUI
import sys
import RPi.GPIO as GPIO #Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
LED = 21 #LED Output port
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BCM) # Declare pin number standard
GPIO.setup(LED... |
4b8c3ccc994573bae5efcd40e36c12b97deef4a9 | jtannas/intermediate_python | /context_managers.py | 4,168 | 4.4375 | 4 | """
25. Context managers
Context managers allow you to allocate and release resources precisely
when you want to. The most widely used example of context managers is
the with statement. Suppose you have two related operations which you’d
like to execute as a pair, with a block of code in between. Context
managers allo... |
e441e0e4fa599fefe6f3f49f32477c68dd46e29a | jtannas/intermediate_python | /caching.py | 1,368 | 4.65625 | 5 | """
24. Function caching
Function caching allows us to cache the return values of a function
depending on the arguments. It can save time when an I/O bound function
is periodically called with the same arguments. Before Python 3.2 we
had to write a custom implementation. In Python 3.2+ there is an
lru_cache decorator w... |
ebd261d238b7e9fe9a2167c9333de3046439771b | jtannas/intermediate_python | /ternary.py | 574 | 4.25 | 4 | """
6. Ternary Operators
Ternary operators are more commonly known as conditional expressions in
Python. These operators evaluate something based on a condition being
true or not. They became a part of Python in version 2.4
"""
# Modern Python Way.
def positive_test(num):
return 'positive' if num > 0 else 'not po... |
4daf27f3920414b4c69baebb22ea7e602d71c23f | sunlei-xxp/alien_invasion | /bullet.py | 1,178 | 4.09375 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""A class for bullet released from ship, it's heritate from class pygame.sprite.Sprite"""
def __init__(self, ai_settings, screen, ship):
"""create a bullet object at the location of ship, with bullet settings"""
super().__i... |
d63bba1a6e438dcdffa68d256af2e3329457b56a | cwhalen9/Examples-of-work | /Rename_files_based_on_old_and_new_file_names_in_Excel_spreadsheet.py | 1,616 | 3.90625 | 4 | """
This script can be used to rename files in a directory
The script reads an Excel document that has the old file names in one column and the new file names in another column
The script compares each file in the directory to the old file list
If a file is in the old file list, it is renamed to the corresponding n... |
fbdcbc79ff16ee1b43ad8a4beafcccf2ccf0d0f3 | xuyanlinux/code | /module01/第二章/用户交互和注释.py | 1,688 | 4.125 | 4 | # name = input("Name:")
# age = input("Age:")
# job = input("Job:")
# hometown = input("Hometown:")
#
# info = '''-------------info of %s----------------
# "Name:" %s
# "Age:" %s
# "Job:" %s
# "Hometown:" %s
# ----------------END----------------------
# '''% (name,name,age,job,hometown)
#
... |
a17a6fd5646482eb2c38b8231ab962bcbe043b1f | xuyanlinux/code | /module01/第一章/用户登录作业.py | 967 | 3.890625 | 4 | #! _*_ coding:utf-8 _*_
#Author:Timmy
#创建一个列表,存储允许登录的用户名和密码
#每一个子列表中存储的,是合法的用户名和密码
user_list = [['张三','z3pass'],['李四','l4pass'],['王五','w5pass']]
count = 0
#登录控制主体
## 将用户输入的用户名和密码组合成一个列表,并判断是不是user_list的子列表
## 如果是,给出欢迎信息,跳出循环,程序结束
## 如果不是,则判断这是第几次输入错误,不足三次时,给出剩余次数;否则,给出结束提示,程序结束
while count < 3:
username = input("输... |
cfebcbda3385cc9fa48e110f1702ec3b91a34eee | xuyanlinux/code | /module02/chapter01/46斐波那契.py | 481 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# __author__ = "Q1mi"
# Email: liufengjimo@live.com
# Date: 2019/5/18
# lis1 = [i for i in range(5)]
# lis_fib = []
# def fib(n):
# count,a,b = 0,0,1
# while count < n:
# print(b)
# a,b = b,a+b
# count += 1
#
# fib(15)
# 根据上面的函数写生成器
def fib(n):
count,a,b ... |
cd514b0f5af545cddd59b73b6aa1c76e566f41d1 | xuyanlinux/code | /module04/chapter01/33event.py | 485 | 3.609375 | 4 | #Author:Timmy
from threading import Thread,Event,current_thread
import time
ev = Event()
def student():
print("%s is studing..."% current_thread().getName())
ev.wait()
print("%s is playing..." % current_thread().getName())
def teacher():
print("老师在上课...")
time.sleep(5)
ev.set()
if __name__ ==... |
9ed362808b9a652e3c5924b58d8261eaa089575e | edxu96/TidySimStat | /src/TidySimStat/DRV.py | 8,087 | 3.796875 | 4 |
import math
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import scipy.stats as st
import random as rd
from operator import add
from TidySimStat.auxiliary import *
def sim_drv_reject(pmf:list):
"""Rejection method to simulate realisations of a discrete random variables
with `ra... |
56eae987c4266c979cbb9f15a68badabd43aff42 | edxu96/TidySimStat | /src/TidySimStat/rng.py | 1,948 | 3.515625 | 4 |
import pandas as pd
def rng(num:int=1, cal_y=None, m:int=123, x0:int=1):
"""Generic function for random number generator.
Keyword Arguments
=================
num: size of random number vector to generate
cal_y: function to calculate `y` based on previous `x`
m: chosen large number, which sho... |
f9be5fcd9c8467fe78da79a42f574df494b3f723 | melyxlin/Fundamentals | /Algorithms/Python/BinarySearch.py | 403 | 4.03125 | 4 | def BinarySearch(array, target):
rightIndex = len(array) -1
leftIndex= 0
while leftIndex <= rightIndex:
middleIndex = (leftIndex + rightIndex) // 2
if array[middleIndex] == target:
return True
elif array[middleIndex] < target:
leftIndex = middleIndex + 1
... |
340929e2b129e09a05b152e0c6ebdb05c9475450 | urosrac/test | /fib.py | 90 | 3.546875 | 4 | def fib(n):
if n==0:
return 0
if n==1:
return 1:
else:
return fib(n-1) + fib(n-2) |
023381cd0171ea36ff58233c6447c4c4db769db4 | agorodetskiy/dl-in-nlp-mipt | /assignments/workshop_2/cs231n/classifiers/softmax.py | 4,715 | 3.859375 | 4 | import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing wei... |
57f770705a778430df236fcf15c9181fc0879c99 | sandyjernigan/Data-Structures | /lru_cache/doubly_linked_list.py | 5,665 | 4.25 | 4 | """Each ListNode holds a reference to its previous node
as well as its next node in the List."""
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
class DoublyLinkedList:
"""Our doubly-linked list class. It holds refe... |
1588df464a139c01f7d6097d5bc4fe6376452fb8 | dinomite/dinotweedele | /delete_old_tweets.py | 1,980 | 3.59375 | 4 | # https://pushpullfork.com/i-deleted-tweets/
import tweepy
import csv
consumer_key = ''
consumer_secret = ''
access_key = ''
access_secret = ''
def read_csv(file):
"""
reads a CSV file into a list of lists
"""
with open(file, encoding = 'utf-8') as csvfile:
reader = csv.reader(csvfile, delimit... |
512e5ec836c5d21f607835d93612cda46f1047d9 | holyTornado/Python | /MyPython/Distribution/MoviesNester.py | 1,780 | 3.703125 | 4 | """这是一个练习,“nester.py”模块,提供了一个名为print_lol()的函数,
这个函数的作用是打印列表,其中有可能包含(也可能不包含)嵌套列表。"""
import os
def print_lol(the_list, indent=False, display_serial=False, level=0, serial=0, print2_files=''):
"""这个函数取一个位置参数,名为“the_list”,这可以是任何Python列表
(也可以是包含嵌套列表的列表)。所指定的列表中的每个数据项会(递归地)
输出到屏幕上,各数据项各占一行。
第二个参数(名为“indent”)用来判断是否用缩进形... |
5a07a96b0f950b57bace44dbcff1bbf8ed51b953 | Anjustdoit/Python-Basics-for-Data-Science | /FileFormat_json.py | 668 | 3.5 | 4 | import json
person = {
'firstname':'Anitha',
'Lastname':'Sarangan',
'age':42,
'address':{"streeraddress":"22 301 Palisades way",
"Zip":"t8h0t4"
}
}
with open('person.json','w') as f:
json.dump(person,f)
# Serializing json
json_object = json.dumps(p... |
9b381446f85c86c9b92fb0749fe97301418828ff | Anjustdoit/Python-Basics-for-Data-Science | /string_try1.py | 546 | 4.25 | 4 | name = "hello"
print(type(name))
message = 'john said to me "I\'ll see you later"'
print(message)
paragraph = ''' Hi , I'm writing a book.
I will certainly do'''
print(paragraph)
hello = "Hello World!"
print(hello)
name = input('What is your name ? --> ')
print(name)
# What is your age ... |
ae9a225c662d62328786f62af88cc5f84a4fd011 | Church-17/python_tools | /listPrimes.py | 719 | 3.71875 | 4 | from itertools import repeat
def true_primes(n: int) -> list[bool]:
nodd = (n - 1)//2
is_prime = [True] * nodd
for p in range(int((n**.5 - 1)/2)):
if is_prime[p]:
is_prime[2*p**2 + 6*p + 3 :: 2*p + 3] = repeat(False, len(range(2*p**2 + 6*p + 3, nodd, 2*p + 3)))
return [True]... |
9b716094b814eee649f76f8dd476f55653ed0e29 | YogeshBarai/Cialfo_CoderByteTest | /ArraySearch.py | 352 | 3.671875 | 4 | import numpy
# Test array
arr = numpy.array([
[ 2, 3, 4, 10, 40 ],
[ 50, 60, 70, 80, 90 ]
])
x = 10
# Method 1
result = numpy.argwhere(arr == x)
if len(result) > 0:
print("Element found at index: ", str(result))
else:
print("Element is not present in array")
# Method 2
print(*(z... |
8fb75936d7f7b691dd43e704536eb889599c11dc | leticiadesouza/AulasParticulares | /Joao/Aulas16-01/Exercicio10.py | 157 | 3.75 | 4 | celsius = int(input("Informe a temperatura em celsius: "))
farenheint = ((celsius/5) * 9) + 32
print("A temperatura em farenheit equivale a: ", farenheint) |
21508f33de349eecd51f7917fef03f1bc08709c9 | leticiadesouza/AulasParticulares | /Preparatorios/exerciciosTeste2/exercicio13.py | 709 | 3.84375 | 4 | # Faça um programa que receba a altura e o sexo de uma pessoa e calcule e mostre seu peso ideal,
#utilizando as seguintes formulas ( onde h corresponde a altura):
# Homens: (72.7 * h) – 58 / Mulheres (62.1 * h) – 44,7
sexo = input('Informe seu sexo (M/F): ')
altura = float(input('Informe sua altura (em metros): '... |
79bb43cae97c861aa3170c0e369ea4e2e323a730 | leticiadesouza/AulasParticulares | /Preparatorios/exerciciosTeste1/exercicio8.py | 217 | 4.0625 | 4 | # Faca um algoritmo que receba um valor dado por um usuario em metros e o retorne o valor em centimetros ao usuario
metros = int(input('Informe o valor em metros: '))
print('O valor em centimetros eh', metros * 100)
|
48eb2136104f2fbfad4ec06b9f0b1b52fd864b85 | leticiadesouza/AulasParticulares | /Isa/exercicio9.py | 114 | 3.921875 | 4 | import math
x= int(input('informe a medida do raio do circulo: '))
print('a area do circulo é:' ,(2*math.pi*x)) |
257f395d43b1d68a3cf4d49b7c923de6b2503fc3 | anksaini/pycharmprojects | /ch3.py | 1,999 | 3.953125 | 4 | import random
import sys
import os
# p51
'''
die1 = random.randint(1,6)
die2 = random.randrange(6)+1
print("You rolled a ",die1," and a ",die2," for a total of ",die1+die2)
#p54
password = input("Enter password : ")
if password == "secret":
print("Access granted")
print("You important")
else:
print("Ac... |
5158fcbc4b170cbd25ab001d6bc60c8c7a33e8a6 | MuhammadAbuelenin/Data_Structure | /18_quick_sort_exercise.py | 1,078 | 4.03125 | 4 | def swap(a, b, arr):
if a != b:
tmp = arr[a]
arr[a] = arr[b]
arr[b] = tmp # another swaping wat ==> arr[a], arr[b] = arr[b], arr[a]
def quick_sort(elements, start, end):
if start < end:
p = partition(elements, start, end)
quick_sort(elements, start, p-1)
quick_... |
ff06754b4de27292da311afd8194de22b07de444 | swag1ong/ray | /release/serve_tests/workloads/serve_test_utils.py | 5,509 | 3.5 | 4 | #!/usr/bin/env python3
import re
def parse_time_to_ms(time_string: str) -> float:
"""Given a time string with various unit, convert
to ms in float:
wrk time unit reference
https://github.com/wg/wrk/blob/master/src/units.c#L17-L21
Example:
"71.91ms" -> 71.91
"50us" -> ... |
c240b447dcfee774d53abc8edbbf6cd4def65288 | goodboy-kr/python-study | /study/stu.py | 123 | 4.03125 | 4 | for num in range(2, 10):
if num % 3 == 0:
print("Found", num)
continue
print("not Found", num)
|
b11cea6096a4b1d087063948bf5c2efd4a9294ee | IamLakhan/Third_Year_Lab_Assignments | /Database Management System Lab/A14JSON/A14JSON.py | 2,365 | 3.6875 | 4 | '''
NAME: VAIBHAV BHAVSAR
TE-B
ROLL NO: 08
ASSIGNMENT NO 14:
Create employee array objects containing employee id , name, designation, salary using json and write a program in python to read and display the employee information.
'''
import json
with open('dbms.json') as f:
data = json.load(f)
def main():
d... |
b4530ccafadb722a0f63b12c30da3b6a7995f862 | AndersHam/DAT120_eksempler | /Testing/For klokke.py | 247 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 7 20:16:11 2021
@author: -anders-
"""
for time in range(24):
for minutt in range(60):
for sekund in range(60):
print(time, ": ", minutt, ": ", sekund) |
e247165867e0bf115ba191b4044687c42e41eef0 | AndersHam/DAT120_eksempler | /Testing/Lister/Mengder.py | 907 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 15:20:41 2021
@author: -anders-
"""
mengde = set()
mengde.add("Henrik")
mengde.add("Petter")
mengde.add("PEtter")
mengde.add("Anders")
for element in mengde:
print(element)
mengde.remove("PEtter")
for element in mengde:
print(elem... |
0833375cdbc335d6f5d52d9260744d500b35e239 | 7thCode/streamlit | /st_matplotlib.py | 841 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import streamlit as st
from matplotlib import pyplot as plt
import webbrowser
def main():
url = 'https://matplotlib.org/stable/gallery/index.html'
if st.button('matplotlib'):
webbrowser.open_new_tab(url)
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30... |
d50626ac217a242938030eb2621bc6263893c191 | martinak1/diceman | /diceman/roll.py | 2,993 | 4.25 | 4 | import random
def roll( num: int = 1, sides: int = 6) -> list:
'''
Produces a list of results from rolling a dice a number of times
Paramaters
----------
num: int
The number of times the dice will be rolled (Default is 1)
sides: int
The number of sides the dice has (Default is ... |
b2e16c670fad8dbeeac8d9cb52cf0bf6ceab591b | KevinJBenoit/advent_of_code_2019 | /day3/day3.py | 5,238 | 3.65625 | 4 | import csv
import os
def organize_csv(file):
"""
read in the csv file and organize the rows into dictionary variables
"""
os.chdir(r'C:\Users\Kevin Benoit\OneDrive\Code\AdventOfCode2019\day3')
#create containers for both rows
tuples1 = []
tuples2 = []
with open(file, 'r') as csv_fi... |
93d99812ce9b8a3b3274fc1f658cf7ecd282a002 | stralar/MoonGen | /scripts/tcp-handshake_client.py | 758 | 3.53125 | 4 | import socket
import time
host_ip, server_port = "10.1.3.3", 9999
data = "Hello World\n"
# Initialize a TCP client socket using SOCK_STREAM
#tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for i in range(50000):
print(i)
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
... |
a0996651156bf6d9ded84b43f7e5cbd59c6f8f11 | Overlord-slayer/Ejercicio3part2 | /Ejercicio3part2.py | 8,275 | 4.0625 | 4 | '''Ejercicio 3, parte 2 (Cadenas, listas y diccionarios)
"Supermercado Familiar"
Nombre: Josué Samuel Argueta Hernández
Carne: 211024
Fecha: 16/03/2021'''
import os
def principal():
# diccionariarios
expediente_cant = {'leche': 20, 'mantequilla': 15, 'queso': 15, 'yogurt': 35, 'manzanas': 35, 'naranjas': 40,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.