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 |
|---|---|---|---|---|---|---|
2641fb80715dea3da84a463c049dea07dff806eb | Xmn0721/MTA-python | /Day2-3或5的倍數.py | 154 | 3.796875 | 4 | for i in range(1,101):
if i%3==0 or i%5==0:
print("i=",i)
j=1
while j<=100:
if j%3!=0 and j%5!=0:
print("j=",j)
j=j+1 |
7362bc098ff06e3db45916f1b10266703127220f | kj0y/edX-MITx-6.00.1x | /Wk3 Ex how many.py | 423 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 16 18:24:25 2018
@author: Kandis
"""
aDict = {'B': [15], 'u': [10, 15, 5, 2, 6]}
def how_many(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
'''
x = 0
for i... |
1fc4167135d40d27a43c4b9570ce65ca803e27ce | hexcity/snippets | /py/peterwashere.py | 397 | 3.546875 | 4 | #!/usr/bin/env python3
'''
@author: Peter Howlett
@description: Across the screen
'''
from time import sleep
import time
str = "Peter Was Here"
columns = 79
sleeptime = 0.05
while True:
for col in range(len(str),columns):
print(str.rjust(col))
time.sleep(sleeptime)
for coly in range(columns... |
d58d5405b1626cc7121f8f0e1cffb8a9fab0ca04 | suyalmukesh/python | /HackerRank/linked_list.py | 738 | 4.03125 | 4 | import sys
class node:
def __init__(self,val):
self.val = val
self.next = None
def traverse(self,a):
while(a != None):
print(a.val)
a = a.next
def add_to_last(self,node):
while(self != None):
self = self.next
self.next = node
... |
8fd5268f63a2e24fd57bdceea53c81a75f82eb16 | nicowjy/practice | /JianzhiOffer/43把数组排成最小的数.py | 1,113 | 4.09375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2019-07-17 23:22:39
# @Author : Nico
# @File : 把数组排成最小的数
"""
题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
"""
class Solution:
def PrintMinNumber(self, numbers):
# write code here
res = ''
... |
92ba8108566ae9aa8060e0c6220d779506770847 | samuelhwolfe/pythonPractice | /programs/loops/triangle.py | 166 | 3.734375 | 4 |
for x in range(6):
for y in range(x):
print('*', end='')
print()
for x in range(4):
for y in range(4-x):
print('*', end='')
print()
|
b53308154172f2e410142464b3afe98b9a1cc36d | AdriBird/SiteWeb | /projet HTML 1.0/Exercices/Boucles/exercice40.py | 792 | 3.6875 | 4 | from random import *
def choix_nombre(min, max):
nombre = randint(min, max)
print("L'ordinateur a trouvé son nombre")
return nombre
alea = choix_nombre(int(input("Chiffre minimum: ")), int(input("Chiffre maximum: ")))
def jeu(hypothèse):
trouve = 1
while trouve == 1:
if hypothèse > alea:
... |
ebeb3c800b32ef0160f7de729e2ec2926c8de19b | sasidharan2303/Python-project | /Error_Free_main_ prog.py | 9,304 | 4.28125 | 4 | ### DEFINING FUNCTION FOR ARITHMETIC OPERATIONS ###
def Arithmetic():
try:
if choice_1 == 1:
## Printing Instructions of Arithmetic Opearations ##
print('*************************************')
print(' Enter 1 for Addition Operation\n','Enter 2 for Subtraction Oper... |
f3539ee122a3c75fb2dda2bfe4fd93fb027f732f | omelchert/MCS2012 | /MCS2012_Melchert_LectureMST_supplMat/MCS2012_mstKruskal.py~ | 2,766 | 3.75 | 4 | ## \file MCS2012_mstKruskal.py
# \brief implementation of Kruskals minimum weight
# spanning tree algorithm using a union
# find data structure
#
# \author OM
# \date 12.06.2012
class unionFind_cls:
"""union find data structure that implemnts
union-by-size
"""
def __init__(self):
self.n... |
7ac4f56c4b647e80629b82b3e3b0369b7d1463bf | daniel-reich/ubiquitous-fiesta | /YEwPHzQ5XJCafCQmE_10.py | 55 | 3.5 | 4 |
def odd_or_even(word):
return (len(word) % 2 == 0)
|
6f1acba32e37f91b5b0635aeecc293add7e31b9b | vimalkkumar/Basics-of-Python | /Functions.py | 3,298 | 4.375 | 4 | """
Syntax Location Interpretation
func(value) Caller Normal argument: matched by position
func(name=value) Caller Keyword argument: matched by name
func(*name) Caller Pass all objects in name as individual positional arguments
fu... |
cfb6176ed79332b02c7710bdcc10b4ed5931b635 | daniel-reich/ubiquitous-fiesta | /k9usvZ8wfty4HwqX2_4.py | 313 | 3.71875 | 4 |
def cuban_prime(n):
root = (3 + (12*n - 3)**0.5) / 6
return '{} {} cuban prime'.format(n, 'is' if is_prime(n) and root == int(root) else 'is not')
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if not n%i:
return False
return True
|
ccc3f65eedf05af4aeb8070969eda82b4d7a57f9 | noorul90/Python_Learnings | /Arrays.py | 647 | 3.84375 | 4 | #array will contain all the value of same type unlike list, in python aarays are not fix in side unlike java, u can expand and shrink it
from array import *
vals = array('i', [1,2,5,6])
print(vals)
#creating new array from existing one
newArray = array(vals.typecode, (a*a for a in vals))
print("new array ", newArray)... |
3808f5356c4f63045b0809bf2564e3c8ec4ac574 | valeriacavalcanti/IP-2020.2---R | /semana_18/01_1006_adaptado.py | 276 | 3.90625 | 4 | n1 = int(input('Nota 1: '))
n2 = int(input('Nota 2: '))
n3 = int(input('Nota 3: '))
media = ((n1 * 3) + (n2 * 3) + (n3 * 4)) / 10
print("Média = {}".format(media))
if (media >= 70):
print("Aprovado")
elif (media >= 40):
print("Final")
else:
print("Reprovado")
|
8431f9e4a5aa4783656aa9ff7cfa8dfdf9ba1c1b | gabriel-valenga/CursoEmVideoPython | /ex030.py | 199 | 3.90625 | 4 | from random import randint
numeroDigitado = int(input('Adivinhe o número entre 0 e 5:'))
numeroSorteado = randint(0,5)
print('Você acertou' if numeroDigitado == numeroSorteado else 'Você Errou')
|
5f1b3bc2f31499c6f0a9fe27c78a3cd3745ad250 | camcottle/Game-Public | /game1.py | 2,609 | 4.21875 | 4 | print ("Welcome to Chose your own adventure python edition")
print ("")
def playerNames():
playerNum = int(input("How many players are playing? "))
print(playerNum)
# Great place to consider using a for loop
if playerNum == 1:
player1 = input("What is player one's first name? ")
print(... |
cbc0f8bbc42f763a44c67b7afa4a83f53b21b23d | djaychela/PythonWorkBook | /25.py | 83 | 3.546875 | 4 | from string import ascii_lowercase
for letter in ascii_lowercase:
print(letter) |
e33c09ec8df35d64028ac7c749375631a2063f2b | vit6556/sudoku | /classes/sudoku_board.py | 5,662 | 3.59375 | 4 | import os, itertools
from random import shuffle, randint
from copy import deepcopy
sudoku_banner = " ____ _ _\n/ ___| _ _ __| | ___ | | ___ _\n\___ \| | | |/ _` |/ _ \| |/ / | | |\n ___) | |_| | (_| | (_) | <| |_| |\n|____/ \__,_|\__,_|\___/|_|\_\\\__,_|\n"
class SudokuBoard:
def __init__(... |
7df01a906406cf7131057ed17333eaa1951059ce | zzhang10/RSA-Machine | /RSA Machine.py | 18,959 | 3.5625 | 4 | #========================================================================================#
# #
# RSA ENCRYPTOR 1.0 #
# ... |
a09a376f921143691ccb1ec9a7eb96fe6cad0e76 | CodecoolBP20161/python-pair-programming-exercises-2nd-tw-adam_mentorbot | /passwordgen/passwordgen_module.py | 1,043 | 3.640625 | 4 | from random import randint
word_list_path = '/usr/share/dict/words'
abc = ["0123456789",
"ABCDEFGHIJKLMNOPQRSTUVXYZ",
"abcdefghijklmnopqrstuvxyz",
"!@#$%^&*()?"]
def wordsgen():
f = open(word_list_path, "r")
words = f.readlines()
word_1 = words[randint(0, len(words))].strip()
... |
6ccbb7aedd31b95f8c4bb64992bcd83edf73bd09 | weflossdaily/Project-Euler | /113.py | 708 | 3.609375 | 4 | def countDescending(prefix,numDigits):
count = 0
if numDigits > 1:
for i in range(int(prefix[len(prefix) - 1]) + 1):
count += countDescending(prefix + str(i),numDigits - 1)
else:
#for i in range(int(prefix[len(prefix) - 1]) + 1):
# print prefix + str(i)
return int(prefix[len(prefix) - 1]) + 1
return coun... |
010db25633ca13b307c1e15ce5446acf2c015775 | zhouwangyiteng/python100 | /t16.py | 365 | 3.609375 | 4 | # _*_ coding: UTF-8 _*_
import datetime
print datetime.date.today().strftime('%d/%m/%Y')
birthDate = datetime.date(1995, 3, 2)
print birthDate.strftime("%Y-%m-%d")
birthNextDate = birthDate + datetime.timedelta(days=1)
print birthNextDate.strftime("%Y-%m-%d")
firstBirthday = birthDate.replace(year=birthDate.year+2... |
4c791eb124c6078a9693233453699305b0f2f6b0 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2617/60752/298158.py | 198 | 3.671875 | 4 | i=input()
i1=input()
i2=input()
if i=='2' and i1=="10010 1"and i2=="100101 1":print("9\n11")
else:
if i=='2' and i1=="10010 1"and i2=="100101 2":print("9\n5")
else:
print("3\n11")
|
ec9b54f1d5293505a669a212581e97f4196aa78b | GlebFedorovich/Moon | /fifith_stage.py | 11,594 | 3.625 | 4 |
# units: kilometer, kilogram, second
# coordinate system: the origin is in the center of the moon
#at the initial moment oX is directed at the Moon, oY is directed at the North pole
import math
import sys
import matplotlib.pyplot as plt
import pylab
from numpy import *
output = open('moontoearth.txt', 'w')
INPUT_FILE ... |
78ba5ae264b4b22c676764d4992b079ebb50e8a4 | JaneNjeri/exercises_to_functions | /Scripts/write_genelist.py | 1,462 | 3.796875 | 4 | #! /home/user/miniconda3/bin/python
"""
write_genelist.py takes a gene annotation file
and writes gene names to file
Usage:
python write_genelist.py <gene_file> <outfile>
"""
import sys
in_file = sys.argv[1]
out_file = sys.argv[2]
def getGeneList():
with open(in_file, 'r') as humchr:
... |
fabed1027ab6ff93b3bcf48ef45944ef70ff055b | Aasthaengg/IBMdataset | /Python_codes/p02712/s356101445.py | 106 | 3.53125 | 4 | n=int(input())
a=[]
for i in range(1,n+1):
if not(i%3==0 or i%5==0):
a.append(i)
print(sum(a)) |
1431a5b5620fafacc29f30d2a8d3fe9e71819e77 | lelik9416/Homework | /task_validator.py | 3,449 | 3.515625 | 4 | from abc import ABCMeta, abstractmethod
import os
import datetime
class ValidatorException(Exception):
pass
class Validator(metaclass=ABCMeta):
types = {}
@abstractmethod
def validate(self):
pass
@classmethod
def get_types(cls):
return cls.types
@cla... |
04a60107cce644cd3d87322b2173b8d4c1c190d2 | Global19/pm4ngs | /src/pm4ngs/jupyterngsplugin/utils/load_content_dict.py | 2,410 | 3.9375 | 4 |
def load_content_dict(file, delimiter, strip_line=True,
replace_old=None, replace_new=None, comment=None,
startswith=None):
"""
This function load file content in a dictionary spliting the line in two (key-value)
:param file: File to parse
:param delimiter: ... |
a3ef74ac052606a13361d8531ead5dce148162f1 | rastgeleo/python_algorithms | /sorting/quick_sort.py | 540 | 3.859375 | 4 | import random
def quick_sort(items):
if len(items) <= 1:
return items
pivot = items[0]
lt = quick_sort([item for item in items[1:] if item < pivot])
gte = quick_sort([item for item in items[1:] if item >= pivot])
return lt + [pivot] + gte
def test_quick_sort():
my_list = random.s... |
8f2b65e954502dedf32b7c907284987509746681 | xatlasm/python-crash-course | /chap3/3-10.py | 461 | 3.828125 | 4 | # Every function
categories = ['country', 'city', 'plant', 'animal', 'object', 'boy name',
'girl name', 'famous person']
print(categories[-7].title())
categories.append('foo')
categories.pop()
categories.insert(0,"bar")
del categories[0]
categories.remove('famous person')
categories.sort()
print(catego... |
4f5a3e0627337098314a736f8f160c4a779526bb | HTMLProgrammer2001/pyGame | /Arcanoid/Classes/Ball.py | 2,311 | 3.53125 | 4 | import pygame
from random import random
from globals import *
class Ball(pygame.sprite.Sprite):
def __init__(self, pos):
pygame.sprite.Sprite.__init__(self)
self.size = BALL_SIZE
self.power = 1
self.color = BALL_COLOR
# move
self.isInit = False
# ball di... |
9537234e130166034003d3a6fedd1c33e3c0ffc5 | ushitora/bwt | /bwt/lyndon/lyndon.py | 1,070 | 4.1875 | 4 | def longest_lyndon_prefix(w):
"""
Returns the tuple of the longest lyndon prefix length and the number of repitition for the string w.
Examples:
abbaa -> Returns (3, 1)
abbabb -> Returns (3, 2)
"""
i = 0
j = 1
while j < len(w) and w[i] <= w[j]:
if w[i] == w[j]:
... |
f32bbf84d7b3a7887eab331d062288b7541f9dc1 | dojorio/dojo_niteroi | /2010/20101021_pybr_fizzbuzz/fizzbuzz.py | 202 | 3.625 | 4 | DIV3 = 'Arveres'
DIV5 = 'somo nozes'
def fizzbuzz(numero):
valor = ''
if numero % 3 == 0:
valor += DIV3
if numero % 5 == 0:
valor += DIV5
return valor or str(numero)
|
f91e1e233e9dff8fbd4b2937c9494135ecb8a03f | Alcatraz714/HacktoberFest-1 | /Python Graphics/Projection.py | 480 | 3.578125 | 4 | import math
from graphics import *
win = GraphWin("PolygonClipping", 500, 500)
def main():
print("Enter number of points")
n = int(input())
arr=[]
for i in range(n):
print("Enter x co-ordinate of point")
x = int(input())
print("Enter y co-ordinate of point")
... |
e13af7754459c150351937f14df5a7fbe96f3ea1 | ParthG-Gulati/Python-day-5 | /employee.py | 625 | 4.21875 | 4 | #Consider an employee class, which contains fields such as name and designation.
#And a subclass, which contains a field salary.# Write a program for inheriting this relation.
class employee:
name = ""
designation = ""
def NAME(self):
self.name = input("Enter the name of the Employee:")
... |
47ab767d1e174c8b3445c7b7a0d5e853727d8ef3 | RotemHalbreich/Ariel_OOP_2020 | /Classes/week_09/TA/simon_group/2-variables.py | 2,115 | 4.59375 | 5 | # Creating Variables
x = 5
y = "John"
print(x)
print(y)
# Variable Names
#
# A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
# (case sensitive and don't start with a number)
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
# Ouput Variables
x = "aweso... |
c0c28116a09cd42749f749ccab53c374bb0896b2 | darlasunitha/python | /62.py | 161 | 3.671875 | 4 | p=raw_input()
"""if all(a in '01' for a in q):
print "yes"
else:
print "no"
"""
if not(p.translate(None,'01')):
print "yes"
else:
print "no"
|
222e5d4b9fe694b7081b80b120e4197f23e8ea12 | MichaelKSoh/Euler_Project | /Problem 006/sumSquareDifference.py | 363 | 3.546875 | 4 | targetNum = 100
def sumOfSquares(num):
counter=0
for i in range(1,num+1):
counter += i**2
return counter
print(sumOfSquares(targetNum))
def SquareOfSum(num):
counter = 0
for i in range(1,num+1):
counter += i
return (counter**2)
print(SquareOfSum(targetNum))
print((SquareOfSu... |
e4291c39bed110adbed214dfb4c5b8481bf97c8b | emerette/python-challenge | /PyBank/main.py | 1,935 | 3.5 | 4 | import os
import csv
from statistics import mean
csvpath = os.path.join( 'Resources', 'budget_data.csv')
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter =",")
print (csvreader)
csv_header = next(csvreader)
print(f"Financial Analysis: ")
print("--------------------------"... |
9a4958ed9db568218992a52a989aa7302a2f227c | WdxzzZ/Grab-AzureHackthon | /utils.py | 525 | 3.75 | 4 | # Great circle distance computes the shortest path distance of two projections on the surface of earth.
from math import radians, degrees, sin, cos, asin, acos, sqrt
def haversine(lat1, lat2, long1, long2):
r = 6371 #km
long1, lat1, long2, lat2 = map(radians, [long1, lat1, long2, lat2])
dist_longtitude = ... |
b685f8d36f8299819c4dca1a70eb6b18493fb006 | longhao54/leetcode | /easy/476.py | 407 | 3.53125 | 4 | class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
return int(''.join(['0' if x == '1' else '1' for x in bin(num)[2:]]),2)
def fast(self, num):
res = ''
if num == 0:
return 1
while num!=0:
re... |
29745ca840d4cc825005cd43842e2122c8347704 | jmg5219/First-Excercises-in-Python- | /celsius_to_farenheit.py | 377 | 4.375 | 4 | #Defining a function to convert temperature in Centigrade to Fahrenheit
def convert_F(temp_c):
temp_f = (temp_c*(9/5))+32
return temp_f
#Prompting User Input fo rTemperature in Centigrade
temp_c = int(input("Temperature in C?"))
#Using string interpolation to print the units
print("%.1f F" % (convert_F(tem... |
4004eff7ca1538adb79219b2075d5631286987ac | ghufransyed/udacity_cs101 | /restaurant.py | 1,055 | 4.25 | 4 | class Restaurant(object):
"""
Represents a place that serves food.
"""
def __init__(self, p_name, p_owner, p_chef):
self.name = p_name
self.owner = p_owner
self.chef = p_chef
def display(self):
"""Display the restaurant."""
print self.name
def is_yummy(s... |
a5a55dc61623b21474c1f46536df5d3c8406ae2a | eze2017/Air-traffic-projection | /predictions/fuel_consumption.py | 13,362 | 4.3125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def compute_distances_vector_in_miles(iata_to_fuel):
"""
This function converts distance from nautical miles to miles.
:param iata_to_fuel: Data mapping fuel consumption to aircraft IATA codes
:return x_miles: Array containing distances in miles
"... |
188865e4e7c96c0b6b2ddbd847ce6f16bc1ffdaf | ypyao77/python-startup | /python-cookbook/03.digit-date-time/13-last-friday.py | 2,302 | 4.15625 | 4 | #!/usr/bin/env python3
# 3.13 计算最后一个周五的日期
# 你需要查找星期中某一天最后出现的日期,比如星期五。你需要查找星期中某一天最后出现的日期,比如星期五。
"""
Topic: 最后的周五
Desc :
"""
from datetime import datetime, timedelta
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
# 上面的算法原理是这样的:先将开始日期和目标日期映射到星期数组的位置上 (星期一索引为 0),
# 然后通过模运算计算出... |
21657edaf9b632a2233a9e6c46cf76db6b2116c2 | toolshc/euler | /001-multiples-3-5/multiple-3-5.py | 263 | 4.1875 | 4 | def is_multiple_of_3_or_5(x):
if ( x%3 == 0 ) or ( x%5 == 0 ) :
return True
else:
return False
def sum(top):
total = 0
for i in range(3,top):
if is_multiple_of_3_or_5(i):
total += i
return total
print sum(10)
print sum(1000) #233168 |
4a9e41c920d9c3a95cad8901bf6b8f9810df6a92 | bilakos26/Python-Test-Projects | /Class_Information.py | 1,373 | 4.125 | 4 | class Information:
def __init__(self, name, address, age, phone_number):
self.__name = name
self.__address = address
self.__age = age
self.__phone_number = phone_number
def set_name(self, name):
self.__name = name
def set_address(self, address):
self.__ad... |
cab4ab98c760f3f97c671166dec90fde0030bb53 | Aviv-Cyber/Library_VOL1 | /University/yesno.py | 921 | 3.953125 | 4 | names_list = []
answers_list = []
name = input("Full name: ")
names_list.append(name)
right_answers = []
wrong_answers = []
not_a_yn_answer = []
num_of_question = []
class one:
answer = input("האם חדשנות טובה לכלכלה? : ")
num_of_question.append(1)
if answer == "yes":
right_answers.append(1)
el... |
e11554d1761aac74cdafa4f5401d524eb6e88c2b | frosyastepanovna/5sem | /lab1.py | 2,140 | 3.96875 | 4 | import math, cmath
print("ИУ5-52б Дума Эмилия Михайловна Лаб1\nПрограмма для решения (би)квадратных уравнений.\nВведите тип уравнения, которое хотите решить\n1. Квадратное\n2. Биквадратнрое")
q = int(input())
if q == 1:
args = []
i = 0
while i < 3:
try:
print("Введите коэффициент:")
... |
51d5356fbf82adbe3afca3889fa693ed062bd624 | jithendra2002/LabTest_01-09-2020 | /L3-copyingarrayelements.py | 312 | 3.765625 | 4 | print("Jithendra-121910313053")
a=[]
n=int(input("enter number of elements to be entered into array"))
b=[]
for i in range(0,n):
x=int(input("enter the element:"))
a.append(x)
print("original array is:",a)
l=len(a)
for c in range(0,l):
x=a[c]
b.append(x)
print("new array is:",b)
|
1c6f3192708f3e3685d0c5d79cd5a81fc3e2a453 | sakurasakura1996/Leetcode | /leetcode_weekly_competition/199weekly_competition/5472_重新排列字符串.py | 961 | 3.65625 | 4 | """
5472. 重新排列字符串 显示英文描述
通过的用户数 0
尝试过的用户数 0
用户总通过次数 0
用户总提交次数 0
题目难度 Easy
给你一个字符串 s 和一个 长度相同 的整数数组 indices 。
请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。
返回重新排列后的字符串。
输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
输出:"leetcode"
解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。
"""
from typing import List
class Solution:
... |
846075147226775dd91404436e08323972c456d1 | b-ark/lesson_5 | /Task2.py | 590 | 4.21875 | 4 | # Generate 2 lists with the length of 10 with random integers from 1 to 10, and make a third list containing the common
# integers between the 2 initial lists without any duplicates.
# Constraints: use only while loop and random module to generate numbers
from random import randint
random_list_1 = []
random_list_2 = ... |
fb0df889474d9eed15423d0c28dd08e98e0e5607 | imjaya/Leetcode_solved | /k_closest_point_to_oorigin.py | 658 | 3.65625 | 4 | from typing import List, Tuple
def k_closest_points(points: List[Tuple[int, int]], k: int) -> List[Tuple[int, int]]:
# WRITE YOUR BRILLIANT CODE HERE
import heapq, math
heap = []
for pt in points:
heapq.heappush(heap, (math.sqrt(pt[0] ** 2 + pt[1] ** 2), pt))
res = []
for _ in range(k):
... |
b3e0c42ddf7f32306e93fadc244f6d55f9ed5667 | vritser/leetcode | /python/239.sliding_window_maximum.py | 631 | 3.640625 | 4 | from collections import deque
from typing import List
# https://leetcode.com/problems/sliding-window-maximum/
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = deque() # Store max k elements
ans = []
for i, v in enumerate(nums):
#... |
364379316c552e721da54a7354a9a63a9b31f933 | Nikitoz78/Codewars | /Shift Left/Shift Left.py | 312 | 3.75 | 4 | def shift_left(a, b):
n = 0
for i in range(len(a) + len(b)):
if len(a) >= len(b) and str(a) != str(b):
a = a[1:len(a)]
n += 1
elif len(a) < len(b) and str(a) != str(b):
b = b[1:len(b)]
n += 1
else:
continue
return n
|
fa503f3cb5b484d5c769583b3f8f09c7ed19b5bc | ndneighbor/python-the-hard-way | /exercise3/ex3sd.py | 418 | 3.9375 | 4 | # Finding out what each operator does
print 2 + 4
print 4 - 8
print 64 / 8
print 8 * 8
print 4 % 2
print 3 < 2
print 7 > 2
print 3 <= 1
print 9 >= 2
# The number excersize now in floating point
print "I will now count my imaginary chickens:"
print "Hens", 25.7 + 38.1 / 6.66
print "Roosters", 100 - 25.09 * 3.12 % 4
... |
c2b030b41c73b2e61b96b79aecfec929f681d68d | charusat09/LPTHW | /ex33.py | 107 | 4.03125 | 4 | print("How long you want to print?")
num = int(input("> "))
i = 1
while i <= num:
print(i)
i += 1
|
68baa25b717852c632036aaeb381f45a678a3c37 | Nicolas669/projet_logique | /dames.py | 2,152 | 3.90625 | 4 | #!/usr/bin/env python
# python script to generate SAT encoding of N-queens problem
#
# Jeremy Johnson and Mark Boady
import sys
#Helper Functions
#cnf formula for exactly one of the variables in list A to be true
def exactly_one(A):
temp=""
temp=temp+atleast_one(A)
temp=temp+atmost_one(A)
return temp
#cnf formula ... |
d8718b4da18ec6915297f92350bd18c69ebb17c9 | xxNB/sword-offer | /leetcode/链表/环形链表.py | 238 | 3.609375 | 4 |
class Solution:
def hasCycle(self,head):
fast=slow=head
while fast:
fast = fast.next.next
slow = slow.next
if fast.val == slow.val:
return True
return False |
1b99447ff3477b9fb5a304b11ba1a44ee9f116c4 | LeonardoBerlatto/URI | /2427.py | 78 | 3.671875 | 4 | x = int(input())
soma = 4
while(x/2 >= 2):
x = x/2
soma = soma*4
print(soma) |
03cfd0c9336a9a35320a0c99407b4c5a994d9370 | Sushantghorpade72/100-days-of-coding-with-python | /Day-02/Day2_Tip_Calculator.py | 651 | 4.03125 | 4 | '''
Project Name: Tip calculator
Author: Sushant
Tasks:
1. Greeting for program
2. What is the total bill? 124.54
3. How many people to split the bill? 5
4. What percentage tip would you like to give?10,12 or 15?
5. Each person should pay?
'''
print("Welcome to tip calculator")
bill = float(input("What was... |
2d40a0de4917815fc18c1b653ea9c0cc0f5040ce | atastet/Python_openclassroom | /Chap01/variables/test_list_deref.py | 305 | 3.9375 | 4 | #!/usr/bin/python3.4
# -*-coding:Utf-8
liste = [1, 2, 3]
liste2 = list(liste)
liste2.append(4)
print("liste = {}, liste2 = {}".format(liste, liste2))
print("id liste = {}, id liste2 = {}".format(id(liste), id(liste2)))
liste2 = liste
print("id liste = {}, id liste2 = {}".format(id(liste), id(liste2)))
|
acb4597b9c9eb159548b45015f2cda19a64a81d3 | deebika1/guvi | /codeketa/basis/find_the_exponent_of_the_given_two_number.py | 292 | 4.125 | 4 | # program which is used to calculate the exponent of the given number
def no(num1,num2):
c=(num1**num2)
return c
# get the value of num1 and num2 from the user
num1,num2=list(map(int,input("").split()))
res1=no(num1,num2)
# print the result of the exponential of the two number
print(res1)
|
42d3fb18196e12816af55ec1c8fccc6889108c47 | Shibaram404/Example | /003_python_List_operation/in_list.py | 593 | 4.375 | 4 | myList = [0, 3, 12, 8, 2]
print(5 in myList)
print(5 not in myList)
print(12 in myList)
# Python offers two very powerful operators,
# able to look through the list in order to check whether a specific
# value is stored inside the list or not.
## The first of them (in) checks if a given element (its left... |
d53de8531cf8603bdd66ad0d16880f7381dd5f16 | thiagonantunes/Estudos | /aulas/dictionary.py | 1,370 | 4.25 | 4 | """
DICIONÁRIO
"""
d1 = {'chave1':'item 1', 'chave2': 'item2'}
d2 = dict(chave1='item 1', chave2 ='item 2') #outra maneira de criar dicionário
d2['nova_chave'] = 'novo item' # adicionando novo item no dicionário
d1['chave'] = 'item'
#para saber se uma key está no dicionário, caso não exista a chave, imprimi valor N... |
8fd470ea556df326c07be86f69e36c332b89f6cf | rosezaf/rose_Challenge | /validate_creditcard.py | 441 | 3.953125 | 4 | import re
t=input()
def check(string):
for i in range(0,len(string)-3):
if string[i]==string[i+1]==string[i+2]==string[i+3]:
return False
return True
for i in range(0,t):
string=raw_input()
if check(string.replace("-",""))==False:
print"Invalid"
elif bool(re.matc... |
3db38ce8d5677eb6a16fbc4d214d513d2ca22d28 | lord12-droidd/Colokvium-AP | /Coloc 7.py | 827 | 3.75 | 4 | """Створіть масив А [1..12] за допомогою генератора випадкових чисел з
елементами від -20 до 10 і виведіть його на екран. Замініть всі від’ємні елементи
масиву числом 0.
Мельник Д.В.
"""
import random
massive = [random.randint(-20, 10) for i in range(12)] # Генератор списку для ініцалізації масиву та його елементів
p... |
bf6324743c584d2d7f972ead4bc6a00e8ff4d1be | Fenster7/How-many-coins-1-3-5 | /How manys coins 1-3-5.py | 264 | 4.09375 | 4 | total = int(input("What is the total worth of your coins?"))
five = int(total/5)
three = int((total - (five * 5)) / 3)
one = int(total - ((five * 5) + (three * 3)))
print("You have these coins:", five, "5 coin(s)", three, "3 coin(s)", one, "1 coin(s)")
|
9499392e0ff11cec3ec148b59d8585bfcb6b862d | armelite/python-learning | /hello.py | 3,275 | 4.0625 | 4 | #i/usr/bin/env/ python3
#-*- coding:utf-8 -*-
import math
'''
print('中文测试正常')
t = (['apple','huawei','xiaomi'],[1000,2000,500],['hongkong','shanghai',
'guangzhou'])
print(t)
name = input('please enter your name:')
print('hello,',name)
age = int(input('please enter your age:'))
#print(age)
if age >= 18:
print('hell... |
4ffe1ca99b1c12e9239d6d7bd63335b09382b023 | daniel-reich/ubiquitous-fiesta | /gdzS7pXsPexY8j4A3_22.py | 283 | 3.84375 | 4 |
def count_digits(lst, t):
result = []
for element in lst:
count = 0
for digit in str(element):
if t == "even" and int(digit)%2 == 0:
count += 1
if t == "odd" and int(digit)%2 != 0:
count += 1
result.append(count)
return result
|
28db64ea2f6e4fe76681413c8e57a729a1e66b59 | kishorebolt03/learn-python-the-hard-way | /ITVAC/problem_solving/dict_problem.py | 1,502 | 3.734375 | 4 | #sorting (NESTED DICTionary)
dict=
{
'AB':{'eng':40,'sci':50},
'RA':{'eng':10,'sci':40},
'JE':{'eng':30,'sci':60}
}
#using predefined func
l=[]
for k ,v in dict.items():
l.append(v['eng'],k)
print(sorted(l))
#using userdefined func
def sortdict(b,rev):
a=b
cnt=[i+1 for i in range... |
309c2fe9731868a03834fa73f954ec9a877f0e7c | darioabadie/bairesdev | /main.py | 4,228 | 3.5625 | 4 |
# Librerías
import pandas as pd
import os
import sys
def main():
# Lectura del archivo people.in
data = []
with open (os.path.join(os.path.dirname(sys.argv[0]), "people.in"), "r") as myfile:
data.append(myfile.read())
# Parseo de los datos y ordenamiento en un dataframe
data = data[0... |
a89f7e79fe282bbaddd808029c7dd91c4346245d | OhOverLord/loft-Python | /алгоритмы 1 курс/(2.2.2)last_fibonacci_number.py | 835 | 3.96875 | 4 | """
Выполнил: Филиппов Л. П2-17
Задача:
Дано число 1≤n≤107, необходимо найти последнюю цифру n-го числа Фибоначчи.
"""
def fib_digit(n):
"""
Функция для нахождения последней
цифры n-го числа Фибоначчи
:param n: n-ое число Фибоначчи
:return: последняя цифра n-го числа
"""
if n < 2:
... |
2dde63440235667ef0101da51c9c33fa0c10e952 | Werkov/Completion | /src/python/learning/stripTex.py | 5,641 | 3.546875 | 4 | #!/usr/bin/env python3
import sys
import argparse
import re
from string import ascii_letters
def stripTex(file):
"""Strip mathematics, content of chosen sequences, sequences and braces from TeX source."""
S_TEXT = 0
S_INLINE = 1
S_DISPLAY = 2
S_DOLLAR_IN = 3
S_DOLLA... |
b4f2b525801f4a0a5467b45a1983da960594e619 | Kvazar78/Skillbox | /24_classes/dz/task_9.py | 1,112 | 3.625 | 4 | from random import choice
class Pole:
lst = [i for i in range(1, 10)]
def input(self, player, coord):
self.lst[coord - 1] = player.symbol
def print_pole(self):
count_elem = 0
print("-" * 13)
for i_elem in self.lst:
count_elem += 1
print(f'| {i_elem... |
596e4aa351bc033a616d3bce885c599985ff586d | AdamZhouSE/pythonHomework | /Code/CodeRecords/2546/60586/261559.py | 206 | 3.59375 | 4 | def exam6():
t=int(input())
for i in range(t):
p=[1,1,1]
n=int(input())
for j in range(3,n+1):
x=p[j-2]+p[j-3]
p.append(x)
print(p[n])
exam6() |
f247f7259f4550d53e797fc2657f78664f249793 | Thiagomrfs/Desafios-Python | /aula 13/desafio052.py | 338 | 3.859375 | 4 | num = int(input("Digite um número: "))
resp = 0
for c in range(1, num+1):
if num % c == 0:
print("\033[34m", end=" ")
resp += 1
else:
print("\033[31m", end=" ")
print(f"{c}", end=" ")
if resp == 2:
print(f"\n\033[34mseu número É primo")
else:
print("\n\033[31mseu número NÃO... |
6f958d764f281796334cec6201670421ed91d759 | poojavarshneya/algorithms | /generate_pallindromic_compositions.py | 738 | 3.84375 | 4 | def generate_pallindromes(s, result, midpoint):
print ("entering: midpoint =", midpoint)
if (midpoint < 0 or midpoint == len(s)):
print(result)
return
start = midpoint
end = midpoint
while s[start] == s[end]:
start = start - 1
end = end + 1
if start < 0:
... |
2da54b928558d794aa84797431598c75684e8076 | Imperiopolis/ccmakers-python | /Day 1/04 variables.py | 414 | 3.5 | 4 | my_name = 'Nora Autumn Trapp'
my_age = 24 # years
my_height = 71 # inches
my_eyes = 'Hazel'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "She's %d years old." % my_age
print "She's %d inches tall." % my_height
print "She's got %s eyes and %s hair." % (my_eyes, my_hair)
# this line is tricky, try to ... |
56a7bbf5fa825d0654ecd45a037cce79f5c6ddd3 | hugechuanqi/Algorithms-and-Data-Structures | /Interview/pratical_interview/hw_0002、矩阵相邻搜索.py | 5,807 | 3.9375 | 4 | ## 题目:矩阵相邻搜索
## 类型:矩阵,回溯法
## 应用:涉及到机器人行走路径
## 题目描述:给定一个矩阵,然后给你一个路径,matrix=[[1,2,3,4,5],[11,12,13,14,15],[21,22,23,24,25],[31,32,33,34,35],[41,42,43,44,45]],path=[1,2,3,4,5,11],并且矩阵中的路径可以超出限制,判断是否存在所给定路径
## 核心:1、如何找到第一个路径点;2、如何沿着这条路径依次行走,包括向上、向下、向左、向右,每次都得判断是否超出边界;3此题似乎可以超出边界。
## 思路:首先输入一个矩阵和路径,首先???
# python知识扩展:对于if ... |
1b20d13f321d69e85a70108902b7e11d9e5e3f09 | kc4v/CSE | /Trenten Williams - World Map OOF.py | 5,427 | 3.609375 | 4 | class Room(object):
def __init__(self, name, north, south, east, west, description):
self.name = name
self.east = east
self.north = north
self.south = south
self.west = west
self.description = description
def move(self, direction):
global current_node
... |
762b5c437a735f329e31508dd3aa3abb248179bc | soraoo/python_study | /basic/09_class/exercise.py | 958 | 4.09375 | 4 | class Dog:
"""一次模拟小狗的简单尝试"""
def __init__(self, name, age):
"""初始化属性"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗收到命令时蹲下"""
print(f'{self.name} is now sitting')
def roll_over(self):
"""模拟小狗收到命令时打滚"""
print(f'{self.name} rolled over!... |
57085bda8fcc493bbce9dad20a617648250866a2 | ksrntheja/08-Python-Core | /venv/modules/31RandRangeFunction.py | 333 | 3.734375 | 4 | from random import *
for i in range(5):
print(randrange(5))
print()
for i in range(10):
print(randrange(1, 11))
print()
for i in range(10):
print(randrange(1, 11, 2))
print()
print(randrange(0, 101, 10))
# 3
# 4
# 4
# 3
# 2
#
# 8
# 5
# 8
# 2
# 6
# 7
# 4
# 2
# 5
# 4
#
# 7
# 3
# 5
# 9
# 3
# 5
# 9
# 1
#... |
8abcb5e660edb1c52d1bac697ae7dffeb3aaad99 | Kenterbery/Discrete_labs | /lab5/main.py | 2,220 | 3.5625 | 4 | from tkinter import *
from tkinter import messagebox
from tkinter.font import Font
import combinatorics
class MainWindow(Tk):
def __init__(self):
super().__init__()
self.initFonts()
self.initUI()
def initFonts(self):
"""Ініціалізація шрифтів, кольорів"""
self.color = "#... |
f4aaccfedc50219552853a8e681c934af8205ca9 | krish-bajaj123/Miscellaneous-Python | /greatest numer.py | 171 | 3.96875 | 4 | a,b=int(input("enter 2 numbers")),int(input())
if(a>b):
print("a is the greatest")
elif(a==b):
print("both are equal")
else:
print("b is the greatest")
|
e0a0f1495c0c36d6565ba2febd6fdf0cd6038e35 | minhduc9699/PhamMinhDuc-fundamental-c4e16 | /S2/BMI.py | 599 | 4.40625 | 4 | height = float(input('what is your height? (cm) '))
weight = float(input('what is your weight? (kg)'))
#convert unit from cm to m
height_cm = height / 100
#BMI calculate
BMI = weight / (height_cm * height_cm)
print('your height is: %.f (cm) = %.2f (m)' % (height, height_cm))
print('your weight is: %.f (kg)' % (weigh... |
8dffd3321dd26680435d9111b1c42e96db866ac0 | diegolinkk/exercicios-python-brasil | /exercicios-com-listas/exercicio11.py | 516 | 4.25 | 4 | #Altere o programa anterior, intercalando 3 vetores de 10 elementos cada.
vetor_1 = []
vetor_2 = []
vetor_3 = []
for i in range(10):
vetor_1.append(int(input("Digite um número inteiro: ")))
vetor_2.append(int(input("Digite outro número inteiro: ")))
vetor_3.append(int(input("Digite outro número inteiro: ... |
e6f003175605dc8f6adc845dbe1ac054b1a740fa | developyoun/AlgorithmSolve | /solved/2475.py | 110 | 3.515625 | 4 | numbers = list(map(int, input().split()))
total = 0
for num in numbers:
total += num**2
print(total % 10) |
c42a4d6e361de3e4d9675f2ee7b9ad8565ad0955 | reed-qu/leetcode-cn | /RemoveNthNodeFromEndOfList.py | 1,628 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/19 下午12:06
# @Title : 19. 删除链表的倒数第N个节点
# @Link : https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
QUESTION = """
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有... |
4067a4a09fa24ff2468fcb79b0d342246730ea97 | DolanDark/Data-Science-projects | /BioInfomatics/DNA count.py | 1,976 | 3.546875 | 4 | import pandas
import streamlit
import altair
from PIL import Image
dna_image = Image.open("gettyimage.jpg")
streamlit.image(dna_image, use_column_width=True)
streamlit.write("""
# DNA Count Neucleotide
This app counts the neucleotide composition of query DNA
***
""")
streamlit.header("Enter the... |
30588ec75a6c20bffa7b3d1397184270c5705c34 | MichelFeng/leetcode | /27.py | 592 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
"""description"""
def removeElement(self, nums, val):
"""TODO: Docstring for removeElement.
:returns: TODO
"""
if not nums:
return 0
n = len(nums)
l = 0
while l < n:
... |
96b9b0a0f5a530fda756f8669e5e35f3f7603856 | ChristianBalazs/DFESW3 | /printend.py | 667 | 3.890625 | 4 |
listVar = ['violin', 'viola', 'cello','traingle', 'harp', 'flute']
print('')
print(listVar[-3])
print('')
# to print item at position -3
listLen=len(listVar)
print(listVar[-listLen])
# to print item at position -lenght o the list = first on the list
print(' ')
# For loop
for tempVar in listVar:
print(tempVar... |
82ce44a2e82d6bb4446ec99f70a5ce50b42e664a | emrekardaslar/HackerRank-Questions | /Problems Solving Questions/dayOfProgrammer.py | 571 | 3.875 | 4 | def checkLeap(year):
if ( (year <= 1917) and (year%4 == 0) or (( year%400 == 0) or (( year%4 == 0 ) and ( year%100 != 0)))):
return True
elif (year == 1918):
return True
else:
return False
def dayOfProgrammer(year):
check=checkLeap(year)
if check == True and year == 1918... |
631e47868021d1bce89292c230803398fd53ffc7 | Mihyar-30614/Backtracking_Algorithm | /KnightTour.py | 1,589 | 3.765625 | 4 | # Cheesboard size
size = 8
# Helper Function to print Solution
def printSolution(board):
for i in range(size):
for j in range(size):
print(str(board[i][j]).zfill(2), end=' ')
print()
# Helper function to check if i,j are in n*n board
def isSafe(board, new_x, new_y):
if (new_x >= 0 ... |
0e6fad420262eb7a9911666280508603df5dc146 | jakesant/dsa-assignment | /q12.py | 547 | 4.21875 | 4 | #Write a function that returns the sum of the first n numbers of the
#Fibonacci sequence. The first 2 numbers in the sequence
#are 1,1, …
def sum_fib(nterms):
x = nterms
sum = 0
while nterms != 0:
sum += fib(nterms)
nterms -= 1
print("The sum of the first", x, "values is", sum)
def f... |
3e3321a59f23adbf1be87c8f74d6e30063a9326b | abueesp/mathstuffinc | /bitscalc.py | 773 | 4.3125 | 4 | ## Bits Calc ##
## Author: Abueesp ##
## Date: Tue, May 23 2015 ##
## License: CC NC-BY-SA ##
scriptname = 'Bits Calc'
prompt = '> '
print "Hello, I'm the", scriptname, "a pretty dumb code for calculating bits"
print "Introduce the number of bits: "
bits = int(raw_input(prompt))
bytes= bits/8
print "You have", bits,... |
48f6447b7442ebadcd362e6cff7d3d719d61143f | kailash-manasarovar/A-Level-CS-code | /functional_programming/lambda.py | 1,188 | 4.21875 | 4 | ## writing lambda functions in Python
# ## simple addition and multiplication
# function = lambda a : a + 15
# print(function(10))
# function = lambda x, y : x * y
# print(function(12, 4))
#
#
# ## sort a list of tuples
# # https://docs.python.org/3/howto/sorting.html - lots of sorting options
# subject_marks = [('Eng... |
d269f0fd67b790c90dec731ef68b5fa6f32b9c32 | damv00/da-academy-pycharm | /Repaso/Matrix_programs/Tic_tac_toe1.py | 1,107 | 4.4375 | 4 | '''
Draw A Game Board
Time for some fake graphics! Let’s say we want to draw game boards that look like this:
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
This one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and ... |
c3208e83d10e9e4a13eb668bb92ab74e49fb0d8a | prathy16/LeetCode | /word_ladder.py | 1,507 | 3.8125 | 4 | '''
Problem: https://leetcode.com/problems/word-ladder/
'''
from collections import deque
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
def d... |
013eae7b31590b2671a35ace62d2906d31b50483 | himraj123456789/competitive-programming- | /breaking_the_records.py | 1,665 | 3.5 | 4 | import os
import sys
import random
import math
def binary_find(t,r):
l1=0
r1=len(r)-1
while(l1<=r1):
mid=int((l1+r1)/2)
if(r[mid]==t):
return mid+1
break
if(r[mid]<t):
if(r[mid-1]>t):
return(mid+1)
bre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.