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 |
|---|---|---|---|---|---|---|
5ca0b430ee499b3972b3a27a1d3b229bad44327d | himangshupal719/spark_with_python | /8_python_crash_course/Python Crash Course.py | 953 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
print("My name is {}".format('Himangshu'))
# In[4]:
print("My name is {}, my number is int {}, my number is string {}".format('Himangshu',10, '20'))
# In[5]:
print("First: {x} Second {y}".format(x='xxx', y='yyy'))
# In[6]:
print("First: {y} Second {x}".forma... |
2dfef24873bd2ce61d53d32a0f8bfbf4b6217a86 | tangria/tangria | /MichaelTang_Dice_Challenge2.py | 4,349 | 4.25 | 4 | # File name: MichaelTang_Dice_Challenge2.py
# Due date: Thursday, July 22, 2021
# Description: This is an extra extension of the "Dice" homework.
# Not only will will print an integer number of
# asterisks to represent the percentage instead
# of a text-only output of h... |
1037ec97946801049e01e48dd802f708750e1e97 | Gayatri-Prathyusha/cspp1-assignments | /M5/GuessMyNumber/guess_my_number.py | 1,165 | 4.34375 | 4 | """Guess My Number Exercise
"""
def main():
"""
Main function"""
least = 0
low = 50
high = 100
guess = "Is your secret number: "
print("Please think of a number between 0 and 100!")
print(guess + str(least) + "?")
s_request = input("$$$Enter 'h' to indicate the guess is to... |
14e1cc3f05ba91652e0e7f7df645330fd84586ee | onnozweers/scripts | /replace-text-block | 1,293 | 4.21875 | 4 | #!/bin/python
# This script replaces text in a file. The search text and replacement text
# are in two other, separate files.
import os
import sys
import argparse
parser=argparse.ArgumentParser(
description='''Searches through a text file for a block of text and replaces it with another text block.''')
parser.... |
245f36325b74490294d90370bfc72446531fa039 | koichi21/LeetCode | /contest/brick_wall.py | 694 | 3.734375 | 4 | #!/usr/local/bin/python
class Solution(object):
def leastBricks(self, wall):
"""
:type wall: List[List[int]]
:rtype: int
"""
# store number of bricks for each column
d = {}
for r in wall:
sum = 0
for b in r[:-1]:
sum +=... |
84b986d1dd1efb4b244656b81467015868d1697d | rairai77/Machine-Learning-and-AI | /My Machine Learning Courseware/Clustering/K-Means Clustering/kmc.py | 1,475 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# Importing the data-set
dataset = pd.read_csv('Clustering/K-Means Clustering/Mall_Customers.csv')
x = dataset.iloc[:, [3, 4]].values
# Using the... |
6cb040fbd1da9d1ef1c4f4596f7e26657a04c4da | myotheone/machine_learning_101 | /lesson5_optimization/gradient_descent_optimization_intro.py | 7,113 | 3.640625 | 4 | #-*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def evaluate_gradient(loss_function, data, params):
"""计算loss_function对params的梯度,根据data的大小有不同策略。
"""
pass
#batch gradient descent
#目标函数是凸函数,保证收敛到全局最优点
#目标函数是非凸函数,保证收敛到局部最优点
#重复计算,每次都计算全部样本的梯度,在迭代轮次之间,可能会重复计算相同的梯度
#无法在线更新
#for i in r... |
73d50ea906a2a2ffa5f826b203fa6bda7c475328 | valboldakov/design-patterns | /python/observer/observer.py | 1,473 | 3.515625 | 4 | from abc import ABC
class Message:
def __init__(self, temp: int, hum: int):
self.temp = temp
self.hum = hum
def __str__(self):
return f"{self.temp} {self.hum}"
class IObserver(ABC):
def update(self, message: Message):
pass
class IPublisher(ABC):
def add_observer(se... |
d4ef0a70459caa67cac1ada094391340da6900c3 | deryacortuk/maths-equations | /dec.py | 316 | 3.703125 | 4 | def is_prime(x):
i = 2
while(x>i):
if(x%i==0):
return False
i +=1
return True
def generator():
i =2
while True:
if(is_prime(i)):
yield i
i +=1
for number in generator():
if(number>100):
break
print(number ) |
60cb5bfb90f850e2303d5563e4d688c10f495854 | basic-maths-exercises/negation-5 | /main.py | 527 | 3.609375 | 4 | import numpy as np
def thereExists( A ) :
v = 0
for a in A :
if a > 4 : v = 1
return v
def negationThereExists( A ) :
# Your code goes here
# This code allows you to test the functions you have written
print(thereExists([3,4,5,6,7,8,9]), "the proposition is true for this set")
print(negationThereE... |
54db70eb164699e963b624d2d527f4dd3a22ebb2 | saraswati87/pythonprogram | /python5.py | 230 | 3.84375 | 4 | str = str(input("enter number "))
list=str.split(",")
n = len(list)
list.sort()
if n % 2 == 0:
median1 = list[n//2]
median2 = list[n//2 - 1]
median = (median1 + median2)/2
else:
median = list[n//2]
print(median) |
5a6187d9f2d13ba5dd74f26b441704f106731faa | create92/CodingTestPractice | /greedy/greedy3-5.py | 1,194 | 3.625 | 4 | '''
<문제> 곱하기 혹은 더하기:문제 조건
입력조건 : 첫째 줄에 여러 개의 숫자로 구성된 하나의 문자열 S가 주어집니다.
(1 <= S의 길이 <= 20)
출력조건 : 첫째 줄에 만들어질 수 있는 가장 큰 수를 출력합니다.
'''
# 해결법
# 0이 들어온 경우, 곱하면 값이 0이 되기 때문에 무조건 더해줌
# 1이 들어온 경우, 곱하면 값이 그대로이기 때문에 더해줘서 증가시켜줌
# 시작은 항상 0으로
# 길이 1 이상 20 이상인 경우
input = str(input())
totalSum = 0
if input.len() < 1 || input.l... |
ec8ef1ca5c815f84165dc4742a275dbd04de04ad | coder6586/Names_generator | /names generator.py | 511 | 3.515625 | 4 | import string, random
def simple_names():
letter1=random.choice(string.ascii_uppercase)
letter2=random.choice(string.ascii_lowercase)
letter3=random.choice(string.ascii_lowercase)
letter4=random.choice(string.ascii_lowercase)
letter5=random.choice(string.ascii_lowercase)
letter6=random.... |
e07a76123cbbeb002263d9e2aafb61ed43b1b124 | alyizzet/Python_Programming_Exercises | /main (3).py | 1,531 | 3.609375 | 4 | class Person:
def __init__(self, fn, ln):
self.first_name = fn
self.last_name = ln
self.address = None #addresses stored by strings
def set_address(self, adr):
self.address = adr #strings
class BankAccount:
def __init__(self, sort_code, account_number):
self.sort_code ... |
807b7bc89aecea4311f7b7c52d31e553a9317306 | vostrikov-ov/Geekbrains_01 | /Lesson_2/theme1_2.py | 1,076 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Используя цикл, запрашивайте у пользователя число, пока оно не станет больше 0, но меньше 10.
После того, как пользователь введет корректное число, возведите его в степень 2 и выведите на экран.
Например, пользователь вводит число 123, вы сообщаете ему, что число невер... |
a848d3dea3572923b8ee40ef7a64ad6b4bafdf0d | jeremiahmarks/dangerzone | /scripts/python/anagrams/wordsy.py | 1,666 | 3.875 | 4 | wordss=open('words.txt')
matching_words={}
words_without_letters={}
alphabet=('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')
def no_e(word):
for letter in word:
if letter == 'e':
return
return word
def chec... |
92bed25d026b6c669946a2c8d8a7f7ee4558e0de | pengyuhou/git_test1 | /leetcode/654. 最大二叉树.py | 535 | 3.640625 | 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 constructMaximumBinaryTree(self, nums) -> TreeNode:
if not nums:
return
index = nums.index(max(nums))
left... |
4dabb7b168a1ef4236e8b54fa7a6add3cacc6534 | marie8bit/ChainsawRecordsSQLAlch | /ui.py | 1,841 | 4.21875 | 4 | #This program uses parameterized SQL statement to manage an SQLite3 database file
#to store chainsaw throwing records.
#The user is able to add, edit, insert, and delete records from the database
import records, choiceProcessor, dbManager
def main():
#initializes database or reads data from the database file
d... |
f5d7e069e2a079778727092fbeb4b2d9f26d7433 | ParadigmPlusPlus/Course-Material | /Lesson-3/BooleanAsCondition.py | 228 | 3.9375 | 4 | boolean1 = True and True
boolean2 = True and False
boolean3 = False and False
boolean4 = True or True
boolean5 = True or False
boolean6 = False or False
if boolean1: # change boolean1 to boolean2, 3, 4, 5, 6
print("Hello") |
d86613e525186d8334bf5dcfa82d3b631c911d8b | tcandzq/LeetCode | /UnionFindSet/SurroundedRegions.py | 2,650 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/8/31 11:25
# @Author : tc
# @File : SurroundedRegions.py
"""
题号 130 被围绕的区域
给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。
找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。
Input:
X X X X
X O O X
X X O X
X O X X
运行你的函数后,矩阵变为:
X X X X
X X X X
X X X X
X O X X
解释:
被围绕的区间不会存在于边界上,... |
7577025c179ee57c6608e6502d1e68fec02cb2cf | shektor/pyman-numerals | /roman_numeral.py | 1,596 | 3.625 | 4 | def convert(number):
numerals = {
1: 'I',
5: 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M',
}
units = [1000, 500, 100, 50, 10, 5, 1]
numeral = ''
while number > 0:
round_one_sig = number
if number > 9:
tens =... |
735dd148da99f579f79c69a93cdc1663c2044875 | TheGrateSalmon/Side-Projects | /Shift Cipher.py | 2,379 | 4.53125 | 5 | # This program allows a user to encode and decode messages through the use of a shift cipher.
# June 12th, 2018
def encrypt(key , message , alphabet):
# this function takes a "message" as a string and encrypts it by shifting the characters of the string forward by an integer key
# keep only a-z charac... |
db6f2d7a220119e10baf8221d67d221a13b5915a | Ham5terzilla/python | /2nd Lesson/2.py | 305 | 3.53125 | 4 | # Ввести с клавиатуры координаты двух точек (A и B) на
# плоскости (вещественные числы). Вычислить длину отрезка AB
Ax, Ay, Bx, By = map(float, input().split())
print(round(((Ax - Bx) ** 2 + (Ay - By) ** 2) ** 0.5, 2))
|
30f3239eb87bebf37503a94635d306a3969d8225 | ATUL786pandey/python_prac_codewithharry | /loop_prac02.py | 286 | 3.546875 | 4 | '''
write a program to greet all the person in the list l1 and which start with s
l1=["Harry","sohan","sachin","shailesh","sahil"]
'''
l1=["Harry","sohan","sachin","shailesh","sahil"]
for i in l1:
if i.startswith("s"):
print("good Evening have a nice day", i)
|
8a0428f6d56daa9170b448410aa423fa5a4def92 | ERICCYS/Coursera-Algorithm-Toolbox | /Week 3 Greedy/Maximum_Salary.py | 763 | 3.65625 | 4 | def input_info():
n = int(input())
number_strings = input().split()
lengths = []
for number_string in number_strings:
lengths.append(len(number_string))
max_length = max(lengths)
info = []
for number_string in number_strings:
info_piece = []
info_piece.append(number_string)
for i in range (max_length):... |
8a28b4b43825bd5a09d6308cf9e43bb5711229e6 | aryajar/Louplus | /game.py | 590 | 3.984375 | 4 | sticks = 21
print("There are 21 sticks. you can take 1-4 number of sticks at a time")
print("Whoever take the last sticks will lose")
while True:
sticks_taken = int(input("Take sticks(1-4):"))
if sticks_taken >4 or sticks <1:
print("Wrong choice")
continue
else:
print("You take {} ... |
364331d0699661d03cc4bc33daaf9f1c27878dbf | UMBC-CMSC-Hamilton/cmsc201-spring2021 | /variables.py | 7,780 | 4.65625 | 5 | # Let's do a little bit of review. (pound-sign, hash tag) start a single-line comment
# the Python interpreter basically ignores the comment lines.
# Multiline comments are done like this:
"""
This is a multi-line comment (basically)
we can use it for that purpose.
Actually: A multi-line string
Do I need... |
17dbf5b3017224bc8481494cc89ef3549c467eb4 | dlordtemplar/python-projects | /Functions/gcd.py | 621 | 3.984375 | 4 | '''
Implement a function gcd(x, y) that computes the greatest common divisor
of x and y. (1 Point)
>>> gcd(8, 12)
4
'''
# ... your code ...
def gcd(num1, num2):
if (num1 > num2):
greaterNum = num1
lesserNum = num2
else:
greaterNum = num2
lesserNum = num1
remainder = les... |
22b700b93fd884e5c7433f915236c0cb13355b62 | mason-landry/sudoku | /sudoku/board.py | 2,423 | 3.828125 | 4 | import numpy as np
class Board:
def __init__(self, size=9):
# Define size of sudoku grid (default is 9x9)
self.size = size
self.board = []
# Fill grid with zeros to start
for i in range(self.size):
self.board.append(np.zeros(self.size, dtype=int))
def updat... |
1f68b5fadcaee11b1ea9dc20a469564b5bfb4bde | rafaelperazzo/programacao-web | /moodledata/vpl_data/7/usersdata/99/5255/submittedfiles/esferas.py | 285 | 3.71875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
A=input('Digite o peso da esfera A:')
B=input('Digite o peso da esfera B:')
C=input('Digite o peso da esfera C:')
D=input('Digite o peso da esfera D:')
if (A==B+C+D) and (B+C==D) and (B==C):
print('S')
else:
print('N') |
9e68d3d693f232855a729256d7a1592b73354b07 | rileychapman/SoftDes | /random/hello.py | 147 | 3.703125 | 4 | def hello(x):
if x >= 0 and x <= 100:
print "hello"
elif x>100 and x < 500:
print "goodby"
elif x >= 600 and x<=1000:
print "ciao"
|
509d316dc4a3cbab41808d750dd468bff16f9ba7 | saipoojavr/saipoojacodekata | /a'sb's1change.py | 180 | 4.03125 | 4 | astr=input()
count=0
for i in range(0,len(astr)):
if(astr[i]=="a" or astr[i]=="b"):
count+=1
if(count==len(astr) or count==len(astr)-1):
print("yes")
else:
print("no") |
4f31726dd8618e6253dc0738768097daa9f089c2 | jeevy222/Hashing-1 | /groupanagrams_revision.py | 656 | 3.796875 | 4 | def groupanagrams(strs):
result =[]
dic = {}
for word in strs:
sortkey = ''.join(sorted(word))
if sortkey not in dic:
dic[sortkey]=[word]
else:
dic[sortkey].append(word)
for item in dic.values():
result.append(item)
return result
''' loop through the given array of words an... |
2b78c804cf4cf3ccbad8f27ef00712131ddeb105 | ssaurabhjawa/Auto-Crop-Image | /auto-crop.py | 5,785 | 3.703125 | 4 | from time import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
def auto_crop(file_name):
"""
Input argument: file_name (Image file name, e.g., 'rose.tif')
This function will auto crop the given image using image processing technique
Output: ROI
"""
... |
69aae714a43d91429bc8032871dbd8af61fad072 | FeiY74/python-memo | /useful.py | 128 | 3.953125 | 4 | # delete one character from a string
def missing_char(str, n):
if ( n >= 0 and n <= len(str)):
return str[:n] + str[n+1:]
|
f1936d6834c5b8f697f1821a72122b15cb58be9f | cqkh42/advent-of-code | /aoc_cqkh42/year_2020/day_10.py | 1,365 | 3.90625 | 4 | """
Solutions for day 10 of 2020's Advent of Code
"""
import functools
from typing import List, Tuple
def _sort_adapters(adapters) -> List[int]:
adapters = [0, *sorted(adapters), max(adapters) + 3]
return adapters
def _chain_adapters(adapters) -> Tuple[int]:
chain = [0] * (max(adapters) + 1)
for nu... |
1d14fb09d21362ed7089e3c4d0cd0698f4a33ecf | codeAligned/Leet-Code | /src/P-056-Merge-Intervals.py | 940 | 3.859375 | 4 | '''
P-056 - Merge Intervals
Given a collection of intervals, merge all overlapping intervals. For
example,Given[1,3],[2,6],[8,10],[15,18],return[1,6],[8,10],[15,18].
Tags: Array, Sort
'''
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
... |
3de5125be7aea69888ec9989e80ca40d839bfcba | BrundaBR/solutions | /watermelon.py | 69 | 3.671875 | 4 | n=int(input())
if (n)%2==0 and n!=2:
print("YES")
else:
print("NO") |
74c262b059ff80a9754f0fc3ab0a42cb568cd042 | stag152766/gb_ik_python | /Lesson6/les_6_task_1.py | 3,748 | 4.03125 | 4 | # 1. Подсчитать, сколько было выделено памяти под переменные в
# программах, разработанных на первых трех уроках.
# Выберите 3 любые ваши программы для подсчёта.
import sys
from Lesson6.task_4 import show_size
print(sys.version, sys.platform)
# 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (In... |
c93b30cbc764609d46114bfddc543283659c160d | CRomanIA/Python_Undemy | /Seccion_17_Pruebas_Automaticas/Sec17cap63.py | 714 | 3.734375 | 4 | #Doctest - Generar pruebas dentro de la documentacion
def sumar(numero1, numero2):
"""
Esto es la documentacion de este metodo
Recibe dos numeros como parametros y devuelve su suma
Se genera la prueba en los comentarios (No olvidar en el mayor que, darle un espacio)
(suma correcta)
>>> sumar(4,... |
5d05866f01932ca1225eb03685aa9466a67eb016 | PooPooPidoo/SimpleCalculate | /calc.py | 2,095 | 4.03125 | 4 | import math as m
import re
def op(x,y,operator):
if(checknum(x,y)):
if operator == '+': return x+y,
if operator == '-': return x-y,
if operator == '*': return x*y,
if operator == "/" and y != 0: return x/y,
if operator == "/" and y == 0: return ["division by zero",]... |
1ba17acff10e50ab6d05383c8e72f4682f4a9dbf | goalong/lc | /v1/231.power-of-two.132672777.ac.py | 699 | 3.65625 | 4 | #
# [231] Power of Two
#
# https://leetcode.com/problems/power-of-two/description/
#
# algorithms
# Easy (40.65%)
# Total Accepted: 164.3K
# Total Submissions: 404.2K
# Testcase Example: '1'
#
#
# Given an integer, write a function to determine if it is a power of two.
#
#
# Credits:Special thanks to @jianchao.l... |
4837192069da7a2efe08ad3acb3bf8c6ae5641ca | helenmfoster/MLProject | /wikipage.py | 2,286 | 3.828125 | 4 | import re
import wikipedia
from paragraph import Paragraph
class Wikipage:
"""Representation of wikipedia article"""
def __init__(self, subject):
"""
subject (string) : subject of desired wikipedia article
"""
self.subject = subject
self.page = wikipedia.page(self.subject)
self.sections =... |
77424d1c1779fbf14aa3a3953a97ab00f80624ce | AlceniContreras/Project-Euler | /Prob17.py | 1,290 | 3.625 | 4 | #-*- coding: utf-8 -*-
# Number letter counts
# --------------------
stop = 1000
num2words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \
11: 'Eleven', 12: 'Twelve', 13:'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Sevent... |
4badcb8924dda4d68dd28af4e5868f3145e829f0 | iamserda/cuny-ttp-algo-summer2021 | /victorLi/assignments/subsets/lc78/lc78.py | 348 | 4.125 | 4 | # Problem Statement #
# Given a set with distinct elements, find all of its distinct subsets.
def find_subsets(nums):
subsets = []
# TODO: Write your code here
return subsets
def main():
print("Here is the list of subsets: " + str(find_subsets([1, 3])))
print("Here is the list of subsets: " + str(find_su... |
9a99e019e0277ed5cbf5b89f497e623aa880ea03 | c212/spring2021-a310-labs | /march/lecture-march-08/BST-tests.py | 627 | 4.15625 | 4 | from BST import *
num = 6
a = BST(num)
print("Start from empty, insert ", num)
a.display()
num = 3
print("----Now insert ", num)
a.insert(BST(num))
a.display()
print("---And insert 2:")
a.insert(BST(2))
a.display()
numbers = [7, 9, 0, 8, 1, 4, 5]
print("---And insert (in order): ", numbers)
for num in numbers:
a.ins... |
4d1b637106732f7fda208190676d5a02dd740b67 | kirillherz/Python-learning | /Алгоритмы/Finding_loop_in_the list.py | 1,746 | 3.84375 | 4 | class Node:
def __init__(self, data, next):
self.data = data
self.next = next
class List:
def __init__(self):
self._head = None
self._tail = None
self._size = 0
self._nextHead = None
def add(self, data):
newNode = Node(data, None)
... |
02f1cb665fd3c8cd9427c4f069d2954a2bfc15d7 | yossibaruch/learn_python | /learn_python_the_hard_way/ex28.py | 1,037 | 4.1875 | 4 | if True and True:
print("1 True")
if False and True:
print("2 True")
if 1 == 1 and 2 == 1:
print("3 True")
if "test" == "test":
print("3 True")
if 1 == 1 or 2 != 1:
print("4 True")
if True and 1 == 1:
print("5 True")
if False and 0 != 0:
print("6 True")
if True or 1 == 1:
... |
9ed7f42bd65b9d70d7a44e0620fa25f8906c991c | RyoTakei/Spark | /Day1/lists.py | 552 | 4.25 | 4 | listOne = ["juice", "Tomatos", "Potatos", "Bananas"]
firstItem = listOne[0]
print("The first item is", firstItem)
listOne[0] = "Green Juice"
print("The First item is now", listOne[0])
# print 1 up to 3 but NOT including 3
print(listOne[1:3])
listOne.append("Onions")
print(listOne)
listOne.insert(1, "Pickle")
prin... |
79821243a964cdda26ecf8c585cd86c737f34677 | alen6697/leetcode-practice | /FlowerPlantingWithNoAdjacent.py | 872 | 3.578125 | 4 | class Solution(object):
def gardenNoAdj(self, n, paths):
"""
:type n: int
:type paths: List[List[int]]
:rtype: List[int]
"""
graph = defaultdict(set)
for u, v in paths:
graph[u].add(v)
graph[v].add(u)
res= [0] * (n ... |
f9c6d45b826238d664b58656f918fd42691f12bf | MatthewC221/Algorithms | /flatten_tree.py | 1,072 | 3.9375 | 4 | # Leetcode: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
# This is pretty difficult imo. You want to keep all the right subtrees in the stack, keep
# moving through left subtrees.
# One way to think about it is, The left children come first. Then the right.
# Definition for a binary ... |
8dc97f5a3c5be932fce0f81510bc9f10a4b66c36 | shaleenb/music-analysis | /src/data/scrape_billboard.py | 3,485 | 3.671875 | 4 | """Scrape Billboard Charts
This script scrapes Wikipedia to get a dataframe of the Billboard year-end Hot 100 songs.
Functions:
prepare_driver() -> selenium.webdriver.Chrome
scrape_for_year(driver, year) -> pandas.DataFrame
scrape_for_range(driver, start_year, end_year) -> pandas.DataFrame
"""
from tqdm ... |
cc73c3e7a3847d685cd4fc3c673ffb65eca769c3 | Python-aryan/Hacktoberfest2020 | /Python/CeaserCipher.py | 990 | 3.515625 | 4 | import os
class CaesarCipher:
text = ""
key = []
def read_text(self, filename):
file = open(filename, 'r')
content = file.read()
self.text = content
def read_key(self, filename):
file = open(filename, 'r')
content = file.read()
self.key = c... |
d722d346c7c041d1bb286a8306e7479a25cc62cd | ravi4all/PythonJune_Morning | /Advance_Python/TimeComplexity.py | 154 | 3.5 | 4 | import time
start = time.time()
a = []
for i in range(0,100000000):
a.append(i)
##print(a)
end = time.time()
print("Time", end-start)
|
6c62114cff4ca7ce96439d156b31d9574c26f9d6 | Casey0Kane/data-structures | /src/quick_sort.py | 1,169 | 4.0625 | 4 | """Merge sort data structure implementation."""
def quick_sort(numbers):
"""Recursively split list and returns quickd list."""
if len(numbers) <= 1:
return numbers
left, right = [], []
for num in numbers[1:]:
if num < numbers[0]:
left.append(num)
else:
r... |
ae5ac014409e42093ef55ddb0fc0c8c49d91daa6 | mike6321/dataStructure_algorithm | /Homework05/Problem02.py | 547 | 3.546875 | 4 | class MaxHeap:
def __init__(self):
self.data = [None]
def insert(self, item):
#마지막에 노드 추가
self.data.append(item)
# 마지막 인덱스 기억
i = len(self.data) -1
# 루트까지 지속해서 만복
while i >1 :
if self.data[i] > self.data[i//2]: # 부모 노드의 번호 : m//2
... |
df22b839f420d96fcb6460ef65fd67320514e932 | sudhamshu4testing/AutomateTheBoringStuffUsingPython | /ExerciseFour.py | 389 | 4.21875 | 4 | # Ending a program early with sys.exit()
"""However you can cause the program to terminate, or exit, by calling the sys.exit() function. Since this function is in the sys module,
you have to import sys before your program can use it """
import sys
while True:
print ('Type exit to exit. ')
response = input()
if re... |
62d73a184557931cd2ebf5eb1186659bbf94b206 | randian666/MPython3 | /demo/collections.py | 2,527 | 4.0625 | 4 | #!/usr/bin/env python3
from collections import namedtuple,deque,defaultdict,OrderedDict,Counter
'''
collections是Python内建的一个集合模块,提供了许多有用的集合类。
1、namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
2、使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。
deque是为了高效实现插入和删除操作的双向列表,适合用于... |
275c32a7df30977aee876d5f248da8bfa6afa7c7 | dhruvarora93/Algorithm-Questions | /Stacks and Queues/Sliding Window Maximum.py | 478 | 3.75 | 4 | from collections import deque
def sliding_window_max(nums,k):
output = []
queue = deque()
for end in range(len(nums)):
while queue and nums[end] > queue[-1]:
queue.pop()
queue.append(nums[end])
start = end - k + 1
if start < 0:
continue
... |
70ec0ca1b09b4c98b555cb348d5b5837ae0d9760 | radomirbrkovic/algorithms | /sort/exercises/02_sort-an-array-of-0s-1s-and-2s.py | 639 | 4.03125 | 4 | # Sort an array of 0s, 1s and 2s https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/
def sort012(arr):
lo = 0
hi = len(arr) - 1
mid = 0
while mid <= hi:
if arr[mid] == 0:
arr[lo], arr[mid] = arr[mid], arr[lo]
lo += 1
mid += 1
elif arr[mid] =... |
7d40c2b681365f8bd374f21aafee543b7e852844 | tomaszbobrucki/numeric_matrix | /Problems/Incomplete implementation/task.py | 216 | 3.75 | 4 | def startswith_capital_counter(names):
counter = 0
for name in names:
if name[0].isupper():
counter += 1
return counter
# print(startswith_capital_counter(["Alice", "bob", "John"]))
|
91074d66b59d3da8df309b4a60b86f5d167b54bd | vridecoder/Python_Projects | /indiceslist/main.py | 152 | 3.5 | 4 | from indices import Indices
list1=['I','am','Vrinda','Singh']
list2=[0,2]
indices=Indices()
indices.index(list1,list2)
print(indices.index(list1,list2)) |
1996e97eb5f766b56303a8b090e2bd98dcfb54e5 | DanielQFK/Python-Exercise | /Python-Exercise-05.py | 867 | 4.0625 | 4 | # list
# some exercises about List
Name = ["alex" , "TIM" , "Christian" , "ryan" , "joHN" ]
print(Name)
# The output would be = ['alex', 'TIM', 'Christian', 'ryan', 'joHN']
print(Name[1].lower())
# The output would be = tim
print(Name[0].title())
# The output would be = Alex
print(Name[-1].lower())
# The output wou... |
b4760b848bbd96c4d0ac7a4dcdbca62e5c210b04 | aadityasingh/AI | /Graph_L1/unidirectional_search.py | 1,596 | 3.609375 | 4 | from time import time
import pickle
# this makes an array of all the words in the file
array_of_text_from_file = open('words.txt').read().split()
f = open('saved_graph.p', 'rb')
try:
n_hash = pickle.load(f)
finally:
f.close()
# Finds the shortest path between two words in the graph
root = input('Enter starting ... |
9e4a6be6568cc21e02be5465d673438219047364 | iblezya/Python | /Semana 2/Cuarentena/cond7.py | 622 | 3.8125 | 4 | while (True):
try:
promedio = int(input('Ingrese su promedio: '))
if 20 >= promedio >= 16:
print('Usted tiene un promedio Bueno.')
elif 16 > promedio >= 10:
print('Usted tiene un promedio Regular.')
elif 10 > promedio >=6:
print('Us... |
4051402ed070add66e1b318cd81d57271a5a3862 | omnivaliant/High-School-Coding-Projects | /ICS3U1/Assignment #9 1D Lists/IntGroup.py | 17,397 | 4.28125 | 4 | #Author: Mohit Patel
#Date: January 6, 2015
#Purpose: To create a program which makes use of the list.
#------------------------------------------------------------#
import random
from tkinter import*
root = Tk()
root.title("IntGroup")
root.config(width=1000,height=500,bg="sky blue")
Size1 = StringVar()
Size1.set(0)
Si... |
93e7ede69748b5bc35fc1805d9007f62ff5ff5bd | anniephilip23/Guvi | /Python/numberguessinggame.py | 310 | 3.890625 | 4 | import random
a = random.randrange(10)
i = 5
while (i!=0):
n = int(input("enter any number between 0 to 10: "))
if a==n:
print ("u have entered correct number")
break
else:
print ("enter any other numb. Your life left is ",i-1)
i=i-1
print ("gameover the number is",a)
|
357e5590312a5fad8a2dad3e0ff543442fbed97d | quieterbwhite/quieter_python | /python/01_getattr.py | 3,130 | 4.125 | 4 | Python中的getattr()函数详解
ref: http://www.cnblogs.com/pylemon/archive/2011/06/09/2076862.html
函数本身的doc
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an... |
cc6670398e9dc00ea1ed938f1924d4c39f87aa42 | puruckertom/esa_python | /scripts/commands08_classes.py | 1,410 | 4.0625 | 4 | #create the Rabbit class, starts with 10 hit points
class Rabbit(object):
def __init__(self, name):
self.name = name
self.hit_points = 10
def hop(self):
self.hit_points = self.hit_points - 1
print "%s hops one node, now has %i hit points." % (self.name, self.hit_points)
def eat_carro... |
3ad24b2429a98c184344206826cc7362a541fdb6 | Miguel-de-Castro/MultilayerPerceptron | /MLP.py | 4,397 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 12 14:58:10 2021
@author: Victor Nobre
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from activation_function import sigmoid
from activation_function import sigmoidDerivada
#REDE NEURAL PARA REALIZAR O TREINAMENTO.
#ENCONTRANDO ARQUIVOS DATA... |
682d6cac25f7ff72ca40d7281d38b5cb17355a34 | GITlibin1025/pyLearn | /leiandduixiang.py | 695 | 4.03125 | 4 | '''
类和对象
按照以下提示尝试定义一个矩形类并生成类实例对象。
属性:长和宽版权属于
方法:设置长和宽 -> setRect(self),获得长和宽 -> getRect(self),获得面积 -> getArea(self)
提示:方法中对属性的引用形式需加上 self,如 self.width'xdu
'''
class Rectangle():
def setRect():
print('请输入矩形的长和宽')
global a
global b
a = input('长:')
b = input('宽:')
def getRect():
print("这个矩形的长是 %s" % a )
p... |
c41cf49d568bee4f2e2caaf24483b0e032b247eb | pjz987/2019-10-28-fullstack-night | /Assignments/andrew/python/lab11_v1.py | 146 | 3.640625 | 4 | operation = input("What operation would you like to do?")
num_1 = int(input("Enter first number."))
num_2 = int(input("Enter second number."))
|
888f4cdff7b44b1bc7608228979f91bd05fd1747 | Tinakhandelwal/Sample-Python-Programs | /plotting.py | 399 | 3.6875 | 4 | import matplotlib.pyplot as plt
import numpy as np
# Create sample data for plotting. Eg: sine wave
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
# Create figure and axes for plotting
fig, ax = plt.subplots()
ax.plot(t, s)
# Include axis info and title
ax.set(xlabel='time (s)', ylabel='Sine value', tit... |
a629186411b817b192a94853bfc1f9d7c304b3ee | junbyungchan/python | /lec06_class/inheritance01.py | 4,408 | 4.03125 | 4 | """
상속(inheritance):
부모 클래스로부터 데이터(field)와 기능(method)를 물려받아서
자식 클래스에서 사용할 수 있도록 하는 개념
- parent(부모), super(상위), base(기본) class
- child(자식), sub(하위), derived(유도) class
"""
from math import pi
# 모든 class의 조상은 object이다.
# 그래서 생략이 가능하다.
# class Shape(object): --> 원래 이 표현인데 생략을 한다.
class Shape:
def __init__(self,x=0,y=0)... |
bc59f11551bc8dec1f75e5fb8e6a45dd27b0cd2f | 2ptO/code-garage | /icake/test_q2.py | 841 | 4 | 4 | import unittest
import q2
class TestQ2(unittest.TestCase):
def test_positive_nums(self):
inputs = [7, 5, 4, 2, 6]
expectedResult = 210
actualResult = q2.get_highest_product_of_three(inputs)
self.assertEqual(expectedResult, actualResult, "Invalid highest product of 3")
def t... |
e5414ab736dfd9cf8498101d0f42a4257daf21ae | eclipse-ib/Software-University-Professional-Advanced-Module | /September 2020/02-Tuples-and-Sets/01-Count-Same-Values.py | 242 | 3.671875 | 4 | string = tuple(float(_) for _ in input().split())
dict_nums = {}
for i in string:
if i not in dict_nums:
dict_nums[i] = 1
else:
dict_nums[i] += 1
[print(f"{key} - {value} times") for key, value in dict_nums.items()] |
1b29def20e469bf5eb9563bc7667cb3a896aaf1a | s-rigaud/Restaurant-Management-System | /app/tooltip.py | 1,632 | 3.546875 | 4 | from tkinter import ttk, Toplevel, Button
__all__ = ["ToolTip"]
class ToolTipSkeletton:
def __init__(self, widget, text):
self.widget = widget
self.tipwindow = None
self.x = 0
self.y = 0
self.text = text
style = ttk.Style()
style.configure(
"too... |
e7bf9d7f7d696b6681587607d95a36d431ef937a | daniel-reich/turbo-robot | /Ygt4LGupxDAqXNrhS_8.py | 1,284 | 3.828125 | 4 | """
Given a grid of numbers, return a grid of the **Spotlight Sum** of each
number. The spotlight sum can be defined as the total of all numbers
immediately surrounding the number on the grid, including the number in the
total.
### Examples
spotlight_map([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
... |
8a7b3f44c1ba00c575ebd8bc0f8d715e0e4c51d1 | SamiaAitAyadGoncalves/codewars-1 | /Python/8kyu/I love you, a little , a lot, passionately.py | 718 | 3.75 | 4 | # https://www.codewars.com/kata/57f24e6a18e9fad8eb000296
#
# Who remembers back to their time in the schoolyard, when girls would take a
# flower and tear its petals, saying each of the following phrases each time
# a petal was torn:
#
# I love you
# a little
# a lot
# passionately
# madly
# not... |
4a932ddcb102926ee6944f53d8f17392148d17f9 | ljc520313/PythonDemo | /com/example/hanshu4.py | 559 | 3.796875 | 4 | # str1 = '上海自来水来自海上'
# str1 = '如来佛祖'
str1 = input('输入一个句子判断是否是回文:')
str_list = list(str1)
str_list1 = str_list
# str_list1 = list(str1)
str_list.reverse()
# reverse()只作用于列表不作用于字符串
print(str_list)
print(str_list1)
if str_list1 == str_list:
print('字符串%s是回文联'%str1)
else:
print('字符串%s不是回文联'%str1)
# 方法2
# k=0
# ... |
46e83d4333489db5c4d3ded70ef4a95b56ccf1e7 | takayuki211/atcoder | /abc049/c/main.py | 601 | 3.9375 | 4 | #!/usr/bin/env python3
import re
s = input()
while True:
# re.subを使うと処理時間超過した。
# s = re.sub('dream$|dreamer$|erase$|eraser$','',s)
# リストのスライスを利用するほうが高速
l = len(s)
if s.rfind('dream') == l-5:
s = s[:-5]
elif s.rfind('dreamer') == l-7:
s = s[:-7]
elif s.rfind('erase') == l-... |
d2140b64b01b0412aef4dcbb037ef3747018bce4 | naveen6797/Git_tutorials | /even add number.py | 141 | 3.859375 | 4 | Number=5.5445654545
if(Number%2==0):
print('even number')
elif(Number%2==1):
print('odd number')
else:
print('others')
|
9a56df4140e4559196a259d7974ea64c61872592 | abushonn/py | /technion2020/assignment1/ex1_1_purchase.py | 1,267 | 3.84375 | 4 |
'''
Input==================
print('A:')
a_price= float(input())
a_quant= int(input())
print('B:')
b_price= float(input())
b_quant= int(input())
print('C:')
c_price= float(input())
c_quant= int(input())
print('D:')
d_price= float(input())
d_quant= int(input())
======================
'''
(a_price, a_quant) = (11.1... |
e3bb7ac63f92bd6ea411cf0bef933e4b43044df7 | blavis21/Python-Book-1-Orientation | /ch4-Dictionary/dictionary.py | 2,097 | 4.5625 | 5 | # PRACTICE: Dictionary of Words
"""
Create a dictionary with key value pairs to
represent words (key) and its definition (value)
"""
word_definitions = dict()
"""
Add several more words and their definitions
Example: word_definitions["Awesome"] = "The feeling of students when they are learning Python"
"""
word_def... |
0455aeef947db1484039034ebc4f1acd29e76c1c | ambivert143/PythonProgram | /enume.py | 215 | 3.703125 | 4 | class Enum:
def __init__(self,list):
self.list = list
def enume(self):
for index, val in enumerate(self.list,start=1):
print(index,val)
e1 = Enum([5,15,45,4,53])
e1.enume() |
d38d221e4c91ddd862cf15086c6ac9cedbe94281 | zarkle/code_challenges | /leetcode/buy_sell_stock_iii.py | 1,024 | 3.515625 | 4 | # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/
# passes 189/200 test cases
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
profit = []
low... |
bf2d85594dbc51b9b27063c50bc501eaa12d16d8 | agustashd/Learning-Python | /matriz_datos_NxM.py | 2,274 | 3.875 | 4 | #!/usr/bin/env python3
"""Ingresar N lotes de M datos.
Calcule el promedio de cada lote e infórmelo en pantalla. Además muestre el
dato máximo y el promedio mínimo y a qué número de lote pertenece cada uno.
"""
def carga_matriz(cant_lotes, cant_datos):
"Función que sirve para cargar la matriz de NxM."
matr... |
7a6b666cf6d3cad36fb8e3f1e397d1bae8fd4aa7 | erichuang2015/python-examples | /算法/04统计单词出现次数.py | 715 | 3.96875 | 4 | #!/usr/bin/env python3
# coding: utf-8
"""统计字符串单词出现次数,不区分大小写。
"""
import re
from collections import Counter
def main():
# 去除多余标点
pattern = re.compile(r'[,.!?]')
# 第一种方式,自定义算法
s = 'I love python, python is simple and powerful!'
d = {}
for letter in pattern.sub(' ', s.lower()).split():
... |
9a63728319bc7a007e3edcc2acf916c0e32b988a | Arunken/PythonScripts | /2_Python Advanced/8_Pandas/10_Sorting.py | 1,643 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 14:30:07 2018
@author: SilverDoe
"""
'''
There are two kinds of sorting available in Pandas :
1. By Label
2. By Actual Value
'''
'''================== Sorting By Label ========================================'''
import pandas as pd
import numpy as n... |
f298e7715358c8343efbb37ab916f919ddd8f8d7 | nish0910/face-detect | /main.py | 589 | 3.96875 | 4 | #code to detect face in an image
import cv2
#contain face features
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
#for reading the image
img = cv2.imread("IMG_20201211_175249.jpg")
#convertng the image into gray scale image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#search the co... |
5f689e1b405405e44fbf8835c968b96972a81bbf | inyong37/Study | /V. Algorithm/i. Book/모두의 알고리즘 with 파이썬/Chapter 16.py | 857 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# Modified Author: Inyong Hwang (inyong1020@gmail.com)
# Date: *-*-*-*
# 모두의 알고리즘 with 파이썬
# Chapter 16. 미로 찾기 알고리즘
def solve_maze(g, start, end):
qu = []
done = set()
qu.append(start)
done.add(start)
while qu:
p = qu.pop(0)
v = p[-1]
if v == end:
... |
5cccf972d231ea79e6945106606164e7eb8199c1 | Satoshi-Daikuhara/Python | /csvopen.py | 3,288 | 3.828125 | 4 | import csv
import pandas as pd
csv_file = open("./Book1.csv", "r", encoding="ms932", errors="", newline="" )
#リスト形式
l = csv.reader(csv_file, delimiter=",", doublequote=True, lineterminator="\r\n", quotechar='"', skipinitialspace=True)
#辞書形式
d = csv.DictReader(csv_file, delimiter=",", doublequote=True, lineterminato... |
5679bb60958ce0460eea76e090ab411a5ca59ff9 | hariedo/wafer | /py/lib/timelines.py | 5,219 | 3.984375 | 4 | # timelines - a data model for events to be compared and rendered
'''
A data model for events to be compared and rendered.
SYNOPSIS
>>> import timelines
>>> line = timelines.Timeline('Japanese Eras')
>>> line.add( timelines.Mark(1600, 'battle of sekigahara' )
>>> line.add( 'tokugawa shogunate',
... |
6ebb521d57eff7ea4961beff987cc142d4a02700 | emotrix/Emotrix | /emotrix/helpers.py | 934 | 3.890625 | 4 | # -*- coding: utf-8 -*-
import math
import random
def average(data):
return sum(data) * 1.0 / len(data)
def variance(data):
avg = average(data)
var = map(lambda x: (x - avg)**2, data)
return average(var)
def standard_deviation(data):
return math.sqrt(variance(data))
def get_variance_range(... |
5443329a7d0392e3b238b2cd370f546411e3d5ec | Arto1597/bedu-data02-team | /Pozole.py | 2,302 | 4.0625 | 4 | """ numeros = [13,23,45,6,67,123]
def numero_par (numero):
return numero*3
#Definir la función
numero_par = list(map(numero_par, numeros))
print(numero_par)
lista=[45,50,91,80,54]
def multiplo_de_5(numeros):
if numeros % 5 ==0:
return print("es normal")
else:
return print("sigue")
mult... |
737b1e679bf4ab0d395cb4184e30423f0389da23 | pabin/university_recommendation | /recommender/graph_plot.py | 1,488 | 3.5 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
def graph_plot():
csv_filepathname = "/home/raj/PycharmProjects/university_recommendation/" \
"database/clean70k.csv"
names = ['University', 'Major', 'Degree', 'Seaso... |
fcd3c07b1de76e1a7b7dcdd73d8e4c7997613428 | sabrinako/advent-2020 | /day-4/solution.py | 3,923 | 3.5 | 4 | """
--- Day 4: Passport Processing ---
First puzzle answer: 204
Second puzzle answer: 179
"""
import re
def validate_regex_fields(regex, value):
return re.search(regex, value)
def validate_in_range(range, value):
"""
range is a tuple
"""
return range[0] <= int(value) <= range[1]
def validate_year_field(name... |
65653fff3310ed48e4ab465e503ca3a300871b09 | candlelogbi/100DProjects | /Day46_47.py | 482 | 3.65625 | 4 | class Library:
def __init__(self,book,shelf):
self.book=book
self.shelf=shelf
class science_section(Library):
def __init__(self,book,shelf,name):
super().__init__(book,shelf)
self.name=name
def printInfo(self):
print("book:", self.book,"self:",self.shelf,"name"... |
5e8be0abc82879f927f1b2c9b2ee70e8b56bf558 | pfs-0512/python_practice | /Dotinstall/myapp.py | 226 | 3.96875 | 4 | # print([i for i in range(10)])
# print([i * 3 for i in range(10) if i % 2 == 0])
# print((i * 3 for i in range(10) if i % 2 == 0))
print(i * 3 for i in range(10) if i % 2 == 0)
print({i * 3 for i in range(10) if i % 2 == 0})
|
c8c3e5e7a344f554b32517f7d1c56129f032de2c | sjpark-dev/python-practice | /problems/programmers/level_1_to_2/p8.py | 495 | 3.796875 | 4 | # 최대공약수와 최소공배수
import math
def solution(n, m):
# x = gcd(n,m)
x = math.gcd(n, m)
y = n * m // x
answer = [x, y]
return answer
# def gcd(n, m):
# n_set = set()
# m_set = set()
# for i in range(1, n+1):
# if n % i == 0:
# n_set.add(i)
# for i in range(1, m+1):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.