blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
4ebe420357dcb5675f940fd28916f72fc1792bc0 | tlima1011/python3-curso-em-video | /ex060_fatoriais.py | 520 | 3.9375 | 4 | from math import factorial
from time import sleep
def while_fatorial(n):
f = 1
print(f'{n}! = ', end='')
sleep(0.5)
while n > 0:
print(f'{n}', end='')
print(' x ' if n > 1 else ' = ', end='')
f *= n
n -= 1
return f'{f}'
def for_fatorial(n):
f ... |
dfe128fa19d1c7477b735a9d2ddb62965066ce62 | PeterWolf-tw/ESOE-CS101-2015 | /B04505004_HW02-2.py | 1,186 | 3.921875 | 4 | # !/usr/bin/env python3
# -*- coding:utf-8 -*-
#下次想寫第二解、第三解…乃至第 N 解時,請寫在同一個檔案裡即可。
def bin2int(x):
decimal = 0
value = 1
if x >= 0:
x = x
while x > 0:
remainder = x % 10
if remainder == 1:
decimal = decimal + value
elif remainder == 0:
... |
927cdb13ed4ef054f16201a0a4bae91e7d4f26e6 | daniloaleixo/30DaysChallenge_HackerRank | /Day02_Operators/operators.py | 1,633 | 4.21875 | 4 | # Objective
# In this challenge, you'll work with arithmetic operators. Check out the Tutorial tab for learning materials and an instructional video!
# Task
# Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal pri... |
bf0f29812143f9d7b6ab361af9eb67eed5a7eb09 | Frankiee/leetcode | /string/1156_swap_for_longest_repeated_character_substring.py | 2,797 | 4.03125 | 4 | # https://leetcode.com/problems/swap-for-longest-repeated-character-substring/
# 1156. Swap For Longest Repeated Character Substring
# Given a string text, we are allowed to swap two of the characters in the
# string. Find the length of the longest substring with repeated characters.
#
#
# Example 1:
#
# Input: text =... |
84cb838843827d50d4c37f50bbb7be53458b92f7 | Raafi101/CSCI133 | /UnitTests/test11Stuffs/test11.py | 5,404 | 3.796875 | 4 | #CS133 Test 11
#Raafi Rahman
#Pong
from tkinter import *
from random import choice
import time as tm
def clock():
return tm.perf_counter()
#Score
p1Score = 0
p2Score = 0
winner = False
# Ball and its velocity
ball, velx, vely = None, 100, 100
field = None
previousTime = 0
keyboard = {'Up':... |
0464161a906b0632c5e2f98c2c0455eaae0a1cc2 | ChangxingJiang/LeetCode | /0601-0700/0687/0687_Python_1.py | 1,194 | 3.765625 | 4 | from toolkit import TreeNode, build_TreeNode
class Solution:
def __init__(self):
self.max = 0
def longestUnivaluePath(self, root: TreeNode) -> int:
def helper(node):
if not node:
return 0
left_length = 0
right_length = 0
if node... |
c29bcd2e478f90a98475a313dd57bf37ad7784af | ctiijima/Train-Custom-Speech-Model | /data/rtf-to-csv.py | 1,521 | 3.53125 | 4 | # Converts all rtf files in a given folder into a single CSV with
# a file name column. This is intended for use in preprocessing
# RTF files typically used by the medical industry for consumption
# outside of Windows.
#
# This requires the striprtf module to be installed.
from __future__ import print_function
from ... |
ac38b483a71dedd9e16283a4620678579cfae2d5 | LennyDuan/AlgorithmPython | /78. Subsets/answer.py | 416 | 3.71875 | 4 | def subsets(nums: list()) -> list():
results = []
n = len(nums)
def backtracking(index=0, curr=[]):
if len(curr) == k:
results.append(curr[:])
for i in range(index, n):
curr.append(nums[i])
backtracking(i + 1, curr)
curr.pop()
for k in r... |
c0cd0445022f4b8d628f739199eb9995de4bfefc | Demon-tk/Gen-Prim-Roots | /main.py | 1,192 | 3.9375 | 4 | import sympy
from math import gcd
def get_input():
return input("Enter your number: ")
def power(x, pow, n):
return sympy.Pow(x, pow) % n
def calculate_first_prim_root(n):
# Check if number is prime
if not sympy.isprime(n):
print("{} is not a prime number, and cannot be a generator".format... |
3b5572be67933a76d32f848c91f770410e811fa9 | type-coder-engineer/Project-Euler | /pb53.py | 519 | 3.546875 | 4 | #coding: utf
import time, math
def combinatoric_nb(n, r):
return math.factorial(n) / math.factorial(r) / math.factorial(n - r)
def solve():
res = 0
for n in xrange(1, 101):
for r in xrange(1, n + 1):
if combinatoric_nb(n, r) > 1000000:
res += 1
return res
if __... |
3a3aa8acd6bbcfa5788072d2faa2f0b2e222407f | garrettsc/cpp_for_python_programmers | /topics/01_printing/print.py | 388 | 4.15625 | 4 | # Note that with Python, there is no need to import a library
# in order to print to the console.
#Printing a literal - Automatically attaches a newline character
print("Hello World")
#Print a literal - Replace the default newline character with a space
print("Hello World, again.", end=" ")
#Printing with formattin... |
117fc89386a2aa12ead6d50b0826b3e548047730 | glyif/AirBnB_clone | /tests/test_models/test_city.py | 1,009 | 3.71875 | 4 | #!/usr/bin/python3
import unittest
from models.city import City
class TestCity(unittest.TestCase):
""" test model: city """
def setUp(self):
""" standard setUp() """
self.model = City()
def test_public_attr(self):
"""
check if public attribute exists and if equal to empty ... |
968ce0a5bb7a0b3629f7082b34eab4feb2569866 | henryscala/leetcode | /py/p30_findSubStr.py | 5,331 | 3.578125 | 4 | # problem30 of leetcode
class Solution:
#variables defined here are called class variables,
#that are shared by all instances
#word_index_dict_dict = {}
#word_count_dict = {}
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]... |
9d0eb65c706c19b0a15719a0a53fb7d26bee15c3 | snoplusuk/echidna | /echidna/scripts/dump_shrink.py | 3,677 | 3.65625 | 4 | """ Example shrinking script
This script:
* Reads in spectrum from hdf5.
* Shrinks spectrum with user input pars and low high values.
* Saves shrunk spectrum to given output or, by default, to the same
directory with _shrink added to the filename.
Examples:
To shrink hdf5 file ``example.hdf5`` that has di... |
fc74417af5367aa0e925667eb916fc3ce142f409 | angus0507/Python0723 | /d08/BMIApp.py | 383 | 3.578125 | 4 | import d08.BubbleSort3 as bb
rows = [
{'h':170, "w":60},
{'h':160, "w":55},
]
#rows = bb.sort('h', rows)
#rows = bb.sort('w', rows)
# code here...
#根據BMI來排序
for row in rows: #不懂
w = row.get('w')
h = row.get('h')
bmiValue = w/((h/100)**2)
row.setdefault("bmi", bmiValue)
... |
c1339d15dd842f16f3b70b29057e71db842a6042 | JavaRod/SP_Python220B_2019 | /students/j_virtue/lesson09/activity/locke_manager.py | 1,583 | 4.4375 | 4 | '''Module to control lock system'''
# Advanced Programming in Python -- Lesson 9 Activity 1
# Jason Virtue
# Start Date 3/01/2020
class Locke:
'''Class to open and close locke'''
def __init__(self, capacity):
'''Initialize the locke class'''
self.run_pump = True
self.open_door = Fal... |
4988b60a1fb6bcf3bb1cd103106dd68607479ee0 | PeterBeard/math-experiments | /persistence.py | 1,002 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Check the multiplicative persistence of a number
"""
import argparse
import operator
def multiply_digits(n):
"""
Multiply together the digits of a number
"""
digits = str(n)
product = reduce(operator.mul, map(int, digits), 1)
return product
def get_persistence_cha... |
7e5f81bce0740f26b07afc8a1a8eed4d199152a7 | joseph-m-manley/AoC-2018 | /Day 1/part2.py | 514 | 3.765625 | 4 | #!/usr/bin/python
def get_changes():
with open('input.txt') as file:
return [ int(x) for x in file.readlines() ]
def main():
changes = get_changes()
current_freq = 0
frequencies = { current_freq }
while True:
for change in changes:
current_freq += change
... |
84e66dbe36492aec3dbc1a672a80c3ee087c83d1 | khaliliShoja/Recursive | /Recursive/5.py | 592 | 3.921875 | 4 |
# coding: utf-8
# Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.
# In[3]:
l=[3,0,0]
c=""
def param(l,c):
if(l[1]==l[0] and l[2]==l[0]):
print(c)
#print("salam")
return
elif(l[1] >= l[2]):
if(l[1]==l[0]):
c1=c[:]
... |
bc270ee94b4fd1e3fe194933657a93ae7cd40e64 | akront1104/NYC_Parking_Violations | /Mapper_Hour_Count.py | 447 | 3.5 | 4 | #!/usr/bin/python
"""Mapper: emits tuples in the form (hour = [0,..,24], 1)
"""
import sys
import re
for line in sys.stdin:
if re.search('^\d', line): # if line starts with a digit
record = line.strip().split(',')
ticket_time = record[19]
try:
hour = int(ticket_time[:2])
... |
fc54fe330a8fcc7e62560ac9c979bb57552fd8e2 | shaiwilson/algorithm_practice | /may12.py | 382 | 3.875 | 4 |
def compress(theStr):
""" implement a method to perform basic string compression """
outstring = []
lastChar = ""
charCount = 0
for char in theStr:
if char == lastChar:
charCount += 1
else:
if lastChar != "":
outstring.append(lastChar + str... |
1b70756d92c29d6390b449638c7fa4fd62fb8393 | 924235317/leetcode | /7_reverse_integer.py | 296 | 4.03125 | 4 | def reverse(x: int) -> int:
tmp = x if x > 0 else -x
res = 0
while tmp:
res *= 10
res += tmp % 10
tmp //= 10
res = res if x > 0 else -res
return res if -(2**31) <= res <= 2**31 else 0
if __name__ == "__main__":
x = -102
print(reverse(x))
|
94a0225a07242ec9d0732decf5cac39c125caf15 | BigOz/whats-for-dinner | /src/scale_images.py | 4,832 | 3.75 | 4 | '''
Scales all the images in a folder. The images will be read from one directory,
and renamed in placed in a parallel directory.
Images to be processed should be placed in a folder within the "images"
directory titled "original_images". It is assumed currently the images will be
.JPEG images. Images should be placed ... |
702cd1c5dcb954ae11bbc4bd05fadab265881c05 | rickpaige/dc-cohort-week-one | /day3/garage.py | 200 | 3.65625 | 4 | garage = ["Nissan", "Ford", "Toyota", "Jeep", "Honda"]
print(f"There are {len(garage)} cars")
garage.append("Chevy")
print(garage)
garage.pop(5)
print(garage)
garage.remove("Nissan")
print(garage)
|
35ed439c89bfc4ba405c5d5f572354e3a1610bea | shubhangi2803/Python-Exercise | /Python-Exercise/4.py | 167 | 3.703125 | 4 | v=input("Enter commma separated values : ")
#changing to list
l=v.split(',')
print("List :")
print(l)
#changing to tuple
t=tuple(l)
print("Tuple :")
print(t)
|
944ccc797e38e81d7c340f941fdb50610f854224 | ZombieSocrates/ThinkBayes | /code/03chapter_exercise1.py | 3,682 | 3.984375 | 4 | """This file contains code for use with "Think Bayes",
by Allen B. Downey, available from greenteapress.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
Exercise from chapter 3 introduced the power law (1/x)^(-alpha),
but assumed that any train we saw came from one company of... |
69270b2db512dd19ffb7c8858b0cc7e389976be0 | pawpaw2022/Coronavirus-web-scraper-and-Voice-assistant | /voice_assistant.py | 792 | 3.640625 | 4 | import pyttsx3
import speech_recognition as sr
"""Make sure your computer has installed:
1. pyaudio (if fails, go search google)
2. speechrecognition
3. pyttsx3
4. pywin32 (if using windows system) """
class voice_assistant:
def __init__(self):
pass
# Make python to ... |
5d5bf5e5b6e2cc4c9f46634daca367705b2e7f27 | Aleksei741/Python_Lesson | /Алгоритмы и структуры данных на Python/Lesson07/Task3.py | 2,354 | 3.84375 | 4 | # 3. Массив размером 2m + 1, где m — натуральное число, заполнен случайным образом. Найдите в массиве медиану.
# Медианой называется элемент ряда, делящий его на две равные части: в одной находятся элементы, которые не меньше медианы, в другой — не больше медианы.
# Примечание: задачу можно решить без сортировки исходн... |
3c16929f1aefa64128c761b01f438894a8aae837 | colorfulclouds/python | /3.py | 1,139 | 3.890625 | 4 | #循环
#for循环
names=['fei','yu','maomao']
for name in names:
print(name)
#计算1-100的和
#list(range())构造一个list 类似于构造函数
sum=0
#下面两种写法一样的
#for number in range(101):
for number in list(range(101)):
sum+=number
print("sum:%d" % sum)
#欢迎信息
L = ['Bart', 'Lisa', 'Adam']
for name in L:
print("hello,%s" %name)
n=1
while n<=5:... |
79dba129aad38c129295899a8dde183d07da24e0 | TianGong42/PythonPractice | /chapter3/ex3_2.py | 300 | 3.71875 | 4 | # 继续使用练习3-1中的列表,但不打印每个朋友的姓名,而为每人打印一条消息。每条消息都包含相同的问候语,但抬头为相应朋友的姓名。
names = ['孔子', '庄子', '老子']
print('Hi, ' + names[0])
print('Hi, ' + names[1])
print('Hi, ' + names[2])
|
da52c988c7dfa46f4253a181943bf3fadecdd5e3 | kiberius/stash | /test.py | 367 | 3.921875 | 4 | def Input():
global limit
try:
limit = int(input('Define the limit: '))
Main()
except:
print('Please enter an integer.')
Input()
def Main():
x = 0
y = 1
for i in range(limit):
print(x)
z = x + y
x = y
y = z
... |
f2b8a162fe22876f9c7167e6f425331095b8fe22 | Jensvans/Make1.2.1 | /make 1.2.1 deel 2/leefdtijd 100.py | 806 | 3.75 | 4 | #!/usr/bin/env python
"""
Een python script dat het volgende doet:
vraagt achter je leeftijd
berekent in welk jaar je geboren bent en dat ook als output meegeeft
berekent in welk jaar je 100 jaar zal zijn en dat ook als output meegeeft
"""
import datetime
__author__ = "Jens Vansteenvoort"
__email__ = "jens.vansteenv... |
1cf8750f1c8ddea30b128fd11f37e7fdba9792e8 | gabriellaec/desoft-analise-exercicios | /backup/user_102/ch92_2019_10_02_17_25_03_952153.py | 328 | 3.75 | 4 | def listanovas(dicionario):
listanova = []
lista_keys = list(dicionario.keys())
lista_values = list(dicionario.values())
for i in lista_keys:
if i not in listanova:
listanova.append(i)
for e in lista_values:
if e not in listanova:
lista.append(e)
print(lis... |
ac6b6cfc60f932db4f48829308b3ea812863762c | ArnoBali/python-onsite | /week_02/07_conditionals_loops/Exercise_02.py | 1,072 | 4.34375 | 4 | '''
Take in a number from the user and print "Monday", "Tuesday", ...
"Sunday", or "Other" if the number from the user is 1, 2,... 7,
or other respectively. Use a "nested-if" statement.
'''
input_ = int(input("Please input a number between 1 - 7: "))
if input_ > 1:
if input_ > 2:
if input_ > 3:
... |
f593c88ad7908f15a4c63b0efdc78966ced1a99d | bilalrahim/Python-practice | /circle.py | 241 | 3.71875 | 4 | pi = 3.14159
def area(radius):
return pi*(radius**2)
def circumference(radius):
return 2*pi*radius
def sphereSurface(radius):
return 4.0*area(radius)
def sphereVolume(radius):
return (4.0/3.0)*pi*(radius**3)
t=1
while(t<2):
print t
|
47cb185950f9542b9409a00462f9d262c9fe6d4c | lhr0909/SimonsAlgo | /_peuler/100-200/116.py | 345 | 3.671875 | 4 | from math import factorial
def choose(m, n):
return factorial(m) / (factorial(n) * factorial(m - n))
def fillTiles(l, n, x):
k = x - l * n
return choose(k + n, n)
def findTotal(n):
s = 0
for i in xrange(2, 5):
for j in xrange(1, n / i + 1):
s += fillTiles(i, j, n)
retu... |
607a49c0ac72e6766008da740edfc18b28931e9f | Mah-sia/assignment-4 | /4_WordCounter.py | 253 | 3.546875 | 4 |
def WC(t):
c=0
space=False
for i in t:
if i==" ":
if space==False:
c=c+1
space=True
else:
space=False
print(f"Word {c+1}")
WC("I am mahsa")
|
0a6b72ebaeee3c3be9fb2fe1fd7b8d04a8e038bc | bhanugudheniya/Python-Program-Directory | /PythonHome/DataTypes/Basic/ArithmeticOperation.py | 582 | 4.15625 | 4 | print("Enter 1 for Addition \n Enter 2 for Subtraction \n Enter 3 for Multiplication \n Enter 4 for Division \n")
choice = int(input("Enter Your Arithmetic Operation Choice"))
if choice<1 or choice>4:
print("Invalid Choice")
else:
num1 = int(input("Enter First Number"))
num2 = int(input("Enter Second Number"))
if ... |
5d25ff230e3a0fe78593f5589e035323d90ef403 | yakubpeerzade/repo1 | /class_object/student2.py | 398 | 3.75 | 4 | class student:
def det(self):
self.name=input("Enter Name:")
self.rno=int(input("Enter rollo:"))
self.marks=int(input("Enter Marks:"))
def display(self):
print("Student Name:",self.name)
print("Roll Number:",self.rno)
print("Marks obtained:",self.marks)
s1=student... |
a409f4be55e3ec0bfc196d32c434b7e0f7f3f85a | afonsoMatheus/Algorithm_Design | /Projeto 3/ts_classification.py | 2,978 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
import math
import heapq as hp
import time
import sys
'''
DTW (Dynamic Time Warping) is a dynamic programing algorithm thats compares two temporal series,
using a bottom-up approach. It's uses the distance function to calculate the distance between two poits
from the series, wit... |
95c24ed8710d24129e5f4b176d5a4399193d935b | tnycnsn/Image-Morphing | /Part1.py | 3,181 | 3.796875 | 4 | import numpy as np
import dlib
import cv2
detector = dlib.get_frontal_face_detector()
#The detector object is used to detect the faces given in an image.
#It works generally better than OpenCV’s default face detector.
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
#To predict the l... |
5ccc9b9bf570b0f4e369e7fa58805263da345a13 | pedropenna1/Exercicios-Python | /exercicio 56.py | 841 | 3.609375 | 4 | somaidade = 0
mediaidade = 0
maioridadehomem = 0
nomevelho = 0
totmulher20 = 0
for n in range (1, 5):
print(('------ {}ª pessoa -----: '.format(n)))
nome = str(input('Digite o nome: ')).strip()
idade = int(input('Digite a Idade: '))
sexo = str(input('Digite o sexo [M/F]')).strip()
somaidade = somaid... |
bb3e94f6c1cdacc015bbb29b85191ea1d0d12e21 | md3997/Cryptography | /Transposition/railfence.py | 1,106 | 3.671875 | 4 | import math
def railFenceEncrypt(pt):
pt = pt.replace(" ", "")
pt = pt.lower()
s1 = ''
s2 = ''
for i, ch in enumerate(pt):
if i % 2 == 0:
s1 = s1 + ch
else:
s2 = s2 + ch
return (s1 + s2).upper()
def railFenceDecryp... |
3776742d06d29c2ba458dbe7c9f6746af04798e7 | zeopean/pycode | /code 015 11/demo.orderedDict.py | 315 | 4.09375 | 4 | #!/usr/bin/python3
from collections import OrderedDict
items = (
('A' , 1),
('B' , 2),
('C' , 3)
)
demoDict = dict(items)
orderedDict = OrderedDict(items)
print('Regular Dict:')
for key , val in demoDict.items():
print(key , val)
print("Ordered Dict:")
for key ,val in orderedDict.items():
print(key ,val)
|
9ceacf4b5fd47f96291f172da6135ef22b0b3fea | Andken/ProjectEuler | /prob66.py | 1,366 | 3.921875 | 4 | # Problem 66
import math
def is_square(n):
return math.sqrt(n).is_integer()
def is_square2(n):
h = n & 0xF
if h > 0x9:
return False;
if (not h == 0x2 and
not h == 0x3 and
not h == 0x5 and
not h == 0x6 and
not h == 0x7 and
not h == 0x8):
return m... |
ab850dc678a0950b2719849d6ff88beee24ead4d | Python-lab-cycle/AparnnaPython | /CO1.9.CHARACTER CHANGED'.py | 207 | 4.21875 | 4 | #Create a string from given string where first and last characters exchanged
str1=input("Enter a String:\n")
print("String after swapping first and last character:\n",(str1[-1:]),(str1[1:-1]),(str1[:1])) |
8d98032e6e717abc39efb26bed2b51a597699ab2 | eduardouliana/uri-challenges | /1036.py | 441 | 3.578125 | 4 | a, b, c = [float(x) for x in input().split()]
msg = 'Impossivel calcular'
delta = ((b ** 2) -4 * a * c)
if (delta < 0):
print(msg)
exit()
# elevando um número na potência 0.5, é o mesmo que fazer a raiz quadrada
raiz = (delta ** (1/2))
divisao = (2 * a)
if (divisao <= 0):
print(msg)
exit()
x1 ... |
005266c9a985efe53a1538c6a24fba5129fe5f0b | Koozzi/Algorithms | /interview/DataStructure/hash/hash.py | 700 | 3.953125 | 4 | def hash_function(key):
"""
Hash function ...
"""
return 1
def find_slot(key):
"""
key exist -> Return current key's slot#
key not exist -> Return the slot# into which key will be placed
"""
slot = hash_function(key)
start = slot
while H[slot] and H[slot].key != key:
... |
068e421c2b187010fcadbe7b0c1d71a708d1d91c | wapj/pyconkr2019tutorial | /async_example/iterator3.py | 238 | 4.15625 | 4 | nums = [1, 2, 3, 4, 5]
# iter, next 를 직접 호출해서
# 잘 동작하는지 실행해봅시다.
it = iter(nums)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
# 여기서 중단됨
print(next(it))
|
a4f07d12ecab5010a691d274fd8aff2fd965ddd3 | poojasgrover/pythonwork | /day3.py | 1,146 | 4.75 | 5 | #!/usr/bin/
################################################
# Dictionary manipultion in Python #
# Simple Code for understanding purpose only #
# A dictionary is {key,value} #
################################################
################################################
# Function ... |
320a01086054fc287450f92877e7858317c7c562 | cuongmv88/ProjectEuler | /problem39.py | 1,178 | 3.8125 | 4 | import time
import math
def calculate_time(func):
def inner1(*args, **kwargs):
begin = time.time()
returned_value = func(*args, **kwargs)
end = time.time()
print("Total time taken in : ", func.__name__, end - begin)
return returned_value
return inner1
... |
2476aee99e86ef4b5a7af10a4838af42afb8b850 | FD70/gb_python_base | /les2/task3.py | 1,018 | 4.1875 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
input_month = int(input("Введите месяц от 1 до 12: "))
WINTER = (12, 1, 2)
SPRING = (3, 4, 5)
SUMMER = (6, 7, 8)
AUTUMN = (9, 10, 11)
m_... |
0ef8a03d1ba401ccb0205e061c46b56bf46d9ec7 | MonkeyNi/yummy_leetcode | /slide_window/5739.py | 651 | 3.671875 | 4 | class Solution:
"""
这个问题实际上就是找符合条件的最长子序列,记录最长长度就可以
Sliding window, O(n)
"""
def maxFrequency(self, nums, k):
if not nums:
0
nums = sorted(nums)
res = 1
start = 0
for end in range(len(nums)):
k += nums[end]
if k < nums[end] *... |
3d1313ec259efabbb150a11354b5bb3c30a14606 | shakeelashaik/python | /loops class/demo8.py | 290 | 4 | 4 | z=0
for x in range(7,0,-2):
for y in range(z):
print(end=" ")
for y in range(x):
print('*',end=" ")
z+=1
print()
z=2
for x in range(3,8,2):
for y in range(z):
print(end=" ")
for y in range(x):
print('*',end=" ")
z-=1
print() |
549642d8e04c8473b44d9aba2ece24e4c9b2f192 | yidaiweiren/Python | /study/day2/在列表的末尾添加元素.py | 194 | 3.625 | 4 | #在列表的末尾添加元素
#使用append('value')方法
str=['name1','name2','name3']
print (str)
str.append('name4') #appwnd()方法,在列表后面追加添加一个值
print (str)
|
10251c333e2d18f8c3b6c3684cdc7340537d1294 | JaeCoding/keepPying | /foo/lc/leetcode/editor/cn/[974]和可被 K 整除的子数组.py | 1,176 | 3.53125 | 4 | # Given an array A of integers, return the number of (contiguous, non-empty) sub
# arrays that have a sum divisible by K.
#
#
#
#
# Example 1:
#
#
# Input: A = [4,5,0,-2,-3,1], K = 5
# Output: 7
# Explanation: There are 7 subarrays with a sum divisible by K = 5:
# [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -... |
c7ba48819f26696853c3402b1ef669713a47aa41 | hplar/hackerrank | /algorithms/warmup/staircase.py | 171 | 3.5 | 4 | #!/usr/bin/python3.4
from sys import stdin
n = int(stdin.readline().strip())
stomp = '#'
space = ' '
for i in range(n):
print('{}{}'.format(space*(n-i), stomp*())) |
7b42cd884dd3cf926245211132815e74da88466f | DadSheng/Genetic-Algorithm | /Driver.py | 14,310 | 3.625 | 4 | from Algorithm import Init_run
import numpy as np
import pandas as pd
#import matplotlib.pyplot as plt
from random import randint
import random
import operator
import itertools
import statistics as stats
#############################################################################
#Initialization step
# Initialize... |
4f2e26214a5e0da2a875d9ee0bbde05f82e80f07 | zhangshichen0/python3-study | /day01/hello.py | 75 | 3.875 | 4 | print("hello world")
a = input("please input a num ");
print("num is " + a) |
afc837992bd64a15cf54ec2868e39b5b06d0d29c | ccwang002/pyapac_code_fighter | /questions/q_bad_default.py | 1,330 | 4.125 | 4 | '''Question bad_default: What's wrong? (Debug)
Description
-----------
Find the bug in the `answer` function.
The bug-free answer should insert all elements in the `values` argument
into an empty list and return it every time when answer function is
being called.
Examples
--------
>>> answer([1, 2, 3])
... |
114b026a7b0fafcc478965b347f0d12e8f69a4cf | yuanrouyu/learnPython | /28—31/car_add.py | 320 | 3.734375 | 4 | class Car(object):
def __init__(self,w,d):
self.wheels=w
self.doors=d
self.color=""
self.shape=""
def paint(self,c,h):
self.color=c
self.shape=h
mycar=Car(4,2)
mycar.paint("red","round")
print(mycar.wheels)
print(mycar.doors)
print(mycar.color)
print(mycar.shape)
|
60dacc5f4cf61e216c6ae7231d872533f378aba2 | DominicRochon/comp-1405-programs | /tutorial1/days.py | 872 | 4.40625 | 4 | month = input ('Which month? ')
valid = True
febMonth = False
if month == 'january' or month == 'march' or month == 'may' or month == 'july' or month == 'august' or month == 'october' or month == 'december':
days = '31'
elif month == 'april' or month == 'june' or month == 'september' or month == 'november':
da... |
7eb6001fff12931605a0ba13ccd4a2d7e04ac643 | JorgeGomezPhD/pclamp | /set_file_name.py | 249 | 3.53125 | 4 | # This file sets the file path and file name
import pyabf
folder = input("Enter folder name where data is stored: ")
file_number = input("Enter last 2 digits of file: ")
file_name = f"{folder}/{folder}0{file_number}.abf"
abf = pyabf.ABF(file_name)
|
2eed413d4c1ec5c15dfb91c70352d2bad086a88c | rohit-2019/HackerRank_Solutions | /Algorithms/Greedy/Max Min.py | 724 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 4 16:21:02 2020
@author: Ashima
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maxMin function below.
def maxMin(k, arr):
arr.sort()
n = len(arr)
min_diff = sys.maxsize-1
for i in range(0, n-k+1):
tem... |
c3f241367a2d46ec8fb62425123c5ce288a3b1c5 | MuhammadZahid9596/Python-Crash-course | /ex6.6edited.py | 261 | 3.65625 | 4 | favorite_languages = {
'jen': 'yes',
'sarah': 'yes',
'edward': 'no',
'phil': 'no',
}
for key,values in favorite_languages.items():
if values=='yes':
print("congratulations")
else:
print("sorry try again") |
0d76c125ffc41f760bcd7065f024cbc07e0e8829 | rwedema/BFVP3INF2 | /_book/sinus.py | 867 | 3.65625 | 4 | #!/usr/bin/env python3
"""
program that plots a sinus wave
usage: sinus.py
"""
__author__ = "F.Feenstra"
## CODE
import matplotlib.pyplot as plt
import numpy as np
import sys
sample_rate = 140
frequency = 4
amplitude = 2
phase = 0.5
def comp_y(t):
"""compute the y value of the sin wave at the for a specif... |
f43f97a7938ae54dfd00d4108c0bbeda4a9295a2 | kammitama5/Distracting_KATAS | /Is0grams.py | 290 | 3.75 | 4 | import numpy as np
def is_isogram(string):
w = list(string)
q = [element.upper() for element in w]
print(w)
if len(w) != len(set(w)):
#print("True")
return False
if len(q) != len(set(q)):
return False
else:
#print("False")
return True
|
726b0f8dc99cdc178b24a4000dab2835d18a467b | jeffreytzeng/HackerRank | /30 Days of Code/Day 12 Inheritance/student.py | 614 | 3.5 | 4 | class Student(Person):
def __init__(self, first, last, idNum, scores):
super().__init__(first, last, idNum)
self.scores = scores[:]
def calculate(self):
total = sum(self.scores)
average = total/len(self.scores)
if average > 100:
print("Score cannot over 100!"... |
a969a95e703fad29308e3ec4c3a85a90703e320f | ClassicVantage/StandardDeviation | /StandardDeviationProject.py | 478 | 3.890625 | 4 | import csv
with open("data.csv",newline='') as f:
reder=csv.reader(f)
file_data=list(reader)
data=file_data[0]
#finding mean
def mean(data):
n=len(data)
total=0
for x in data:
total+=int(x)
mean=total/n
return mean
sqaredList=[]
for no in data:
a=int (no)... |
30bfd8b8dd4b4658fad91819b958fe0ca4c26443 | gy6274858/7daypython | /day1/multi.py | 243 | 3.625 | 4 | def table():
#在这里写下您的乘法口诀表代码吧!
for i in range(1, 10):
for j in range(1, i+1):
print("%d * %d = %d" % (j, i, j*i), end='\t')
print()
if __name__ == '__main__':
table()
|
7971885fc8d3f11a8b87a19047d8cdcd6bc08791 | JeckyOH/LeetCode | /75_Sort_Colors/Solution.py | 1,184 | 3.84375 | 4 | class Solution_01(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
counter = [0] * 3
for num in nums:
counter[num] += 1
for i in range(len(nums)):
if (... |
9d92ae4ae7101fcc69eee2ab1f8b96e703aa070f | austinlyons/computer-science | /merge-sort/python/merge_sort.py | 876 | 3.875 | 4 | def merge(left, right):
out = []
l = 0
r = 0
l_len = len(left)
r_len = len(right)
while l < l_len and r < r_len:
if left[l] <= right[r]:
out.append(left[l])
l += 1
else:
out.append(right[r])
r += 1
if l < l_len:
out = ou... |
bc04ea1a588f0b7b2d74db8d06c3e85c2725e281 | itsolutionscorp/AutoStyle-Clustering | /all_data/cs61a/untarred backup/155.py | 1,267 | 4.125 | 4 | def num_common_letters(goal_word, guess):
"""Returns the number of letters in goal_word that are also in guess.
As per the rules of the game, goal_word cannot have any repeated
letters, but guess is allowed to have repeated letters.
goal_word and guess are assumed to be of the same length.
goal_word... |
1b49a9a577326aa004e6747a8690716f36187761 | crazywiden/Leetcode_daily_submit | /Widen/LC465_Optimal_Account_Balancing.py | 2,616 | 3.921875 | 4 | """
465. Optimal Account Balancing
A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for Bill's lunch for $10. Then later Chris gave Alice $5 for a taxi ride. We can model each transaction as a tuple (x, y, z) which means person x gave person y $z. Assuming Alice, Bill, and... |
f6896f860f6287b0831cbce145ca6e568806db5a | PlanetKev/KevTECH | /Number Sorter.py | 363 | 4.3125 | 4 |
numbers = []
# creating the list for sorting
# sort the array and print -
def sort(array):
array.sort()
print("Ordered Sequence: " + str(array))
num = int(input("Enter the length of the sequence: "))
# input length of the sequence
while num > 0:
add = int(input("Number: "))
numbers.app... |
7feeea707e6e7240d1e7d671da998321860a022a | Eric-BR2001/Univap-Lista-de-Exercicio-Python | /Primeiro Ano/7.py | 629 | 4.0625 | 4 | print("Digite o A:")
A= float(input())
print("Digite o B:")
B= float(input())
print("Digite o C:")
C= float(input())
print("Digite o D:")
D= float(input())
print("A SOMA de A com B é:",A+B)
print("A MULTIPLICACAO de A com B é:",A*B)
print("A SOMA de A com C é:",A+C)
print("A MULTIPLICACAO de A com C é:",A*C)
print("A S... |
8bc81b0cff92c2d1e61f09417c2b5f726711ad84 | EderOBarreto/exercicios-python | /ex069.py | 621 | 3.71875 | 4 | qtdMaiores = 0
qtdHomens = 0
qtdMulher = 0
while True:
print(' Cadastre uma pessoa')
print(30 * '-')
idade = int(input('Digite a idade: '))
sexo = input('Digite o sexo [M/F]: ').strip().upper()[0]
print(30 * '-')
if idade > 18:
qtdMaiores += 1
if sexo == 'M':
qtdHomens +... |
855a97cda84e0daf33e575d4a685977ea4653934 | Wren6991/HyperRam | /scripts/listfiles | 3,416 | 3.53125 | 4 | #!/usr/bin/env python3
import shlex
import os
import sys
import argparse
import re
help_str = """
Tool for building file lists, into formats required by various tools.
".f" files contain four types of command:
file (filename)
adds a file to the list
include (dir)
add a directory to include path, if output form... |
4222d5b30a6c16144c20aa1303f172b9ec4a6d9a | connor-mcshane/pyFinGraph | /pyFinGraph/sim/Element.py | 2,992 | 3.75 | 4 | """
The Elements. Elements are the smallest units in a model
"""
from abc import ABC, abstractmethod
import logging
class Element(ABC):
@abstractmethod
def apply(self):
pass
@abstractmethod
def subscribe_to(self, event):
pass
class Node(Element):
""" Nodes are any elements that ... |
f2cc725e6bef58e828a5ad4b0ca4bd4e76075439 | cxyxiaozhou/pythons | /text1.py | 217 | 3.953125 | 4 | while True:
try:
firstname=input("pelase input firstname:")
print(int(firstname))
except ValueError:
print("you's value in error not str")
else:
print(firstname) |
ec7127eaec35901519c0eaab589631db5b0830bd | sushilmchaudhari/allscripts | /time_calc.py | 394 | 3.546875 | 4 | def time_calc(time_in_seconds):
time_in_seconds = float(time_in_seconds)
day = time_in_seconds // (24 * 3600)
time_in_seconds = time_in_seconds % (24 * 3600)
hour = time_in_seconds // 3600
time_in_seconds %= 3600
minutes = time_in_seconds // 60
time_in_seconds %= 60
seconds = time_in_sec... |
a49ee34ec99b396f437b5b59f9da3666e82fc1b2 | leksiam/PythonCourse | /Practice/RyzhovD/RyzhovDenis_2_Game_objects.py | 2,507 | 4.3125 | 4 | """
Superclass and subclasses are created.
Different types of movement are defined as printable strings (for simplicity) \
as a function of speed.
Additional actions are added.
For class Reptile method move now depends on speed and artifact.
"""
class Master: #
def __init__(self, name):
# attribute defin... |
d822b25cfad9010bcbcbc45b298fadd38cf11ee6 | jramdohr/Coding-Challenges | /100 Python Challenges/#3.py | 574 | 4.1875 | 4 | #Question 3
#Level 1
'''
Question:
With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.
Suppose the following input is supplied to the program:
8
Then, the output... |
12ae4be1aaec94842f97e60baf8dba2c45c36680 | weiweiECNU/leetcode | /easy/961. N-Repeated Element in Size 2N Array/test.py | 509 | 3.5625 | 4 | # https://leetcode.com/problems/n-repeated-element-in-size-2n-array/
from collections import Counter
def isRepeated(A):
# b = Counter(A[:])
# return b.most_common()[0][0]
alist = []
for i in A:
if i not in alist:
alist.append(i)
else:
return i
A = [1,2,3,3]
B =... |
95893f2ec42caaf273835a7f933d8f7029ea7994 | filaone/codewars | /python_skills/052_replace_part_of_string.py | 596 | 3.671875 | 4 | #!/usr/bin/python
#-*- coding:utf-8 -*-
#**********************************************************
#Filename: 052_replace_part_of_string.py
#Author: Andrew Wang - shuguang.wang1990@gmail.com
#Description: ---
#Create: 2016-09-05 22:58:15
#Last Modifieda: 2016-09-05 22:58:15
#*******************************************... |
0fa76eec751af902563bc5ce66e2869bf910eaf9 | chvsree2007/gharial | /basics/no-of-spaces.py | 125 | 4.0625 | 4 | #!/bin/python3
string = input('Enter a string ')
l = string.split()
print('Total number of spaces in the string ',len(l)-1)
|
4ac8d408bfc2ed36eb674d157b32243f4e27f60a | yasir-web/pythonprogs | /splitfn.py | 278 | 4.3125 | 4 | #WAP to take user full name as input and display Short name
name=input("Enter Full Name: ")
shortname=name.split()
#print(shortname)
print("Your short name is =",end="")
for i in range(len(shortname)-1):
print(shortname[i][0]+".",end="")
print(shortname[len(shortname)-1])
|
d628f4790435ee5aad558fc49f88a670f2a84ed5 | PriyankaDeshpande9/PythonML | /Python_asg1.10.py | 288 | 4.15625 | 4 | '''10. Write a program which accept name from user and display length of its
name.
Input : Marvellous Output : 10'''
def main():
name = input("Enter the name : ")
cnt = 0
for i in name:
cnt+=1
print(cnt)
if __name__== '__main__':
main()
|
cf326441b8cd2224aa0e5d20b6389bdfb4aefcf5 | ReneNyffenegger/about-python | /statements/global/2-assign-to-var.py | 123 | 3.671875 | 4 | num = 42
def printNumAndIncrement(i):
print(num)
num = num + i
printNumAndIncrement(57)
printNumAndIncrement( 1)
|
a6c4b26c3f3b3de1172a98de83023dc7cde8b75a | AaayushUpadhyay/python-modules | /Error handling/exceptions.py | 1,294 | 3.875 | 4 | # 4 blocks of exception handling in python,
# jis part of code mei error ane ke chances ho woh try mei hoga
# apna khud ka exception banane ke liye we will create a class which inherits from the Exception class
# Aur hume Exception class ke constructor ko override karna padega
class ValueTooSmallException(Exception)... |
898be79380dcc5542e62097957628110c4ab0d68 | fercho1011/Statistical-LearningII | /9.4 NP-BackPropagation.py | 4,913 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 21 15:21:27 2019
@author: Fernando
"""
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
os.chdir(r"C:\Users\Fernando\Documents\STUFF\GALILEO\3-Machine Learning II")
tr = pd.read_csv('EntrenamientoPerceptron.csv')
def ReLu(... |
335231a2b543d171bf1f7def99ac40df482d1616 | Bharadwaja92/CompetitiveCoding | /CodeSignal/Python/MeetPython/CountBits.py | 853 | 4.53125 | 5 | """"""
"""
Implement the missing code, denoted by ellipses. You may not modify the pre-existing code.
Implement a function that, given an integer n, uses a specific method on it and returns the number of bits in its
binary representation.
Note: in this task and most of the following tasks you will be given a code snip... |
2fb8fb5422eea717244d6a95f8bfa44ddaf65bd8 | LukeBreezy/Python3_Curso_Em_Video | /Aula 14/ex062.py | 455 | 3.859375 | 4 | print('{:=^16}'.format(' PA '))
termo = int(input('Primeiro termo da PA: '))
razao = int(input('Razão da PA: '))
qtd_termos = 10
enesimo = termo + razao * qtd_termos
print('A seguir, os 10 primeiros termos da PA')
while termo < enesimo:
print(termo, end=' | ')
termo += razao
if termo == enesimo:
... |
2f6220b68d0d3fe65c7a1609abde60a36f9d116b | ThamirisMrls/Computer-Science | /hw19_Kallick.py | 1,134 | 3.78125 | 4 | '''
File: hw19_Kallick.py
Author: Daniel Dyssegaard Kallick
Description:counts word frequency
'''
def word_frequency(filename):
"""Takes a filename(string) as a parameter, returns a dictionary of
word frequencies"""
fin=open(filename,'r')
wordlist=fin.read().split()
fin.close()
wordfrequency={}
... |
3ba1d1c6981ab7d9fc28d23a8c1793bf5805d06b | neerja28/python-data-structures | /Tuples/tuples0.py | 866 | 3.609375 | 4 | # Find the top ten comman words using tuples
fhand = open("romeo.txt")
counts = dict()
for line in fhand :
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
lst = list()
for key,value in counts.items():
newtuple = (value, key)
lst.append(newtuple)
print(lst)
# [(1,... |
afc6f8a917404c2d5874499e733b435802b9871e | Steve-Jadav/LeetCode | /DetectCapitalUse.py | 576 | 3.6875 | 4 | class Solution:
def detectCapitalUse(self, word: str) -> bool:
"""Problem 520"""
allCaps = True
noCaps = True
firstCap = True
for i in range(0, len(word)):
if i == 0 and word[i].isupper():
firstCap = True
elif i != 0 and word[i... |
59b4e324950c642f796724c7e49c3feafd8b2602 | AmiraliNayerzadeh/cs50-Introduction-to-Computer-Science | /pset7/houses/roster.py | 527 | 3.734375 | 4 | # TODO
from sys import argv, exit
from cs50 import SQL
import csv
if len(argv) != 2:
print("missing command-line argument")
exit(1)
houses = argv[1]
db = SQL("sqlite:///students.db")
sql = "SELECT * FROM students WHERE house = %s ORDER BY last, first"
for row in db.execute(sql, houses):
if not row["... |
c4bab3d7e77289d7e29cda0520396514b01d6ca9 | xavierloos/python3-course | /Basic/Control Flow/Errors in Python/name_error.py | 770 | 3.90625 | 4 | # 1. In script.py, another teammate Alex wrote a Who Wants to Be A Millionaire question and four options. If the answer is an uppercase or lowercase “A”, then the score goes up.
# Run the program to check it out.
# 2. Oh no, there are two NameError errors!
# Can you find them both?
# Who Wants To Be A Millionaire ... |
6ef96b4ad72c894eacaa0e9cdf57359229fbc703 | kangsup/maybler0 | /day1_6.py | 135 | 3.59375 | 4 | #예제 3-7
number1 = input("숫자 10을 입력하세요")
changed1 = int(number1)
print (type(changed1))
print (changed1 + 30) |
f333814699208030bbb947f169f86ced61d0a711 | mayankvanjani/Data_Structures_and_Algorithms | /Class/class_3_20.py | 6,032 | 3.9375 | 4 | class BinaryTree():
class Node():
def __init__(self, left, right, parent, data):
self._left = left
self._right = right
self._parent = parent
self._data = data
class Position():
def __init__(self, node, tree):
self._node = node
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.