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 |
|---|---|---|---|---|---|---|
1dc8a0478fc7384104d7bdcab1085f7e323ee0d1 | chaudharydeepak/aoc2020 | /day-10/day10.py | 952 | 3.5625 | 4 | file1 = open('input.txt', 'r')
Lines = file1.readlines()
jolts = [int(i) for i in Lines]
# part 1
jolts.append(0)
# jolts.append(max(jolts)+3)
# jolts.sort()
# diffs = {0:0, 1:0, 2:0, 3:0}
# for i in range(0, len(jolts) - 1):
# diffs[jolts[i + 1] - jolts[i]] += 1
# print(diffs[1] * diffs[3])
# part 2
def co... |
0c5429d37b0c76d3498d03d3bc8f0dcb68d068ac | JuanHonores/Grupo13_Anderson_Juan | /codigo58.py | 226 | 4.0625 | 4 | varA="Hola"
varB="mundo"
if type(varA)!= int:
if type(varB)!=int:
print ("string involucrado")
elif type(varB)==int:
if varA>varB:
print("mas grande")
elif varA<varB:
print("mas pequeño")
else:
print("igual")
|
39fd6c069ead2bfb09a5950e1a70e819df7668f0 | singhru27/Regularized-Logistic-Regression | /models.py | 11,249 | 3.890625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def sigmoid_function(x):
return 1.0 / (1.0 + np.exp(-x))
class RegularizedLogisticRegression(object):
'''
Implement regularized logistic regression for binary classification.
The weight vector w should be learned by minimizing the regularized risk
... |
2e5bb889400480a5b4f1f1385f492cbcb4edecc2 | MeironGeek/geekbrains | /lesson01/example04.py | 413 | 3.9375 | 4 | number = int(input("Введите целое положительное число "))
check = -1
while number > 10:
d = number % 10
number //= 10
if d > check:
check = d
if(check == -1) :
print('Самое больше число =', number)
elif (check < number):
print('Самое больше число =', number)
else:
print('Самое больше ч... |
b9252de66be26ce64c86a0db5a3948aa43f86b9f | KenMwanza/bc-9-oop | /note-taking-app/notes_app.py | 919 | 3.59375 | 4 | class NotesApplication(object):
def __init__(self, author):
self.author = author
self.notes = []
def create(self, note_content):
self.notes.append(note_content)
def list(self):
print("Note ID: " + self.author + " - " + str(self.notes))
def get(sel... |
b61cf404bf9ebd0aefb8b9b04d18944df3f24448 | Iamsdt/PythonStart | /src/practice/oop/SuperCar.py | 469 | 3.578125 | 4 | import src.practice.oop.Car as Car
class SuperCar(Car.Car):
_rate = .8
def __init__(self, name, year, cc, fuel, color):
super(SuperCar, self).__init__(name, year, cc, fuel)
self.color = color
def run(self, time):
temp = time * self._rate
self._fuel -= temp
def detai... |
2c65d024275fb2ee4fb7e3dd40d7e25d60762153 | protocista/LPTHW | /ex2.py | 466 | 3.640625 | 4 | ''' How to make a multiline comment A comment, this is so you can read your program later.
Anything after the # is ignored by python. Not technicaly a comment.
this is just a weird quirk, the program still reads this.
'''
import time
print("I could have code like this.") # and the comment after is ignored
# You can al... |
1e02ed7a23f3de388f917ae4b0de3eaeb849318f | qmnguyenw/python_py4e | /geeksforgeeks/algorithm/medium_algo/10_17.py | 15,910 | 3.578125 | 4 | Count of Numbers in Range where first digit is equal to last digit of the
number
Given a range represented by two positive integers L and R. Find the count of
numbers in the range where the first digit is equal to the last digit of the
number.
**Examples:**
**Input :** L = 2, R = 60
... |
80a5fcb589843b030af9edbedeb2618f41a95b6b | rodmur/hackerrank | /other/blah.py | 455 | 3.6875 | 4 | #!/usr/bin/python3
import operator
class Student(object):
def __init__(self, id, name, marks):
self.id = id
self.name = name
self.marks = marks
def __str__(self):
return '%s has marks %s' %(self.name, self.marks)
students = [ Student(0, 'Foo', 30), Student(1, 'Bar', 95),... |
b7e81232a715e8cd44e06296f094bdf05bf84e83 | beOk91/code_up | /code_up1671.py | 197 | 3.5 | 4 | a,b=map(int,input().strip().split())
if a==0 and b==1:
print("win")
elif a==1 and b==2:
print("win")
elif a==2 and b==0:
print("win")
elif a==b:
print("tie")
else:
print("lose") |
0926972839edb59d0e19dae8276d485096320cf2 | markyasu/short_example_package | /asia.py | 291 | 3.8125 | 4 | class Asia:
def __init__(self):
# create asian nation members
self.members = ['Azerbaijan', 'Brunei', 'China']
def printMembers(self):
print('Printing members of the Asia class')
for member in self.members:
print('\t%s ' % member) |
3c2a764da88ee522946b5c4403f8a368889f95bd | zclima/DBPerfumes-ZaqueuCardoso | /data.py | 910 | 3.65625 | 4 | import sqlite3
path =
banco = sqlite3.connect(path + )
cursor = banco.cursor()
#Marcas
cursor.execute("INSERT INTO Marcas VALUES(1, 'Natura')")
cursor.execute("INSERT INTO Marcas VALUES(2, 'Oboticário')")
#Fixaxoes
cursor.execute("INSERT INTO Fixaxoes VALUES (1, 'Delicado')")
cursor.execute("INSERT INTO Fixaxoes VA... |
6ffd3aca196d9a6f4ec19e6400f766a03024919c | RiveTroy/Learning_Python | /Head First Python/Chapter 1/Chapter1.1.py | 899 | 4.15625 | 4 | # print() function is a built-in functions that shows your work in the screen.
print("My name is Enes Kemal Ergin")
''' Unlike other C based languages, which use { and } to delimit blocks, python
uses indentation instead. '''
# By the way it indentation is very important try to get used to it.
# Python IDLE allo... |
e364d7e1dd38b186628b4ea20a5f2a0e9b60da2e | glebb/nhlstatsscarper | /src/eashltoolkit/html/common.py | 1,228 | 3.53125 | 4 | """Common functions for html parsing"""
# -*- coding: utf-8 -*-
import urllib2
import eashltoolkit.settings
def get_content(url):
"""Get html content of given url.
untested copy/paste code"""
content = None
if url:
try:
headers = {'User-Agent': 'Mozilla/5.0'}
req = urll... |
2d5e29633ea88a6f9abf962a768fab9a1e54b2aa | Uthaeus/practice_python | /palindrome.py | 254 | 4.3125 | 4 |
print("Let's Check if a word is a palindrome.")
word = (input("Enter a word: "))
def reverse(s):
str = ""
for i in s:
str = i + str
return str
str1 = word.lower()
str2 = reverse(str1)
if str1 == str2:
print('Yes')
else:
print('No')
|
c66a30924dfe25e9394eb0ee04fed6e3a18028ad | leviandrade/Exerc-cios-Python | /par_ou_impar.py | 158 | 3.625 | 4 | def par(n):
if n%2==0:
return True
else:
return False
n=int(input('n'))
if par(n):
print('é par')
else:
print('não é par')
|
56d44cf0a68c7ecc8321c848fc5b5b2b8d6effe1 | pedrottoni/Studies-Python | /Cursoemvideo/Mundo1/exercise014.py | 284 | 4.34375 | 4 | # Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
celsius = float(input("Digite a temperatura em Celsius:"))
fahrenheit = (celsius * 9 / 5) + 32
print(f"A temperatura de {celsius}ºC corresponde a {fahrenheit:.1f}ºF.")
|
4d090b2c71a26f46809576df6143d810a24a4c95 | Apex-yuan/mydocs | /docs/Python/test_code/class.py | 1,554 | 4.21875 | 4 | #!/usr/bin/env python3
# class MyClass:
# '''
# 自定义类
# '''
# i = 12345
# def f(self):
# return 'hello world!'
# x = MyClass()
# print("i", x.i)
# print("f", x.f(),x.i)
### 运算符重载
# class Vector:
# def __init__(self, a, b):
# self.a = a
# self.b = b
# def __str__(s... |
fe9bb37e8fb95bb1bb64abf5c9c586b887927b77 | kernowal/projecteuler | /2.py | 737 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: alexogilvie
Project Euler Problem 2: Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By consideri... |
9d764a6ff4ba0380af7669ea15db6e0d2cead0aa | hrithik0/newbieProjects | /emoji.py | 180 | 3.625 | 4 | emojis = {
":)" : "😊",
":(" : "😔"
}
message = input("> ").split()
output =""
for words in message:
output += emojis.get(words,words) + " "
print(output) |
60f9be7efe06c16959fd056c8f532633bab1a725 | PeterZhangxing/others | /test.py | 29,039 | 4.15625 | 4 | #!/usr/bin/python3.5
# products_list = [
# ('telephone',2000),
# ('computer',12000),
# ('bicycle',20000),
# ('television',4500),
# ('kindle',1450),
# ]
# shopping_list = []
# salary = input("please input how much money you obtain: ")
# if salary.isdigit():
# salary = int(salary)
# while Tru... |
69df0c153561cf293cdc296eb0ca3d9c3d8cf552 | jing1988a/python_fb | /lintcode_lyft/IntersectionofTwoArraysII548.py | 1,555 | 4.09375 | 4 | # Given two arrays, write a function to compute their intersection.
#
# Example
# Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
#
# Challenge
# What if the given array is already sorted? How would you optimize your algorithm?
# What if nums1's size is small compared to num2's size? Which algorithm is bette... |
4b6a934a1a24f0ca1d2b8316b3b4a5e2f3f2e35b | LewisT543/Notes | /Learning_Tkinter/13Widget-anchor-cursor.py | 1,520 | 4.71875 | 5 | #### WIDGET ANCHOR + CURSOR ####
# ANCHOR
# The anchor is an imaginary (invisible) point inside the widget to which the text (if any) is anchored.
# We can change where the text is anchored by using:
# button['anchor'] = <compass direction>
# Compass directions : n, s, e,... |
5971590ef5c68729c4d3d7bd8c00a66a9a123272 | Nilsonsantos-s/Python-Studies | /Mundo 1 by Curso em Video/Exercicios Python 3/ex033.py | 524 | 3.90625 | 4 | # leia 3 numeros e verifique o maior e o menor
n1 = float(input('Digite um numero:'))
n2 = float(input('Digite um numero:'))
n3 = float(input('Digite um numero:'))
p1, p2, p3 = 0, 0, 0
if n1 > (n3 and n2):
p1 = n1
if n2 < n3:
p2 = n2
else:
p2 = n3
elif n2 > (n1 and n3):
p1 = n2
if n... |
f192c195a612a86fd663f743a3a2e283ad868e46 | OleksiiBondarr/evo2018_2 | /start.py | 3,693 | 3.59375 | 4 | import random
class ServerSimulation:
"""
type_id - int тип заполнения серверов (1 - рандомное, 0 - зеркальное)
server_amount - int кол-во серверов
data_amount - int кол-во кусков данных
data_chunks - словарь: key - номер сервера, value - список кусков данных
"""
data_chunks = {... |
27c0040d6903a4c72db24660b26e4c8478086832 | TBisig/Python | /ScoresandGrades.py | 848 | 4.15625 | 4 | # Scores and Grades
# Score: 87; Your grade is B
# Score: 67; Your grade is D
# Score: 95; Your grade is A
# Score: 100; Your grade is A
# Score: 75; Your grade is C
# Score: 90; Your grade is A
# Score: 89; Your grade is B
# Score: 72; Your grade is C
# Score: 60; Your grade is D
# Score: 98; Your grade is A
# End of ... |
02818da8195c7903b79501fc4b3315bfe46e230e | Ritella/ProjectEuler | /Euler045.py | 1,159 | 3.609375 | 4 | # Triangle, pentagonal, and hexagonal numbers
# are generated by the following formulae:
# Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
# Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
# Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
# It can be verified that T285 = P165 = H143 = 40755.
# Find th... |
f2d812e9f9d2cadf3d88c1f892328e7bb9e18254 | kilura69/softuni_proj | /2_advanced/03_multidimensional_lists/01_sum_matrix_elements.py | 490 | 4.21875 | 4 |
'''
Write a program that reads a matrix from the console and prints:
* The sum of all matrix elements
* The matrix itself
On the first line, you will get matrix sizes in format "{rows}, {columns}"
'''
matrix_type = input().split(', ')
rows = int(matrix_type[0])
columns = int(matrix_type[1])
matrix = []
for... |
0deb50e343338302a3cabdaad711cf522cd2fdfa | himanshush200599/codingPart | /leetcode/easy/searchInsertPos.py | 1,162 | 4 | 4 | #my solution - Brute force
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target <=nums[0]:
return 0
if target > nums[len(nums)-1]:
return len(nums)
for i in ... |
6d427a59851f441a8c1b544fcf596628d71faab2 | itsdj20/python_practise | /pyth/algo/a3.py | 262 | 3.71875 | 4 | def selection(lst):
for a in range(1,len(lst)):
x=lst[a-1]
if x>lst[a]:
return
# lst=list(map(int,input("input the no to be sorted").split()))
lst = [9, 1, 15, 28, 6]
selection(lst)
print(lst) |
a4d7c97def0de9d0351e6a39d74e3660ac76b3c6 | Andrea2395/manejo_riesgo-criptografia | /trabajoclase#2/ejercicio#3.py | 343 | 4.125 | 4 | def ejercicio3():
numList = list()
minimum = None
maximum = None
for x in range(10):
num = input("Ingrese un número: ")
numList.append(num)
minimum = min(numList, key=int)
maximum = max(numList, key=int)
print("El número mayor es : " + maximum + " y el número menor es: " + mi... |
f8ecb3f667d6c3eab9ab0ba2bf28d8040e2c2873 | MJK0211/bit_seoul | /keras/keras10_split.py | 955 | 3.640625 | 4 | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np
#1. 데이터
x = np.array(range(1,101))
y = np.array(range(101,201))
x_train = x[:70] #70개
y_train = y[:70]
x_test = x[70:] #30개
y_test = y[70:]
#2. 모델구성
model = Sequential()
model.add(Dense(150, input_dim=1)) ... |
4137e1a8d4c23f43f9eafa7f13a77b8601d8c0ad | inaph/30DaysOfPython-inaph | /Day_03/slope.py | 220 | 3.734375 | 4 | def slope_intercept(x1,y1,x2,y2):
slope = (y2-y1)/(x2-x1)
intercept = y1 - slope * x1
return slope, intercept
print(" Slope and intercept of line with point (2,2) and (6,10) are ", slope_intercept(2,2,6,10)) |
de948172cba24b3048a6f1d14ead441ab224fe54 | LucasBrogiolo/Joguinhos | /menuJogos/jogoAdvinha.py | 1,416 | 3.75 | 4 | def jogar():
from random import randint
import sys
numero = randint(0, 100)
tentativas = []
contador = 7
print("\n*******************************")
print("******* Acerte o número *******")
print("*******************************\n")
while contador != 0:
try:
chute... |
4ca2f830f88b1ed218e872c57ebd9735b4180b61 | callmekungfu/daily | /leetcode/pascal_triangle.py | 467 | 3.5 | 4 | from typing import List
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0:
return []
if numRows == 1:
return [[1]]
new_row = [1]
result = self.generate(numRows - 1)
last_row = result[-1]
for i in range(len(la... |
ae2bc9a01ce2a8c2c366eccf35da827fcda04cb8 | Satily/leetcode_python_solution | /solutions/solution105.py | 810 | 3.671875 | 4 | from data_structure import TreeNode, ds_print
class Solution:
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
def find(l, v):
for index, ele in enumerate(l):
if ele == v:... |
8940c85662cfe1388bb07add2ae3f611b9e0cdcd | Hussein-A/Leetcode | /Easy/Python/344. Reverse String.py | 768 | 4.09375 | 4 | #Write a function that reverses a string. The input string is given as an array of characters char[].
#Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
#You may assume all the characters consist of printable ascii characters.
#Runtime: beats ... |
a69691bbe388f39242b63b612e7ba33eb79386db | Redwan-Islam/Python_Simple-Calculator | /simplecalculator.py | 1,192 | 4.375 | 4 |
print (" Welcome to Redwan's Python made calculator ")
# Function to add two numbers
def add(num1, num2):
return num1 + num2
# Function to subtract two numbers
def subtract(num1, num2):
return num1 - num2
# Function to multiply two numbers
def multiply(num1, num2):
return num1 * num2
#... |
e2c915ecd4d8a6ab3068ddde90624b6c7c210722 | vmred/codewars | /katas/7kyu/See your next happy year/solution.py | 685 | 3.640625 | 4 | # Scenario
# You're saying good-bye your best friend , See you next happy year .
# Happy Year is the year with only distinct digits , (e.g) 2018
# Task
# Given a year, Find The next happy year or The closest year You'll see your best friend !alt !alt
# Notes
# Year Of Course always Positive .
# Have no fear , It is... |
057dbbe5ea0798f206abc99464de1cf7f65fd27c | gabjson/Projetos-em-python | /Prova/mala.py | 247 | 3.875 | 4 | largura = float(input('largura :'))
comprimento = float(input('comprimento :'))
altura = float(input('altura :'))
if largura >45 or comprimento >56 or altura >25 :
print("sua mala não é permitida")
else :
print('Sua mala é permitida')
|
378cfdc58337d63de706517ffb51d6c9541738b1 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/2642.py | 1,541 | 3.625 | 4 | # your code goes here
import sys
def flip_s_at(s, pos, k):
st = s
k = int(k)
for i in range(pos,pos+k):
print i
return st.replace('-', '+', pos + k)
def flip_pancakes(s, k):
loops = len(s) - int(k)
scop = list(s)
sout = ''
flip_cnt = 0
kint = int(k)
pos = 0
lpos =... |
de3c3d58d1d4a229a4332464fbf5119852697870 | MikeOcc/MyProjectEulerFiles | /Euler_2_51.py | 2,230 | 3.71875 | 4 | ###
# Problem 51 of Project Euler
###
from math import *
sum = 0
fibnum = 0
firstnum = 0
secondnum = 1
ctr = 1
#startnumber=13
#startnumber*=1.0
def IsPrime(startnumber):
prime = True
for divisor in range(2,startnumber):
if float(startnumber)/float(divisor)==int(float(startnumber)/float(divisor)):
... |
074545a859251046fe909f4f6cd0d0eec1078d47 | btguilherme/Rosalind | /Mendels First Law/Verifications.py | 601 | 3.671875 | 4 | # -.- encoding:utf-8 -.-
import sys
def verifySum(a,b,c):
soma = a + b + c
if soma < 2:
print "Soma dos indivíduos deve ser >= 2 (evitar divisão por zero)."
sys.exit(0)
return
def verifyPositivity(a,b,c):
if (a < 0) or (b < 0) or (c < 0):
print "Parâmetros de entrada devem ser ... |
07eba8ce5e684fa508b02d425eba3b221d988285 | 224apps/Leetcode | /Data-Structures/Quick_Sort.py | 692 | 3.5625 | 4 | class Solution:
def partition(self, arr, low, high):
i = (low -1)
pivot = arr[high]
for j in range(low, high):
if arr[j] < pivot:
i = i+1
arr[i],arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return (i+1)
d... |
1327f21b80122e9922616c6672143927b0e901ef | paulafortuna/SemEval_2019_public | /scripts_pipeline/feature_extraction/FeatureExtraction.py | 2,300 | 3.84375 | 4 | from abc import abstractmethod, ABC
from scripts_pipeline.PathsManagement import PathsManagement as Paths
class Parameters:
"""
Works as a Parent Class that for every set of FeatureExtraction procedure contains the parameters.
"""
def __init__(self, feature_name, dataset_name):
self.feature_n... |
9dabe3d8b655bf8d9a1e045708ea8c4ae15b4671 | kseniadumpling/python-lessons | /week1/lab2.py | 570 | 4.15625 | 4 | # Считать несколько имен людей одной строкой, записанных латиницей, через пробел, например:
# «Anna Maria Peter».
# Вывести их одной строкой в порядке возрастания «Anna Maria Peter».
# Вывести их одной строкой в порядке убывания «Peter Maria Anna».
inputStr = str(input())
arr = inputStr.split()
arr.sort()
output = "... |
adbb0efd27cbc2a09fd1ef656d0629d68ffd2e09 | roldatasci/dsp | /python/advanced_python_csv.py | 679 | 3.828125 | 4 | # WRITING TO CSV
# change to dir
import os
print(os.getcwd())
# read in input file
import csv
with open('faculty.csv', 'r') as f:
data_list = list(csv.reader(f))
header = data_list[0]
data = data_list[1:]
print(header) # ['name', ' degree', ' title', ' email']
print(data[0]) # ['Scarlett L. Bellamy', ' Sc... |
1967d50037c49951ce0958fc191e05e3cdcdcdca | orca9s/crawler | /bs4_sample.py | 1,257 | 3.921875 | 4 | # html_doc = """
# <html><head><title>The Dormouse's story</title></head>
# <body>
# <p class="title"><b>The Dormouse's story</b></p>
#
# <p class="story">Once upon a time there were three little sisters; and their names were
# <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
# <a href="http://ex... |
9b12b842e3d363c4358b515d2684983a31c483fd | agore1/cs3240 | /Lab3/lab3_part1.py | 1,273 | 3.90625 | 4 | __author__ = 'ayg9fh'
from Crypto.Hash import SHA256
user_pass = {}
username = input("Please enter a username: ")
password = input("Please enter a password: ")
# Continuously gather usernames and passwords
while username and password:
print("Got a username and password")
print(username, password)
pass_h... |
7efea7216e2d80193d9c83523df4ce4435ae7de0 | preethi-sv/Backtracking-problems | /ratInAMaze.py | 1,717 | 4.03125 | 4 | # Problem: Check if path exists from (0,0) to (n-1, n-1) in a nxn maze and
# print the path if exists.
# Print the solution path in the maze
def printSolution(solution):
for i in solution:
for j in i:
print('1' if j == 1 else '.', end='\t')
# print(str(j) + ' ', end='')
pri... |
e0e60ae4da2fe456619624b1d7b94ae610390b37 | edyoda/DSA-with-Rudrangshu-310321 | /HashTables/find_pairs_with_sum.py | 1,245 | 4.03125 | 4 | # Python 3 implementation of simple method
# to find count of pairs with given sum.
import sys
# Returns number of pairs in arr[0..n-1]
# with sum equal to 'sum'
def getPairsCount(arr, n, sum):
m = [0] * 1000
# Store counts of all elements in map m
for i in range(0, n):
m[arr[i]] += 1
twice_count = 0
# It... |
a49b1834f0565bce275e54e2a04081d377b1f864 | Empythy/Algorithms-and-data-structures | /字母异位词分组.py | 1,334 | 3.5625 | 4 | # -*- coding: utf-8 -*-#
"""
Created on 2020/7/3 13:05
@Project:
@Author: liuliang
@Email: 1258644178@qq.com
@Description: leetcode 49 字母异分位词分组
所有输入均为小写字母
@version: V1
"""
import collections
from typing import List
from collections import defaultdict, Counter
class Solution:
def groupAnagrams(self, strs: ... |
77f5cd58d58f55c5dbb905ac94cdf75a21cf1ad3 | xklsses/1508 | /9.day/2-三角形嵌套.py | 89 | 3.84375 | 4 | i = 1
while i < 6:
x = 1
while x < i:
print("*\t",end="")
x+=1
print("")
i+=1
|
00f05e0af52001b37b3d496cfb2e5c6374df2ee3 | BillCarreon/CheckIO | /Home/Xs and Os Referee.py | 1,681 | 3.9375 | 4 | def checkio(game_result):
counter = 0
#for loop to iterate through the given strings and replace them with game_results as nested arrays
for indx,val in enumerate(game_result):
#this checks for the horizonal win
if val == "XXX": return "X"
if val == "OOO": return "O"
game_result[ind... |
98e41967062c0752b35bb77388c7c1479d0b23ba | terrifyzhao/educative | /13_top_k/8_find_closest_elements.py | 1,238 | 3.734375 | 4 | from heapq import *
# 排好序的数组,找最接近x的k个元素
def find_closest_elements(arr, K, X):
result = []
close_index = find(arr, X)
start = max(0, close_index - K + 1)
end = min(close_index + K - 1, len(arr) - 1)
for i in range(start, end + 1):
heappush(result, (abs(arr[i] - X), arr[i]))
res = []
... |
3eeebaa6b109966cd0d074d55206e511715dc94b | PollySaf/pythonProject | /polly/while/time_date_ex.py | 1,400 | 4.125 | 4 | # import datetime
# print(datetime.datetime.now())
# print(datetime.datetime(2020,12,12,23,59,59))
#
# 9.1
# name=input("what is your name")
# age=int(input(("how old a u")))
# from datetime import datetime
# now=datetime.now()
# year=now.strftime("%Y")
# year=int(year)+100-age
# print(year)
# 9.2
#
# from datetime i... |
0dd913e84f909c3164ed912177ee49d13bb9dad1 | zhongpei0820/LeetCode-Solution | /Python/500-599/508_Most_Frequent_Subtree_Sum.py | 1,516 | 4 | 4 | #
#Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with t... |
16fd7ee32e6df56566fa01d63834b35c672b2fca | DiyanKalaydzhiev23/fundamentals---python | /functions more exercise/tribonacii sequence.py | 400 | 3.859375 | 4 | num = int(input())
list_nums = []
def sequence():
next_num = 0
if len(list_nums) < 3:
if len(list_nums) == 2:
next_num = list_nums[-1] + list_nums[-2]
else:
next_num = 1
else:
next_num = list_nums[-1] + list_nums[-2] + list_nums[-3]
list_nums.append(next... |
31e0b4fb350552749b03d631f2c61979d0b0defc | grapatin/AOC2016 | /src/day21-Scrambled-Letters-And-Hash/day21.py | 5,658 | 3.609375 | 4 | # import cmath for complex number operations
from abc import abstractproperty
import cmath
# import Path for file operations
from pathlib import Path
from collections import deque
import itertools
problemInputTxt = Path(
"/Users/pergrapatin/Source/AOC2016/src/day21-Scrambled-Letters-And-Hash/input.txt").read_text(... |
26b8f376053dfb9ee8f561adda5f3cc4080753cc | NordicSHIFT/NordicSHIFT | /app/server/scheduleTest.py | 1,109 | 3.640625 | 4 | from scheduler import scheduler2, Schedule
from student import Student
from shift import Shift
import datetime
def main():
###### Create Students ######
students = []
alfred = Student("alfred",10)
students.append(alfred)
bob = Student("bob",10)
students.append(bob)
###### Create ... |
2e00582eb97450dfce83d7222f3a4d7e9e2b739c | mervebetulyalcin/GlobalAIHubPythonCourse | /homeworks/homework_day_3.py | 639 | 4.03125 | 4 | """name = 'merve'
password = '12345'
Name = str(input("Please enter your name : "))
passWord = str(input("Please enter your password :"))
if name==Name and password==passWord:
print("Enter is successfull")
else:
print("Please check your name and password")
"""
info_dictionary = {'merve': '12345', 'erdem':'56... |
1b2cb128de225a8c9d7fe7c758594c55cb896eb4 | moni310/Loops_questions | /row_name.py | 63 | 3.8125 | 4 | name=input("enter the name=")
for name in name:
print(name) |
aed6323ef210fed9043db093f46594a99cd264e0 | ellismckenzielee/codewars-python | /naughty_or_nice.py | 514 | 3.546875 | 4 | #naughty or nice? kata
#https://www.codewars.com/kata/52a6b34e43c2484ac10000cd
def return_names(people,nice=True):
output = []
for person in people:
if (person['was_nice'] == True) and (nice==True):
output.append(person['name'])
elif (person['was_nice'] == False) and (nice==False):
... |
eaddc60b44b6f1bfbb975b7d91750be712c2e591 | hamstaole/hello_python | /func_traning.py | 841 | 4 | 4 | # function that adds two given numbers
def add(term1, term2):
return term2 + term1
print(add(3, 4))
# say hello to the given name
def greeting(person):
print("Say hello ")
print("Say hello " + person + "!")
person = "Duong Kasino"
greeting(person)
# practice
def say_hi(name, age):
print("Hello" ... |
3e6b5f3b25c9b075e383f91c9666760fa5928d78 | yinghuihou/MyLeetCode | /1-100/24.py | 873 | 3.90625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def printList(l: ListNode):
while l != None:
print(l.val)
l = l.next
def main():
a = ListNode(2)
b = ListNode(3)
c = ListNode(4)
d = ListNode(5)
a.ne... |
ca418a794b310224bb2e8925964216fcf6fa57d4 | ffffffuck/Jumptopy | /Jumptopy/chapter.05/Restaurant-3.py | 965 | 3.5 | 4 | class Restaurant:
number_served=0
def __init__(self):
self.restaurant_name = '설사'
self.cuisine_type = '카레'
def describe_restaurant(self):
print("저희 레스토랑의 명칭은 [%s]이고 [%s] 전문점 입니다" %(self.restaurant_name, self.cuisine_type))
def open_restaurant(self):
print("저희 [%s]레스토랑 오픈했... |
e4c212f618538981472fee0f8513b47691c02d1f | mc4/algo | /codeeval/moderate/minimum_coins.py | 317 | 3.609375 | 4 | import sys
def minimum(n):
count = 0
while n > 0:
if n >= 5:
n -= 5
count += 1
elif n >= 3:
n -= 3
count += 1
elif n == 2:
n -= 2
count += 2
else:
n -= 1
count += 1
return count
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
print minimum(int(test.strip())) |
b13673bf1a1368d9b1352bf030f7268c3fb7c93c | Beqott/Python_Uygulamalar- | /Geometrik şekil bulma.py | 1,527 | 4.0625 | 4 | print("""
GEOMETRİK ŞEKİL HESAPLAMA PROGRAMI
DÖRTGENİN TİPİNİ BULMAK İÇİN 1
ÜÇGENİN TİPİNİ BULMAK İÇİN 2 TUŞUNA BASINIZ
"""
)
işlem = int(input("İşlem Numarasını giriniz:"))
if işlem == 1 :
a = int(input("dörtgenin bir kenar uzunluğunu giriniz:"))
b = int(input("dörtgenin karşısındaki kenar ... |
afef8e66ccb1c4f3f5fe85c38ab2b6b70d1307fc | mattheuslima/Projetos-Curso_Python | /Exercícios/Ex.98.py | 770 | 3.65625 | 4 | from time import sleep
def contador(i,f,p):
if i<f:
if p<0:
p= p * (-1)
elif p==0:
p=1
c=i
print(f'\nVamos iniciar a contagem de {i} até {f} com saltos no valor {p}')
while c<=f:
print(f'{c}',end=" ",flush=True)
c+=p
sleep(0.5... |
599d48c0a31abbb1d6dda253341a424133f1679d | PipsVazquez/PythonExamplebyExampel | /e001.py | 115 | 3.640625 | 4 |
print("Hello, Tell me What is your First Name?")
name = input()
print("Hello {}".format(name))
print("Finish")
|
545d1a931826362cb2ca878d94ba02c6ed095990 | STFinancial/Guitar | /note_flashcards.py | 379 | 3.65625 | 4 | import random as r
from constants import NOTES, NOTES_ONLY_FLATS, NOTES_ONLY_SHARPS
show_number_side = False
def select_set(set_num):
return [
NOTES, NOTES_ONLY_FLATS, NOTES_ONLY_SHARPS
][set_num]
while True:
n = r.randint(0,11)
note_set = select_set(r.randint(0,2))
if show_number_side:
input(n)
print(no... |
3bb6d6c52cbf66fe93c773cf4f51139247339ef5 | Sin-Yejun/PPS | /week1/2/2-2_신예준_20210706.py | 300 | 3.5625 | 4 | n = int(input())
for i in range(n):
string = input()
O_count = 1
total = 0
pv = ''
for i in string:
if i == pv:
O_count += 1
else:
O_count = 1
if i == 'O':
total += O_count
pv = i
print(total)
|
25e107f44de8c23f759c477557f82161ba8e5d05 | august-k/sharpy-paul | /sharpy/managers/grids/grid.py | 4,728 | 3.59375 | 4 | import math
import os
from abc import abstractmethod
from s2clientprotocol.debug_pb2 import Color
from sc2.position import Point2, Point3
from .rectangle import Rectangle
from .blocker_type import BlockerType
class Grid:
def __init__(self, width, height):
self.height = height
self.width = width
... |
860aa906eb198666a6d09baafd80ce45ecbccbec | alexandraback/datacollection | /solutions_2463486_1/Python/idno0001/c.py | 1,679 | 3.84375 | 4 | #!/usr/bin/env python
import sys, math
DIGITS = 14
def num_digits(n):
return int(math.log10(n)) + 1
def is_palindrome(n):
s = str(n)
for l in xrange(len(s)):
r = len(s) - (1 + l)
if s[l] != s[r]:
return False
return True
def main(argv=None):
if argv is None:
argv = sys.argv
# Pre-build the list of ... |
8119278d4a6dd0b6ab917c6f875d25f93d704693 | Kimxons/python_TDD | /palindrome.py | 639 | 4.09375 | 4 | class Stack:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self,data):
self.items.append(data)
def size(self):
return len(self.items)
def show(self):
print (self.items)
def peek(self):
return self.items[le... |
0e71d4be72321e8055c682a17d6e3993f8cef5df | agustashd/Learning-Python | /MIT MOOC/polySum.py | 350 | 3.78125 | 4 | from math import *
def polysum(n, s):
'''
n, s: positive integers, n = number of sides and s = length
returns: the sum of the are and the square perimeter rounded
to four decimal places
'''
area = (0.25 * n * (s**2)) / tan(pi / n)
perimeter = s * n
return round(area + perimeter*... |
a29996cddb3c9833c8988ddfe21c5f6d506d4af3 | arunkamaraj/learning | /append_extend_insert.py | 424 | 3.671875 | 4 | def append_example():
li = ['a', 'b', 'mpilgrim', 'z', 'example']
li.append("new")
print li
def insert_example():
li = ['a', 'b', 'mpilgrim', 'z', 'example']
li.insert(2, "new")
print li
def extend_example():
li = ['a', 'b', 'mpilgrim', 'z', 'example']
li.extend(["two", "elements"])... |
567addd4e775a0a80665b75a1666cbf1fdda28e9 | KumarjitDas/Algorithms | /Algorithms/Recursion/Python/countdown.py | 911 | 4.5 | 4 | def countdown(value: int):
""" Print the countdown values.
countdown
=========
The `countdown` function takes an integer value and decreases it. It prints
the value each time it. It uses 'recursion' to do this.
Parameters
----------
value: int
an integer value
Returns
-------
... |
9af1be85f33817c8079333c3e99688418dfe88cf | sushanted/pydemos | /sr/demos/stdlib/MultithreadingDemo.py | 1,377 | 4.09375 | 4 | from threading import Thread
from queue import Queue
# Simple multithreading
class CounterThread(Thread):
def __init__(self, name):
# Note this is important
Thread.__init__(self)
self.name = name
def run(self):
for i in range(10):
print(self.name, i)
workers = ... |
50370593da5f86b9945a1299082ac4d5af9051f9 | fzdm2005/ISU_CS576_project4 | /draw_cspace.py | 2,820 | 3.5625 | 4 | import math
def draw(ax, cspace, obstacles, qI, qG, G, path, title=""):
"""Plot the C-space, obstacles, qI, qG, and graph on the axis ax
@type ax: axes.Axes, created, e.g., fig, ax = plt.subplots()
@type cspace: a list [(xmin, xmax), (ymin, ymax)] indicating that the C-space
is given by [xmin, xm... |
5e0c8b68fc2936435d3c8545cb1d2118868035fc | RobRcx/algorithm-design-techniques | /divide-and-conquer/summation_dc.py | 338 | 3.703125 | 4 | def summation(A, start, end):
if (start == end):
return A[start]
else:
if start == end-1:
return A[start] + A[end]
else:
mid = start + (end-start)/2
left_sum = summation(A, start, mid)
right_sum = summation(A, mid+1, end)
return left_sum + right_sum
A = [3, 4, 2, 1, 5, 8, 7, 6]
print summatio... |
0cee903460a2eab474ba0d6a4ec2565bef6d9ce0 | roxanacaraba/Learning-Python | /25-Frequently-Asked-Python-Programs/Swapping_2_numbers.py | 688 | 3.90625 | 4 | num1=10
num2=20
print("valoarea primului numar inainte de swapping: ", num1)
print("valoarea celui de-al doilea numar inainte de swapping: ", num2)
# Prima abordare cu o variabila temporala:
temp=num1 #rezulta ca tem=10 pt ca num1=10
num1=num2 #rezulta ca num1=20 pt ca num2=20
num2=temp #rezulta ca num2=10 pt ca te... |
677e14e003a72b777a494baa9a0fc4c42f2de1c2 | chinmairam/Python | /factors.py | 120 | 3.578125 | 4 | n=int(input("Enter any no."))
print("Factors of ",n)
i=1
while i<=n:
if n%i==0:
print(i,end='\t')
i=i+1
|
4d6c852b8f206c4dfe881e6a6b8fdc64f22648f5 | liutongling/leetcode | /november1/november_30_ReorganizeString767.py | 2,720 | 3.625 | 4 | #problem description
#Given a string S,check if the letters can be rearranged so that two characters that are adjacent to
#each other are not the same
#if possible, output any possible result, if not possible, return the empty string
class Solution:
def reorganizeString(self, S: str) -> str:
#创建一个字典
... |
29b12757eee62d866686b4805f455da10dac6128 | houyinhu/AID1812 | /普通代码/project/gui/pack.py | 351 | 3.53125 | 4 | import tkinter as tk
window = tk.Tk()
window.title("啊虎")
window.geometry("500x300")
tk.Label(window,text='P',fg='red').pack(side='top') #上
tk.Label(window,text='P',fg='red').pack(side='bottom') #下
tk.Label(window,text='P',fg='red').pack(side='left') #左
tk.Label(window,text='P',fg='red').pack(side='right') #右
window... |
9f9595486f4cf777ca1ccf2bf0da7bd0e9d74811 | alecav98/Software-Elements-of-Computing | /BST_Cipher.py | 5,210 | 4.25 | 4 | # Description: We will will create a simple encryption scheme using
# a binary search tree. To encode a sentence, we insert each letter
# into a binary tree using the ASCII value as a comparative measure.
class Node (object):
def __init__ (self, data):
self.data = data
self.lchild = None
self.... |
8011ddc36d8bc7fcd127b6892a0918189299255b | avijoshi4u/Python | /Removedup.py | 180 | 4.03125 | 4 | lst = eval(input("Enter the list of elements"))
lst2 = []
for each_val in lst:
if each_val not in lst2:
lst2.append(each_val)
print(lst2)
s = set(lst)
print("set", s)
|
e0792747bfd5e1d0459c07e9a78ed455d5bb3ef4 | GDG-Buea/learn-python | /chpt9/piechart.py | 1,568 | 4.0625 | 4 |
# This program uses a pie chart to display the percentages of the overall grade represented by a project's,
# quizzes, the midterm exam, and the final exam, 20 percent of the grade and its value is displayed in red,
# quizzes are 10 percent and are displayed in blue, the midterm exam is 30 percent and is displayed ... |
1fdc50f7ecfc13f38d98979bcc7ad2b8a7dc2daf | i35186513/270201057 | /Lab4/example1.py | 204 | 4.09375 | 4 | the_num = (int(input("Enter a number: ")))
if the_num<10:
print(the_num)
else:
ones = the_num % 10
tens = (the_num//10) % 10
total = ones + tens
print("The sum of the last two digits:",total)
|
ecda19c153611a9be9b4d8b79e2e1da42a1c5362 | tinghaoMa/python | /demo/base/lesson_14_匿名函数.py | 524 | 4.15625 | 4 | #!/user/bin/python
# -*- coding: utf-8 -*-
"""
匿名函数
"""
'''
lambda x: x * x 就是匿名函数
def f(x): return x * x
'''
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6])))
'''
匿名函数可以赋值给变量
f = lambda x: x * x
f(5)
'''
# 匿名函数作为返回值返回
def build(x, y):
return lambda: x * x + y * y
print(build(1, 2... |
73f09a761dabcad400ff5e7127615962bb078f32 | ManuLam/Competition | /Kattis/starArrangements.py | 520 | 3.625 | 4 | def method1(n,i):
if(n % i == 0 or (i*int(n/i+i)*2 == n) or (i*int(n/i+i) + i*int((n+i-1)/i+i) == n)): return True
def method2(n,i):
if((i*int(n/(i+(i-1))) + (i-1)*int(n/(i+(i-1))) == n) or (i*int((n+i-1)/(i+(i-1))) + (i-1)*(int((n+i-1)/(i+(i-1)))-1) == n)): return True
n,a = int(input()), []
print("%d:" %... |
66fd83e9060c425f41ddf34f3dc5652b29c5c58b | lobsterkatie/hackerrank | /algorithms/warmup/simple_array_sum.py | 665 | 4.1875 | 4 | # Given an array of integers, can you find the sum of its elements?
# Input Format
# The first line contains an integer, N, denoting the size of the array.
# The second line contains N space-separated integers representing the
# array's elements.
# Output Format
# Print the sum of the array's elem... |
fdb31e9dbcc352cabe7df943533226494911ee97 | ViniciusAtsushi/Curso-em-Video--python | /Curso em Vídeo/m2/ex_61.py | 770 | 3.78125 | 4 | # Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA,
# mostrando os 10 primeiros termos da progressão usando a estrutura while.
n_inicial = int(input('Digite o primeiro termo da PA: '))
razao = int(input('Digite a razão da PA: '))
aux = 0
while aux != 10:
print(f'{n_inicial}')
n_inic... |
e8670d23f067a0695d3a8224b8c541f2af652549 | pabloTSDAW/Programacion-Python | /Trimestre3/Ejercicios/Ejercicio grafico 4.py | 1,622 | 3.609375 | 4 | '''a) Crear un conversor de temperaturas. Crear una caja de texto
Farenheit [ Entry ] [ Convertir(Button) ] [ Celsius(Label) ]'''
from tkinter import Tk, Frame, Button, BOTH, Label, Entry, DoubleVar, StringVar, IntVar
class Ventana(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, back... |
bfedfb21b838cea44a4a0b10bad1292b8811cf1b | yuvakurakula/BFS-1 | /BinaryTreeRightSideView.py | 865 | 3.953125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# Time Complexity - O(n)
# Space Complexity - O(n)
class Solution(object):
def rightSideView(self, root):
""... |
09c627b840700fd1ff79d1b41b80e1a1bf2958c2 | mailboxsaravanan/definitions | /pass-fail-if-else.py | 310 | 3.796875 | 4 | #50 + PASS otherwise FAIL
#90 to 100 ===> A ==> Even + Odd -
#80 to 89 ===> B
#70 to 79 ===> C
#60 to 69 ===> D
#50 to 59 ===> E
#0 to 49 ===> FAIL
mark = int(input("Enter the mark:"))
if mark < 50:
print("Fail")
elif mark > 50:
print("Pass")
##could not bring range command here
|
36e20861253990eed5deaade35ecb4aa9325d4c0 | michaelcyng/python_tutorial | /tutorial6/while_loop_examples/break.py | 357 | 4.25 | 4 | print("Please enter a positive integer")
required_count = int(input())
count = 1
print("Start counting")
while count <= required_count: # The following runs as long as this condition is true
print("Count: {0}".format(count))
count += 1
if count > 5:
print("Count is greater than 5. Exit the loop")
... |
9c8bcb2e75331ea0f15389850b78e99ac61ad7e2 | TalaatHarb/project-euler-100 | /python-project-euler-100/p018.py | 2,566 | 3.65625 | 4 | from Solution import Solution
class Edge:
def __init__(self, to_node, weight):
super().__init__()
self.to_node = to_node
self.weight = weight
class DAG:
def __init__(self):
super().__init__()
self.adjecency_dict = {}
def add_edge(self, from_node, to_node, weight):... |
59643de65394d24954086d15aa28e48e4f337472 | uFitch/goit-python-homeworks | /Python-2/Homework_9/modul_9_Schoology.py | 2,287 | 3.609375 | 4 | OPERATIONS = {
'hello': hello_func,
'add': hello_func,
'change': change_func,
'phone': phone_func,
'show all': show_all_func,
'good bye': exit_func,
'close': exit_func,
'exit': exit_func
}
phone_book = {}
def input_error(func):
def handler(data):
try:
result =... |
b8436962bbdaf6ec31050b8bde364d3b7d39c37b | armooey/Algorithms | /Sorting Algorithms/Quick Sort/QuickSort.py | 467 | 3.53125 | 4 | def partition(arr, l, h):
pi = arr[h]
i = l - 1
for j in range(l, h):
if arr[j] < pi:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[h] = arr[h], arr[i + 1]
return i + 1
def quick_sort(arr, l, h):
if l < h:
pi = partition(arr, l, h)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.