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 |
|---|---|---|---|---|---|---|
2213e27af6af0016ae88f618b3168f44ff5b8d83 | melissabica/whats-up | /tweet_classify.py | 7,487 | 3.71875 | 4 | def hasRepeats(document):
"""Returns True if more than 3 consecutive letters are the same in document."""
previous = ''
two_previous = ''
for letter in document:
if letter == previous == two_previous:
return True
two_previous = previous
previous = letter
return Fa... |
523d3c3eab34a3fa8b4ee657661b741688165385 | derickdeiro/curso_em_video | /aula_22-modulos-pacotes/desafio_110-reduzindo-ainda-mais-seu-programa.py | 359 | 3.53125 | 4 | from utilidadescev import moeda
"""
Adicione ao módulo moeda.py criado nos desafios anteriores, uma função chamada
resumo(), que mostre na tela algumas informações geradas pelas funções que já
temos no módulo criado até aqui.
"""
valor = float(input('Digite um valor: '))
p = float(input('Digite um percentual: ... |
6542dac8bffdcdd3dc71ebbe849d4e4e230ec374 | ferreret/python-bootcamp-udemy | /36-challenges/ex122.py | 441 | 3.9375 | 4 | '''
find_the_duplicate([1,2,1,4,3,12]) # 1
find_the_duplicate([6,1,9,5,3,4,9]) # 9
find_the_duplicate([2,1,3,4]) # None
'''
def find_the_duplicate(numbers):
duplicates = [num for num in numbers if numbers.count(num) > 1]
return duplicates[0] if len(duplicates) > 0 else None
print(find_the_duplicate([1, 2, 1... |
8548c0a9e45c998638964b041981ba2719cc9348 | joetechem/cs_python | /cs_python/foundations/functions_and_loops/greeter_v3.py | 729 | 4.3125 | 4 | # Python 2.7
# USING A FUNCTION WITH A WHILE LOOP
# Let's use the get_formatted_name() function we looked at earlier
# Only this time, we'll throw in a while loop to greet users more formally.
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = first_name + ... |
85aec4f07ff69396d9e296d0de5ba44dd0dc2db2 | DanAyala/TAPfinal | /prime_threading.py | 1,657 | 3.609375 | 4 | #!/usr/bin/env python3
import concurrent.futures
import multiprocessing
import time
def primos(inicio, fin):
numeros_primos = list()
for num in range(inicio,fin + 1):
if (num > 1):
for i in range(2,num):
if (num % i) == 0:
break
else:
#print(num)
numeros_primo... |
0d93361de78939022811722fef37f7fe4f0cb3a0 | ttomchy/LeetCodeInAction | /tree/q543_diameter_of_binary_tree/solution.py | 1,007 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
FileName: solution.py
Description:
Author: Barry Chow
Date: 2020/11/18 4:03 PM
Version: 0.1
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Sol... |
050d1a40cd52edbaa112f07caaf261aa4b1d929b | tedtedted/Project-Euler | /004.py | 569 | 4.25 | 4 | """
A palindromic number reads the same both ways.
The largest palindrome made from the product of
two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
palindromes = []
def is_palindrome(num):
string = str(num)
first = string[:]
last = st... |
af0d0f111416a1c47748e522211d81cf9ecb1b46 | vagerasimov-ozn/python18 | /contin.py | 117 | 4 | 4 | number = 0
while number < 15:
number+= 1
if number % 3 == 0:
continue
else:
print(number) |
b9a17467eb7e05a864b2a8999abea888f89ac17a | luckmimi/leetcode | /LC79.py | 904 | 3.65625 | 4 | class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
for row in range(len(board)):
for col in range(len(board[0])):
if self.backtrack(board, row, col, word):
return True
return False
def backtrack(self,board,row, col, word):
... |
afa93a0d1ea8e998cc5efedd0862b9db584e4446 | 4mayet21/COM404 | /3-decision/2-if-else/bot.py | 235 | 3.90625 | 4 | #asking for input
print("what activity would you like me to perform?")
activity = str(input())
if activity == "calculate":
print("performing calculations...")
else:
print("performing activity...")
print("activity completed!") |
67c309bee7acb56ac1d5de2c902af9afe0bb5995 | Dilmer-R/Python-POO | /Ejercicio 4/Ejercicio_4--Herencia--Walter_Diaz.py | 3,980 | 4.09375 | 4 |
class Productos():
def __init__(self,nombre,costo,tipo):
self.nombre=nombre
self.costo=costo
self.tipo=tipo
def informe(self):
print(f""" ---INFORME DEL PRODUCTO---
Nombre: {self.nombre}
Costo: {self.costo}
Tipo: {self.tipo} """)
... |
652a69f3019e6890b3fb4963e987ea49326cf08b | santiagovasquez1/Curso-python | /programa 007.py | 988 | 4.125 | 4 | #Pedir informacio al usuario
#Usano iput
#Usando raw input
#Al escribir cadenas hay que ponerlas con ""
"""
nombre = input ("Dame tu nombre ")
base_=input ("Dame la base " )
altura= input ("Dame la altura ")
area = base_*altura
perimetro = 2*(base_+altura)
#print "Hola %s el area es %.2f y el perimetro es %.2f" ... |
1353797e71e0f5b851088c1430f3bca2b4b0ee75 | wjj8795/learngit | /出租计费.py | 372 | 3.578125 | 4 | i = 1
while i == 1:
km = int(input())
if km <= 0:
print ("请输入正确的公里数进行计算,程序结束")
elif km > 0 and km <=2:
money = 8
print (money)
elif km >2 and km <=12:
money = 8 + (km - 2) * 1.2
print (money)
elif km > 12:
money = 8 + 10 * 1.2 + (km - 12) * 1.5
... |
5489a44fcb5098d1cf65d91ca1bb9fbd09c8ce46 | deepthi93k/icta-calicut-fullstack | /python/reverse.py | 289 | 4.09375 | 4 | num=int(input("Enter a number"))
rev=0
while(num>0):
rem=num%10
rev=rev*10+rem
num=num//10
print(rev)
def reverse(n):
rev=0
rem=0
while(n>0):
rem=num%10
rev=rev*10+rem
num=num//10
return rev
num=int(input("number is"))
result=reverse(num)
print(result)
|
30a690ce5f9b126d0bb19eb4005bf105a752830f | mouyleng2508/VS_Code | /Cryptography Algorithm/tempCodeRunnerFile.py | 345 | 3.578125 | 4 | from string import maketrans
rot13trans = maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')
# Function to translate plain text
def rot13(text):
return text.translate(rot13trans)
def main():
txt = "ROT13 Algorithm"
print (rot13(txt))
if __name... |
135cccba85a1f12348d73cceff34be2ed66e54d9 | nhuntwalker/code-katas | /src/find_smallest_int.py | 458 | 4.1875 | 4 | """Find the smallest integer in the array (7 kyu).
Given an array of integers your solution should find the smallest integer.
For example:
Given [34, 15, 88, 2] your solution will return 2.
Given [34, -345, -1, 100] your solution will return -345.
You can assume, for the purpose of this kata,
that the supplied array ... |
0f6e5338306385788ba860aec11ecc22577a0947 | GlebovAlex/2020_eve_python | /Lasya_Homework/vowel.py | 753 | 4.40625 | 4 | '''
1) count the number of each vowel in a string using dictionary and list comprehension.
'''
# created a vowel list with all the vowel alphabets as elements
vowel = ['a','e','i','o','u']
vowel_Counts = dict()
userInput = input('Enter your string input here: ').lower()
'''
iterated through the user provide... |
1c9402fc06021cce1f6cde783fd33a49e21a3e31 | perfsonar/pscheduler | /python-pscheduler/pscheduler/pscheduler/filestring.py | 835 | 4.25 | 4 | """
Functions for retrieving strings from files
"""
import os
def string_from_file(string, strip=True):
"""
Return an unaltered string or the contents of a file if the string
begins with @ and the rest of it points at a path.
If 'strip' is True, remove leading and trailing whitespace
(default be... |
bca56c6463631c1c898b73b57faa1dec1877a54a | rvcevans/adventofcode | /2015/advent5.py | 1,318 | 3.59375 | 4 | import os, requests
strings = requests.get('http://adventofcode.com/day/5/input',
cookies=dict(session=os.environ['ADVENT_SESSION'])).content.strip().split('\n')
vowels = {'a', 'e', 'i', 'o', 'u'}
disallowed_strings = {'ab', 'cd', 'pq', 'xy'}
def vowel_count(word):
count = 0
for vowel ... |
28c7bcdf0fb860381989b7a0af378ae36e6c94b4 | ptwd/MSU_REU_ML_course | /_build/jupyter_execute/notebooks/day-4/Day_4-What_is_Tuning_and_Validation.py | 4,009 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # What is Tuning and Validation?
#
# ## 1. What have done so far?
#
# Thus far we have talked about two kinds of supervised machine learning problems: regression and classification. Fairly broad definitions of these two are below:
#
# * **Regression**: Using a set of input da... |
5fb31ef827e45e6e52581c11e81a6071151abc3b | DaisyKoome/Python_Scripts | /Py101.py | 182 | 3.96875 | 4 | name=input('Please enter your name: ')
age=input('Please enter your age: ')
print("The name of the person is",name,"and the age of the person is",age)
input("Press enter to quit")
|
b71da885208f93e6ecf17c0946322a125dc4e08d | kawai-sk/Competition_programming-Python3- | /Slim_Span.py | 1,082 | 3.53125 | 4 | # coding: utf-8
# Slim Span,https://onlinejudge.u-aizu.ac.jp/#/problems/1280
# 右、奥
# 最小全域木の全探索です。重さ順にエッジをソートし,
# 最初に繋ぐ辺として選ぶものを軽い方から順に調べます。
def root(x):
r = []
while P[x] != x:
r.append(x)
x = P[x]
for u in r:
P[u] = x
return x
def unite(x,y,n):
a = root(x)
c = root(y)... |
59e3386bacca956914b27d45991184ef6788a976 | Gilb03/bouncer | /app.py | 318 | 4.125 | 4 | age = input("How old are you: ")
if age != "":
age = int(age)
if age >= 18 and age < 21:
print("You can enter but need wristband")
elif age >= 21 :
print("You can enter and drink!")
else:
print("You cant come in little dude =(")
else:
print("Please enter an age!")
|
3d316938ac872e43bec981709f797c994e83be60 | yandexdataschool/Practical_RL | /week04_[recap]_deep_learning/mnist.py | 2,505 | 3.703125 | 4 | import sys
import os
import numpy as np
__doc__ = """taken from https://github.com/Lasagne/Lasagne/blob/master/examples/mnist.py"""
def load_dataset():
# We first define a download function, supporting both Python 2 and 3.
if sys.version_info[0] == 2:
from urllib import urlretrieve
else:
... |
116945196336be265fec1553109af3ce10b88e01 | hevalhazalkurt/codewars_python_solutions | /6kyuKatas/Which_are_in.py | 189 | 4 | 4 |
def in_array(array1, array2):
arr = []
for a2 in array2:
for a1 in array1:
if a1 in a2 and a1 not in arr:
arr.append(a1)
return sorted(arr)
|
c9066581c2b67d35404fdfafbacb4ef76074f277 | KocUniversity/comp100-2021f-ps0-ER-Mustafa | /main.py | 195 | 3.859375 | 4 | import math
x = int(input("Enter number x: "))
y = int(input("Enter number y: "))
result = x**y
print("x**y = " + str(result))
print("log(" + str(x) + ") = " + str(math.log2(x)))
print("76742") |
ce54bdfbd0ba728265689328bc2e08d42b5d3374 | flightdutch/Python-HomeTasks | /L7.Theory/2Person.py | 1,360 | 4.25 | 4 | """
Person Class
"""
class Person:
max_age = 120
# Создает объект alex - екземпляр класса Person
alex = Person()
# Созадем атрибуты объекта (переменные)
alex.name = 'Alex'
alex.age = 17
# class работает по принципу словаря:
# - если чего то нет - добавить
# - если это уже есть - изменить
kate = Person()
kate.nam... |
b5ef98c5a2afa1ba5fa5dbe2b2e0e7432a0c4ee1 | BarbierJeremy/ProjetS3 | /SCRIPTS/Others/Methode_1/Parse_And_Filter_Sjcount.py | 2,154 | 3.5625 | 4 | #!/usr/bin/python3
# -*- coding: Utf-8 -*-
## For now, only keep + strand
def Analyze_Count(Count) :
#Open file
f = open(Count, "r")
Fini = False
#Dictionary to get Positions
Positions = {}
# Loop to iterate on each line
while not Fini :
line = f.readline()
if line == "" :
Fini = True
else :
... |
28cd1d7b988323094c27bcd71cffa4b369d21526 | LoopSun/PythonWay | /PythonLearn/Python Basic/HelloWorld.py | 402 | 3.6875 | 4 | #!/user/bin/python3
#^.^ coding=utf-8 ^.^#
def cute_split_line():
print("*"*20)
class hello_world():
def __init__(self, want_to_say = "Hello, World"):
self.want_to_say = want_to_say
def __str__(self):
return self.want_to_say
def say(self):
print("{0}.".format(self.want_to_say... |
25ae4dff28b7563438847248872138a24ccebfb5 | Luca2460/Imeneo-Leetcodes-Solutions-in-Python | /98. Validate Binary Search Tree.py | 776 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
printed = []
def inOrder(root):
... |
7d7079a1aa2c644574ed0d6f8428bf0f4a23b9f5 | 969452199/pythonproject | /day03/day03_class05.py | 174 | 3.515625 | 4 | i = 0
sum = 0
for i in range (0,100):
i = i+1
sum = sum + i
print(sum)
a = 0
sum1 = 0
for a in range (0,101):
if a%2 ==0:
sum1 = sum1 + a
print(sum1)
|
11014699b05e0df50b73a4c86647c90379d2e868 | m0rtal/GeekBrains | /Введение в высшую математику/дз3-2.py | 1,957 | 4.125 | 4 | """ 1. Задание (в программе)
Нарисуйте график функции: y(x) = k∙cos(x – a) + b для некоторых (2-3 различных)
значений параметров k, a, b
"""
from math import cos, sin
import matplotlib.pyplot as plt
import numpy as np
from random import randint
x = np.linspace(-np.pi, np.pi, 101)
for i in range(3):
k = randint(1,... |
848a5804c1fb296e305b0df67d901a1b8bce5769 | q-riku/Python3-basic2 | /04 面向对象编程-类/Cat.py | 900 | 4.34375 | 4 | """
类的创建语法:
class 类名:
《代码块》
备注:类名命名规则不能以数字开头,尽量以大写字母开头; 驼峰式命名法
helloworld HelloWorld
类的调用:变量名 = 类名([是否带参]) 叫对象;
对象能干么?
答:能够调用类中所有的属性和方法;
"""
class Cat:
def __init__(self, color, legs): #构造方法
self.color = color
self.legs = legs
felix = Cat("ginger", 4)
rover = Ca... |
00cb98d470ac8ed6cc90af4498f4927108a69722 | LucasKetelhut/cursoPython | /desafios/desafio036.py | 598 | 3.953125 | 4 | casa=float(input('Insira o valor da casa: R$'))
salario=float(input('Insira o salário do comprador: R$'))
anos=int(input('Em quantos anos ele irá pagar: '))
meses=anos * 12
gasto=casa/meses
if (gasto > (0.3 * salario)):
print('O gasto mensal será de R${:.2f} durante os próximos {} meses\nIsso é superior a 30% do ... |
78a522aa22f3da6cc938e708c06330d7ff5b3bc2 | deepatmg/toolkitten | /summer-of-code/week-01/love.py | 1,114 | 3.953125 | 4 | # #love affair
# name = "Rebecca Fillier"
# result = ""
# print('result: ' + result)
# # print(name[1])
# # i = 1
# # print(name[1])
# # for i in range(0,15):
# # print(name[i])
# # print(len("Rebecca Fillier"))
# for i in range(0, len(name)):
# # print(name[i])
# if i % 2 == 0:
# print(name[i])
# r... |
2175a11a9db96fc58f0567b1bb32e9afec9ded19 | browngirlangie/Unit-4-Lesson-4 | /Lesson 4/Problem 5/problem5.py | 311 | 3.875 | 4 | from turtle import *
kitkat = Turtle()
kitkat.color("green")
kitkat.pensize(12)
kitkat.speed(10)
kitkat.shape("turtle")
screen = Screen()
screen.bgcolor("yellow")
kitkat.forward(80)
kitkat.right(50)
kitkat.forward(200)
kitkat.left(150)
kitkat.forward(50)
kitkat.circle(25)
kitkat.backwards(300)
mainloop() |
5ee421fd43933f7ae179fdccdd4819156a67f9e3 | janarqb/Week2_Day4_Logic | /Task2.py | 247 | 4.125 | 4 | given_number = int(input("Please insert the number:"))
if given_number % 5 == 0 and given_number % 3 == 0:
print('HahaHoo')
elif given_number % 3 == 0:
print("Haha")
elif given_number % 5 == 0:
print("Hoo")
else:
print("Aaaaa") |
2670e9f33e5a6e57129b5286d289ddf68564057e | sunnysidesounds/InterviewQuestions | /amazon/longest_substring_wo_repeats.py | 1,117 | 4.21875 | 4 | """
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "012345"
Input: "pwwkew... |
44bb844f9b3e20ff6710808749eaf942aefe98af | faten20/Python-Programming-1 | /Week_12/TryExceptExample-1.py | 208 | 3.8125 | 4 | '''
divide by zero error using try and axcept
'''
try:
x=int(input('Enter first number'))
y=int(input('Enter second number'))
a=x/y
print(a)
except :
print ('divide by zero error')
|
a49a410103c0136ed3fe02f69e89b5c4e7aa6860 | juechen-zzz/LeetCode | /python/0017.Letter Combinations of a Phone Number.py | 899 | 4.0625 | 4 | '''
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf"... |
bb146e8cbb6f96eea4fdd8dee411ebefe1108d58 | github188/note-1 | /算法/merge3.py | 658 | 4.125 | 4 | #!/usr/bin/env python
def qsort3(alist, lower, upper):
print(alist)
if lower >= upper:
return
pivot = alist[lower]
left, right = lower + 1, upper
while left <= right:
while left <= right and alist[left] < pivot:
left += 1
while left <= right and alist[right] >= pivot:
right -= 1
if left > right:
... |
020abbf176f7a8c33ee8cb5c46897f356de34214 | Alapont/PythonConBetsy | /Gente/discoteca.py | 799 | 3.5 | 4 | # Discoteca unts unts
class Discoteca:
# Constructor por parametros
def __init__(self, nombre="club momentos",aforoMaximo=100):
self.nombre = nombre
self.aforoMaximo=aforoMaximo
self.dinero=0
self.colaEntrada=[]
self.genteDentro=[]
def añadirColaEntrar(self, persona... |
3afb658ff6b19fc1d4e17575b5a881fc94c34b3f | immzz/leetcode_solutions | /maximum product subarray.py | 511 | 3.5625 | 4 | class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
current_min = nums[0]
current_max = nums[0]
res = nums[0]
for num in nums[1:]:
current_max,current_min =... |
62d20720385771bc21718bc47c13fe20d1cb8f40 | PraveenMPKumar/ENG_Thesaurus | /Theasaurus_local.py | 1,436 | 3.890625 | 4 | import json
from difflib import get_close_matches
#Storing data from json file
data = json.load(open("data.json"))
closest_words = []
#Function to fetch the meaning
def get_meaning(word):
w = word.lower()
if w in data:
return data[w]
elif w.title() in data:
return data[w.title()]
eli... |
b22d07e4520da41da60a2ef93c606afbc743c2cf | ClodaghMurphy/dataRepresentation | /Week3/PY03readOurFile.py | 649 | 3.6875 | 4 | from bs4 import BeautifulSoup
with open("../Week2/carviewer2.html") as fp:
soup = BeautifulSoup(fp,'html.parser')#fp = file pointer
#print (soup.tr)
#above command is commented out but it finds the first instance of a tr
rows = soup.findAll("tr")#find all of the elements called tr
for row in rows:
#print("---... |
12ba0e1694347c069cbe7c0363e7f4899290ac50 | natty2012/Python4Bioinformatics2020 | /Notebooks/write_to_file.py | 1,125 | 3.6875 | 4 | def write2file(gene_list, out_file):
"""
Takes a gene list and writes the output to file
"""
with open(out_file, 'w') as outfile:
outfile.write('\n'.join(gene_list))
def remove_empty(gene_list):
"""
Given a gene list, removes items
that start with dash (empty)
"""
tag = True... |
8042d2a6917b1ab30dac6e46160bdb1070f8c9f7 | hopkeinst/Diplomado_Uniminuto_Python_2021 | /041_Listas_2/041_DosListas.py | 1,743 | 3.953125 | 4 | import os
import sys
sistema_operativo = sys.platform
if sistema_operativo.startswith('win'):
os.system("cls")
else:
os.system("clear")
print("LISTAS - TRABAJO CON 2 LISTAS")
print("Se van a trabajar 2 listas para guardar datos de productos y cantidades.")
print("\nVas a ingresar los productos a medida que se le s... |
9677ad4975192e4904d1ed15d32ac3b631eedfc8 | pukkapies/geninterp | /geninterp/factors.py | 13,406 | 3.96875 | 4 | __author__ = 'Kevin Webster'
import copy
def prime_factors(n):
"""
Factors n into primes
:param n: An integer
:return: A list of prime factors of n. If n = 1, return []
"""
assert n >= 1
if n == 1:
return []
else:
i = 2
factors = []
while i * i <= n:
... |
936a33418e02ae427e0b2aaecbb89069c2b6e7e1 | cramer4/Python-Class | /Chapter_11/homework_11_3.py | 391 | 3.859375 | 4 | class Employee:
def __init__(self, first, last, salary):
self.first_name = first
self.last_name = last
self.salary = salary
def raise_salary(self, money=""):
if money:
self.salary += money
else:
self.salary += 5000
print(self.sa... |
ba1164c174eeb0a25f119c217480d6753e71bf0a | EricSchles/phd_algorithms | /cuny_gc/chapter2/find_sum.py | 550 | 3.640625 | 4 | def binary_search(arr, value):
if len(arr) == 1 and arr[0] != value:
return False
if arr[0] == value:
return True
mid_point = len(arr)//2
if value < arr[mid_point]:
return binary_search(arr[:mid_point], value)
else:
return binary_search(arr[mid_point:], value)
def fi... |
ee1ee956a4ac929a80bcae9dde91aae39b79e371 | manuel-garcia-yuste/ICSR3U-4-02-Python | /Whileloop2.py | 482 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by: Manuel Garcia Yuste
# Created on : October 2019
# This program do a while loop
def main():
# variables
answer = 1
counter = 1
# input
number = int(input("Enter a number to loop it and add its results: "))
# process & output
while counter <= number:
... |
17b943b3a445113135d3995d736d95b231bfed5f | arthurcorreiasantos/pi-web-full-stack | /01 - Coding Tank/01 - Exercícios/12 - Aula/3 - até 0.py | 198 | 3.890625 | 4 | lista = []
num = int(input('Digite um número inteiro: '))
while num != 0:
lista.append(num)
num = int(input('Digite outro número inteiro: '))
print('Você digitou', len(lista), 'números') |
cf241538ba1dd67e65a0586ed8d9b95b2699103d | IndraSigicharla/Python-Code | /Small_Code/sorting_algos/selection_sort.py | 254 | 3.640625 | 4 | a = [int(input()) for _ in range(10)]
def sorter(lst):
for i in range(len(lst)):
mn = i
for j in range(i+1, len(a)):
if lst[mn] > lst[j]:
mn = j
lst[i], lst[mn] = lst[mn], lst[i]
sorter(a)
print(a)
|
e494609dd7cf28d3203b8a68932acdca644d1250 | Howmuchadollarcost/INF1100 | /ball_table1.py | 700 | 3.625 | 4 | g = 9.81
v_0 = 5
n = 5
stop = 2*v_0/g #last
dt = stop/n #uniformally spaced interval
print("For loop:")
print("----------------------")
print("V0 : t")
for i in range(0,n+1):
t = i*dt
y = v_0*t - 0.5*g*t**2
print("....................")
print("%.2f : %.2f" %(t,y))
print("|------------... |
4e5c07813377bb71c3ed7b4afef1f58e0170940e | Nanutu/python-poczatek | /module_2/zad_58/homework/main.py | 868 | 3.796875 | 4 | # Zabezpiecz listę pozycji w zamówieniu i łączną wartość zamówienia przed utratą spójności.
#
# W tym celu:
#
# Zamień listę pozycji w zamówieniu na zmienną prywatną.
# Zamień również metodę obliczającą łączny koszt zamówienia na prywatną.
# Dodaj metodę publiczną umożliwiającą dodanie nowego produktu do za... |
bfb12b34b42e08e6ad746a4e1cfdd9a6792ca387 | Liveo123/base64Hack | /base64.py | 1,412 | 3.765625 | 4 | # Description: Convert base64 to ASCII based on the RFC 3528 scheme
# Author: Paul Livesey
# Usage: base64.py filename
import pdb
# Function to convert a single base64 character to it's
# numeric equivalent
def cnvtToAsc(letter):
for i in range(0, len(b64Table)-1):
if b64Table[i] == letter:
ret... |
b834c14861457187b272ca8b02bce828a0c51f03 | patdriscoll61/Practicals | /Practical01/Workshop02/taskThree.py | 368 | 4.125 | 4 | # Discount Calculator
DISCOUNT_PERCENT = .20 # .2 is 20%
def main():
full_price = float(input("Enter Full Price: "))
discounted_price = calculate_discount(full_price)
print("Discounted Price: ", discounted_price)
def calculate_discount(full_price):
discounted_price = full_price - full_price * DISCO... |
6e106e60b4350f1c6e97e97bf740d5d1492f19d1 | ahmetakcan/python_proj | /defloraiton.py | 116 | 3.765625 | 4 | x = 0
for i in range(0, 10):
x = x + i
print(x)
# i ve 1 ile ayrıca dene farkı gör
# 0,1,2,3,4,5,6,7,8,9 |
23da1fede8f5d21d16b0728bda41ca1e6250f80c | pimoroni/scroll-phat | /examples/count.py | 656 | 3.546875 | 4 | #!/usr/bin/env python
import sys
import time
import scrollphat
if(len(sys.argv) == 1):
print("""
Scroll pHAT - Count
Counts up to <number>
Usage: {} <number>
Number should be under 999.
""".format(sys.argv[0]))
sys.exit(-1)
val = int(sys.argv[1])
if(val > 999):
print("Number must be under 999 to... |
d0979f20e0940d7a2d5e7215d458ab8a3d1190a6 | Austin-Buchanan/MealGeneratorApp | /mealApp.py | 2,526 | 4.0625 | 4 | import random
print("Welcome to Austin's Meal App!")
mealList = []
done = False
# load data from mealData.txt to mealList
inFile = open('mealData.txt')
for line in inFile:
mealList.append(line.strip())
inFile.close()
def suggestMeal(mealList):
"This suggests a random meal in the meal list to the console."
... |
635067cd98830099abb2e1c7aa6d839e788794d9 | qaidjohar/PythonCourse | /23_sqlite/2_createTable.py | 927 | 3.9375 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
return conn
def create_table(conn, creat... |
f8719ddb784837a42ca37088b2ae87c5faa4df75 | ipeksargin/data-structures-algorithms | /arrays/convertAsci.py | 373 | 3.921875 | 4 | #Asci numaralarına gore harfleri buyukten kucuge siralar.
def sort_str(s):
s = list(s)
print(s)
arr = []
secondArr = []
for i in range(len(s)):
x = ord(s[i])
arr.append(x)
arr.sort()
#print(arr)
for k in range(len(arr)):
char = chr(arr[k])
secondArr.... |
eb62193d81298342a620c5a4019c6efbc1c55b72 | GeoffreyRe/python_exercices | /exercice_utilisation_objet_par_un_objet/utilisation_objet.py | 1,221 | 4.09375 | 4 | # Réalisation d'un petit exercice d'un objet de la classe "Rectangle" qui utilise un objet de la classe "Point".
#Création des deux classes
class Point(object):
"définition d'un point géométrique"
class Rectangle(object) :
"définition d'une classe de rectangle"
# instanciation de la classe Rectangle + attrib... |
531f016a5492c3e425f49862eab6ce7d9e3fe93d | fefa4ka/schema-library | /analog/current/Gain/__init__.py | 3,552 | 3.5 | 4 | from bem.abstract import Electrical, Network
from bem.analog.voltage import Divider
from bem.basic import Resistor
from bem.basic.transistor import Bipolar
from bem import Net, u, u_Ohm, u_V, u_A
class Base(Electrical(), Network(port='two')):
"""**Emitter-Follower** Common-Collector Amplifier
The circuit sho... |
f9fad04ebfa6d0709e481ff98b44b5028431aca2 | graalumj/CS362-HW4 | /Q2/test_average.py | 586 | 3.578125 | 4 | import unittest
import average
class test_average(unittest.TestCase):
# Test whole number average
def test_avg_whole(self):
self.assertEqual(average.avg([2,2,2,2]), 2)
# Test floating point average
def test_avg_floating(self):
self.assertEqual(average.avg([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 5.5)
... |
6c365caa2b276fdeff09dd5e1c9d11674e47ce3b | jefftoppings/wizard-scorekeeper | /play_in_console.py | 2,026 | 3.703125 | 4 | from player import *
from game import *
from hand import *
from calculate import *
if __name__ == '__main__':
print("*** Welcome to Wizard Scorekeeper! ***\n")
# obtain the number of players
valid_input = False
num_players = 0
while not valid_input:
num_players = int(input("How many player... |
3ee8bc93193fbbae19489913246bf3df9a1100a2 | gbvsilva/algorithm_toolbox | /week3_greedy_algorithms/3_car_fueling/myCar_fueling.py | 455 | 3.6875 | 4 | # python3
import sys
def compute_min_refills(distance, tank, stops):
# write your code here
min_refills = 0
last_stop = 0
stops.append(distance)
for i in range(len(stops)-1):
if stops[i] + tank < stops[i+1]:
return -1
if tank + last_stop < stops[i+1]:
min_refills += 1
last_stop = stops[i]
return m... |
1d1553e3a91c46c61410294da6e2e40c2a989f29 | satishr1999/slide-show-presentation | /main.py | 2,174 | 3.578125 | 4 | # Slide-Show Presentation
#importing cycle from itertools library
from itertools import cycle
#importing Tkinter library as tk
import tkinter as tk
#importing Image from PIL library
from PIL import Image
#importing ImageEnhance from PIL library
from PIL import ImageEnhance
#defining slides class
class slid... |
40877a380f403dcfb92b5359021b2b248cead2f0 | rafaelperazzo/programacao-web | /moodledata/vpl_data/148/usersdata/264/86629/submittedfiles/testes.py | 250 | 3.78125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
n= int(input('Digite o número de temos:'))
numerador=1
denominador=1
soma=0
i=1
while (i<=n):
if (i%2)==0:
soma= soma- (i)/(i*i)
else:
soma= soma+ (i)/(i*i)
print ('%.5f' %soma) |
54abdf15a0b388f1d0233681c5f5251968b0fe2f | dccdis/riga | /prototype.py | 1,086 | 3.71875 | 4 | #!/usr/bin/python
'''
Usage:
argv[1] = accounts file
argv[2] = max password length to iterate
'''
import sys
import string
from hashlib import md5
def passwdgenerator(maxlength):
validchars = string.printable[:94]
if (maxlength == 0):
yield tuple()
return
for x in validchars:
for ... |
a04d9779f9635ca9551eb6b3d9bb10e04398cc9c | EllaAurora/Learning1 | /Computer.py | 683 | 3.609375 | 4 | global ratel, rate5, rate15
rate1 = 5.57
rate5 = 11.75
rate15 = 28.49
function parcelCost(weight)
overWeight = "Too Heavy, parcel rates do not apply"
underWeight = "Send as package, not parcel"
if weight >= 20 then
theCost = overWeight
elseif weight >=15 then
theCost = str(rate5)
el... |
f777e02cdcb43748441b3d1213b0e8b78222101e | akashadr/Albanero-Hackweek | /Q37.py | 361 | 3.84375 | 4 | def Decimal_To_Binary(DN):
if(DN==0 or DN==1):
return DN
else:
BN=""
while(DN>0):
BN=str(DN%2)+BN
DN=DN//2
return int(BN)
if __name__=="__main__":
N = int(input())
L = list()
for i in range(N+1):
X=Decimal_To_Binary(i)
Y=str(X)... |
d0e2ffeb6c25c5c0b00536b6d28ad4839ab5fa9e | satishkhanna/feature_selection_project | /q04_select_from_model/build.py | 593 | 3.71875 | 4 | # Default imports
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
data = pd.read_csv('data/house_prices_multivariate.csv')
np.random.seed(9)
def select_from_model (df):
X, y = df.iloc[:,:-1], df.iloc[:,-1]
model ... |
8cf555f48ea97e4dda0df737cbeb389c11449274 | eddarmitage/enigma | /tests/mappings_test.py | 1,297 | 3.640625 | 4 | from string import ascii_uppercase
import codecs
from enigma.mappings import IDENTITY, ROT13, AsciiMapping
ROT13_OUTPUT = [codecs.encode(c, 'rot13') for c in ascii_uppercase]
def test_identity_mapping():
"""Ensure IDENTITY mapping maps every uppercase ASCII letter to itself"""
assert_mappings(IDENTITY, ascii_... |
8929fcded77d164176277d6073f4e6254d11b7f7 | at3103/Leetcode | /139_Word Break_mock_interview.py | 1,267 | 4.125 | 4 | """
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Re... |
c0798e79659109948a2535425b6a4a9dbb9e6b72 | Eslam-Mohamed78/python-data-structures-and-algorithms | /algorithms/sorting/bubble-sort.py | 555 | 4 | 4 | def bubble_sort(alist):
n = len(alist)
for i in range(n - 1 , 0 , -1):
for j in range(i):
if alist[j] > alist[j + 1]:
alist[j] , alist[j + 1] = alist[j + 1] , alist[j]
def smart_bubble_sort(alist):
n = len(alist)
for i in range(n - 1 , 0 , -1):
exchanges ... |
534f062b268e709dda52d2e5ed866eeca6565ae4 | EricMontague/Leetcode-Solutions | /easy/problem_1122_relative_sort_array.py | 3,208 | 3.859375 | 4 | """My solution to Problem 1122: Relative Sort Array."""
from heapq import heappush, heappop
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
heap = []
arr2_positions = {}
arr2_length = len(arr2)
for index, num in enumerate(arr2):
... |
c863419770af866136bd1b6e785871d9dc6af4ba | felipegt56/O_poder_da_Tataruga | /formatos_em_loop.py | 345 | 3.5 | 4 | speed(1)
shape("turtle")
#PENTAGONO
for count in range(5):
color('red')
forward(100)
left(72)
penup()
backward(200)
pendown()
#HEXAGONO
for count in range(6):
color('blue')
forward(100)
left(60)
penup()
backward(150)
pendown()
#CIRCULO
for count in range(360):
color('black')
forward... |
9820852ddc166f6601214eae40dd55568292bd48 | bsofcs/interviewPrep | /findOccurenceOfKeys.py | 834 | 3.578125 | 4 | def firstOccurence(arr,low,high,val,n):
if low>high:
return
mid=low+(high-low)//2
if (mid==0 or arr[mid-1]<val) and arr[mid]==val:
return mid
elif arr[mid]>val:
return firstOccurence(arr,low,mid-1,val,n)
else:
return firstOccurence(arr,mid+1,high,val,n)
def lastOccurence(arr,low,high,val,n):
if low>high:... |
411ff775b0b10a5d9f4855ec7febf9180da27611 | xiam220/UdemyCourses | /Python/StringMethods.py | 1,179 | 4.28125 | 4 | String Functions
greet = 'hellloooo'
print(len(greet))
#Output: 9
print(greet[0:len(greet)])
#Output: hellloooo
Formatted Strings
name = 'Johnny'
age = 55
print(f'Hi {name}. You are {age} years old.')
#Output: Hi Johnny. You are 55 years old.
"""
Alternative:
print('Hi ' + name + '. Y... |
0ee32d84074e515f81571ccdea79ddb2f2e7a40d | 16030IT028/Daily_coding_challenge | /InterviewBit/013_counting_Triangles.py | 1,007 | 3.5 | 4 | # https://www.interviewbit.com/problems/counting-triangles/
"""
You are given an array of N non-negative integers, A0, A1 ,…, AN-1.
Considering each array element Ai as the edge length of some line segment, count the number of triangles which you can form using these array values.
Notes:
You can use any value only on... |
0a5e1d9153b934f56dd65244f2a13c105ad63005 | jimbrunop/brunoperotti | /Exercicios-Python/DecisaoExercicio1.py | 577 | 4.0625 | 4 | #Faça um Programa que peça dois números e imprima o maior deles.
primeiro_numero = float(input("Informe o primeiro numero: "))
segundo_numero = float(input("Informe o segundo numero: "))
def valida_numero(primeiro_numero, segundo_numero):
if primeiro_numero < segundo_numero:
return print("o segundo numero... |
831158c2ad8e65d667ea07ca4cbfc5e96e5acbde | aniagut/ASD-2020 | /Zadania grafy/dwudzielnosc.py | 1,154 | 3.625 | 4 | #kolorujemy bfsem-jesli ktorys juz pokolorowany na inny niz powinien byc, to graf nie jest dwudzielny
class Queue:
def __init__(self):
self.head=0
self.tail=-1
self.size=0
self.q=[]
def enqueue(self,v):
self.q.append(v)
self.tail+=1
self.size+=... |
9fe4432f7ed0190b051d3e7d1d1b97b331b2b6d7 | basti-shi031/LeetCode_Python | /Ex9_PalindromeNumber.py | 769 | 3.640625 | 4 | import time
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# 时间 O(n)
# 空间 O(n)
x_str = str(x)
length = len(x_str)
middle_index = int(length / 2)
for index in range(0, middle_index):
if x... |
b171f3977de3a104220a8cd84339c810e6c5dc1b | mgbo/My_Exercise | /Дистанционная_подготовка/Программирование_на_python/8_функция_рекурсия/zadacha_C.py | 233 | 3.765625 | 4 |
'''
Принадлежит ли точка квадрату - 1
'''
x = float(input())
y = float(input())
def IsPointInSquare(x, y):
return -1 <= x <=1 and -1 <= y <=1
if IsPointInSquare(x, y):
print ('YES')
else:
print ("NO") |
632ccd7c28a1127700add8da88abe0abe169fb50 | pixlalchemy/lpthw | /lpthw/ex17.py | 1,494 | 4 | 4 | # imports argument variable from sys
from sys import argv
# imports exists from os.path
from os.path import exists
# Takes the arguments entered from the command line,
# and stores them in their own variables
script, from_file, to_file = argv
# Prints the string "Copying from %s to %s" and takes the values stored
# in ... |
4b2431d634a0505ecea4a9698003379fb2866496 | DuNG-bot/nguyenthedung-fundamental-C4EP35 | /Lesson2/homework/moreturtle.py | 551 | 4.03125 | 4 | # from turtle import*
# shape('turtle')
# color('red','red')
# left(120)
# for i in range (4):
# right(150)
# forward(80)
# left(60)
# forward(80)
# left(120)
# forward(80)
# left(60)
# forward(80)
# mainloop()
n = int(input('Enter the number of shapes: '))
from turtle import*
shape('... |
ebd06b52e2f9526e995645a961aca3315777cdc6 | LiquidityC/aoc | /2021/day_09/main.py | 1,394 | 3.609375 | 4 | from collections import defaultdict
import sys
def get_neighbors(point):
x, y = point
return {
(x+1,y),
(x-1,y),
(x,y+1),
(x,y-1)
}
def measure_basin(start, area):
checked = {start}
neighbors = get_neighbors(start)
size = 1
while len(neighbors) > 0:
... |
fde822f751958cc09d1c9f69432730d6b38ef47c | tushar-rishav/Algorithms | /Archive/Contests/Codechef/Contest/Others/Infiloop/zeroes.py | 248 | 3.578125 | 4 | #! /usr/bin/env python
def main():
t=input()
while t:
n_5=0
n=input()
for i in range(1,n+1):
j=i
while not (j%5):
j/=5
n_5+=i
print n_5
t-=1
if __name__=="__main__":
main()
|
2e1d1044b02a8d204ffc40192c400e6f392ad945 | frankieliu/problems | /leetcode/python/971/971.flip-binary-tree-to-match-preorder-traversal.py | 1,821 | 3.984375 | 4 | #
# @lc app=leetcode id=971 lang=python3
#
# [971] Flip Binary Tree To Match Preorder Traversal
#
# https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/description/
#
# algorithms
# Medium (41.88%)
# Total Accepted: 3.8K
# Total Submissions: 9K
# Testcase Example: '[1,2]\n[2,1]'
#
# Given a b... |
8a54a8c97f2721d3a6fb3bffa5846d5d3bb088ae | TetianaSob/Python-Projects | /ex-22.py | 358 | 3.6875 | 4 | answer = [num for num in range(1,101) if num % 12 == 0]
print(answer) # [12, 24, 36, 48, 60, 72, 84, 96]
# answer = [val for val in range(1,101) if val % 12 == 0]
# answer = [char for char in "amaizing" if char not in "aeiou"])
answer2 = [char for char in "amazing" if char not in ["a", "e", "i", "o", "u"]]
... |
6de127f4d187cd31341b4b0a47c63b6c08a31302 | Cjhome/python | /python-learn/进程和线程区别.py | 1,629 | 3.625 | 4 | """
进程 能够完成多任务 运行多个软件
线程 能够完成多任务 软件中运行多个窗口
同一进程间的不同线程可以共享全局变量
不同进程间不能共享全局变量
一个程序至少有一个主进程 一个主进程里至少有一个主线程
线程不能够独立运行,必须依赖于进程
线程和进程在使用上各有优缺点 线程执行开销小,但不利于资源的管理和保护;而进程正相反
"""
import os,threading,multiprocessing
from multiprocessing import Queue
"""
进程共享全局变量
需要传参
队列的使用
"""
n = 100
def test():
global n
n += 1
... |
aebc2c942ffd9864ec6e73eb5b9780904e85f76d | WillianVieira89/Python_Geek_University | /Script_Python/Estudos/Exercicios de fixação/Exercicios_Secao5/exercicio_10.py | 278 | 3.734375 | 4 | altura = float(input("Digite sua altura: "))
sexo = input("Digite seu sexo: ")
homem = (72.7 * altura) - 58
mulher = (62.1 * altura) - 44.7
if sexo == "masculino":
print(f"Seu peso ideal é: {homem:.2f} quilos")
else:
print(f"Seu peso ideal é: {mulher:.2f} quilos")
|
dfbce0ee1c23522c8e209183fab54142e6829f44 | seojpark91/HackerRank_dailycoding | /appendAndDelete.py | 623 | 3.5 | 4 | def appendAndDelete(s, t, k):
s_length = len(s)
t_length = len(t)
if s_length + t_length < k:
return "Yes"
same = 0
for letter_s, letter_t, in zip(s,t):
if letter_s == letter_t:
same +=1
else:
break
extra_s = s_length - same
extr... |
faf19f8aa672f9a58e9685bfb572ed5f6a32d2a5 | stollcri/UA-3460-560-P2 | /nltk/util_wordfreq.py | 626 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, nltk
def process_file(file_name):
dictionary = {}
dict_strg = open('/usr/share/dict/words', 'r').read()
dict_list = dict_strg.split()
for word in dict_list:
dictionary[word.lower()] = 1
dict_list = []
dict_strg =""
file_string = open(file_name, 'r').... |
194f33c2588803e3c10be65a707357343d8800a4 | stressisboucard/par-apr-2019-prework | /temperature.py | 1,065 | 3.65625 | 4 | import matplotlib.pyplot as plt
%matplotlib inline
temperatures_C = [33,66,65,0,59,60,62,64,70,76,80,69,80,83,68,79,61,53,50,49,53,48,45,39]
minimun = min(temperatures_C)
print("le minimun est de ",minimun)
maximum = max(temperatures_C)
print("le maximum est de",maximum)
somme = sum(temperatures_C)
mean = somme/len(t... |
0909ca80c69156bacf45723e6fcbdc3f62051beb | Victorkme/PythonProjects | /areEquallyStrong.py | 423 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 15:04:02 2019
@author: User1
"""
yourLeft = 10
yourRight = 15
friendsLeft = 10
friendsRight = 15
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
return (max(yourLeft,yourRight) == max(friendsLeft,friendsRight) and min(yourLeft,yourRight) == ... |
58f090743070729e37d95f4d8deb1340cef83313 | tonysulfaro/CSE-331 | /Lecture/Lecture06-Sorting/binary_search.py | 756 | 4.09375 | 4 | """Return True if target is found in indicated portion of a Python list.
The search only considers the portion from data[low] to data[high] inclusive.
"""
def recBinarySearch(data, target, low, high):
if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return Tr... |
3f6f9e15159d59f84f9cf9f938b65bd07bb9f13a | YusufVolkan/25.12.2020-globalaihub-hw-teslim | /just homework 25.12.2020.py | 1,844 | 4 | 4 | name=input("enter your name:")
surname=input("enter your surname:")
deneme=3
failed=0
while True:
if deneme==0:
print("please try again later..")
break
if name=="Yusuf" and surname=="Volkan":
print("Welcome {} {}".format(name,surname))
deneme-=1
bre... |
35dd6e5d1c13f3be929e8275e9522e34e76ae569 | acrius/path_to_mordor | /ptm/adventure_managment/spells/implementations/utils.py | 851 | 3.5 | 4 | '''
Module contains secondary functions for spells.
'''
from os import makedirs
from os.path import exists, join, isdir
def make_package(package_path: str):
'''
Create python package with package_path path.
:param package_path: path of new package
:type package_path: string
'''
if not ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.