blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
22e1556e651dbc2189aca730e65446ce7640c33b | leo-it/ejercicios-python-curso2020 | /ejercicios para entregar/ejerciciospyborrador.git/intro/hipoteca2.py | 621 | 3.515625 | 4 |
tasa = 0.05
saldo = 500000
pagoMensual = 2684.11 #mensual
totalPagado = 0.0
mes = 0
pagoExtra = 1000
while mes < 12:
saldo = saldo * (1+ tasa/12) - pagoMensual -pagoExtra
totalPagado = pagoMensual + totalPagado + pagoExtra
mes = mes + 1
print(f'Total Pagado: ${round(totalPagado, 2)} en ... |
4d02d9af5ebf1db8a65d3406df07c150c89d9c89 | leo-it/ejercicios-python-curso2020 | /ejercicios para entregar/ejerciciospyborrador.git/intro/vocales.py | 115 | 3.546875 | 4 | cadena = "Ejemplo con for"
for c in cadena:
f= cadena.split()
a= f[-1:]
print('caracter:', c, a) |
a443fdb4a4c5ccbd37ca65c518247ae35ce5ab4c | philthebeancounter/python | /holplanclass.py | 3,470 | 3.859375 | 4 | from datetime import date
from datetime import timedelta
from datetime import datetime
#def employee_entitlement_irreg_hours(result,company_entitlement):
#inputs
data=open('data.txt','a')
name_input = raw_input("name> ")
company_entitlement = input ("Annual entitlement >")
bh1 = date(2017,1,2)
bh2 = date(2017,4... |
8e0cca73aae903ff39b22bd14757374ca134b478 | marykamala/471 | /stringstask.py | 656 | 3.609375 | 4 | data="""
1.Forward indexing --->0 1 2 3 4 5 length
2.backward indexing(or)negative indexing
-1 -2 -3 -4 -5 -6 length of the string
a="good afternoon all"
"""
'''l=[1,22,36,25,663,265,145,2567,36]
output=[]
count=0
for i in l:
if len(str(i))==2:
output.append(i)
count+=1
avg=sum(output)/count
... |
bdeab6a046d4236f6dd006dd5c44bdcdf62bf029 | amigojapan/amigojapan.github.io | /8_basics_of_programming/fruits.py | 580 | 4.71875 | 5 | fruits=["banana","apple","peach","pear"] # create a list
print(fruits[0]) # print first element of list
print(fruits[3]) # print last element
print("now reprinting all fruits")
for fruit in fruits: # loops thru the fruits list and assigns each values to th>
print(fruit) # prints current "iteration" of the fruit
pri... |
a0c1a127f9d5ae377ea3d811f03e824b0d8ad0e3 | sshivashankar/Python | /aksing questions.py | 236 | 3.828125 | 4 | print("How old are you ?", end =' ')
age = input()
print("How tall are you?", end =' ')
height = input()
print("What do you like?", end=' ')
like = input()
print(f'you are {age} years old, {height} cm tall and you like {like} ') |
c087789647cad25fc983acd3bfceee19ab0a507f | Narfin/test_push | /controlFlows.py | 636 | 4.28125 | 4 | # if, elif, else
def pos_neg(n):
"""Prints whether int n is positive, negative, or zero."""
if n < 0:
print("Your number is Negative... But you already knew that.")
elif n > 0:
print("Your number is super positive! How nice.")
else:
print("Zero? Really? How boring.")
my_num =... |
0d479a7cb6765e8f6fcf1f15b9de0eb7debc1f62 | duttmf/Scripts | /table.py | 156 | 3.890625 | 4 | #!/usr/bin/#!/usr/bin/env python
for x in range(1,11):
for y in range(1,11):
z = x * y
print(z, end="\t")
print()
|
a5fedfaa712bd4bde62918f22991523f9275a913 | davaponte/ProjectEuler | /0-50/000036.py | 374 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 000036.py
#
def IsPalindrome(s):
for k in range(len(s) // 2):
if (s[k] != s[-k -1]):
return False
return True
Suma = 0
for n in range(1, 1000000):
b = str(bin(n))[2:]
if IsPalindrome(b) and IsPalindrome(str(n)):
Suma += n... |
71327ec9951aa23f76737bcdd4f37cf3affac324 | davaponte/ProjectEuler | /000104.py | 1,420 | 3.5 | 4 | # 000104.py
def Fib():
f0 = 1
yield f0
f1 = 1
yield f1
while True:
f0, f1 = f1, f1 + f0
yield f1
# def IsPandigital(s):
# l = list(s)
# l.sort()
# i = int(''.join(l))
# return 123456789 == i
def IsPandigital(s):
return set(s) == set('123456789')
# rt5 = 5**.5
... |
c3350f589f4411d1efcc4c4f8515a7f9aea850b1 | davaponte/ProjectEuler | /0-50/000035.py | 545 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 000035.py
#
import math
def IsPrime(n):
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
Count = 0
for n in range(2, 1000000):
s = str(n)
AllPrimes = True
for k in range(len(s)):
if n... |
ed8ffbbf78433477812990eed3adbc402a7c65ae | davaponte/ProjectEuler | /0-50/000037.py | 704 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 000037.py
#
import math
def IsPrime(n):
if (n == 1):
return False
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
Acum = 0
limit = 11 #Dice el problema que solo hay 11
n = 11 #2, 3, 5 y ... |
f003d77993b9579e51df889fa49f5c08a45572f4 | davaponte/ProjectEuler | /0-50/000041.py | 704 | 3.84375 | 4 | #!/usr/bin/env python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# untitled.py
#
import math
from itertools import permutations as p
def IsPrime(n):
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
Ans = 0
for k in range(9, 2, -1):
l = [(x + 1)... |
8320d0ff84c5e31926cf209eed93f4cf8d77cc9e | tsc9/SEclass | /Exceptions.py | 1,443 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 8 15:53:04 2019
@author: ttc
"""
# Case 1, an exception is caught
#%%
try:
items = ['a', 'b']
third = items[2]
print("This won't print")
except IndexError:
print("Index out of bound")
print("continuing")
# Case 2, a division by zero exception won't cau... |
a557323756f431312e585b84c9660d987bb5caeb | bell2lee/sw-proj-2-a | /fibonacci_임성원.py | 695 | 3.765625 | 4 | import time
#재귀함수를 이용한 방법
def fibo(num):
if num ==1 or num ==2:
return 1
else:
return fibo(num-1) + fibo(num-2)
#반복
def iterfibo(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
a,b = 1,1
for i in range(num-1):
a,b = b,a+b
... |
d7fa96cee55aa9517c3ab5d02e30dc72f57b7d3b | nicholan/pygame-space-invaders | /space-invaders/bullet.py | 1,608 | 3.90625 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, game):
"""Class for single bullet."""
super().__init__()
self.screen = game.screen
self.settings = game.settings
self.color = self.settings.bullet_color
self.speed =... |
24cecbe50a1744d99d40895ac146957a1c05f1ac | paulbible/tescas | /source/embedding_tools.py | 9,054 | 3.640625 | 4 | """
A tools file to collect some reusable embedding functions
"""
import numpy as np
from collections import defaultdict
import os
import nltk_tools
import string
import math
def load_embeddings(filename):
"""
This function loads the embedding from a file and returns 2 things
1) a word_map, this is a ... |
10a144c4b71e34c1bf3680ca0c59f56e3fca6cef | brandonchamba/APITesting | /list1.py | 796 | 3.859375 | 4 | import random
cave_numbers = range(0,20)
caves = []
for i in cave_numbers:
caves.append([]) #create empty list
unvisited_caves = range(0,20)
visited_caves =[0]
unvisited_caves.remove(0)
while unvisited_caves != []:
i = random.choice(visited_caves)
if len(caves[i] ) >=3 :
continue
next_cave = rand... |
4f7d8f04312ca464a475bf7aa297a0b99a3df646 | cmoroexpedia/leetcode | /longest-palindromic-substring/longest_palindromic_substring.py | 6,122 | 3.640625 | 4 | class Solution_Optimal(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
ans = ''
for i in range(len(s)):
palindrome = self.palinDrome(s,i,i)
if len(palindrome)>len(ans):
ans = palindrome
pal... |
e01f1e15a4adcc69049d8eab44c9270a7206c765 | cmoroexpedia/leetcode | /merge-sorted-array/merge_sorted_array.py | 2,894 | 3.890625 | 4 | import json
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
# make a copy of nums1
... |
62fe4bd668a1272480da30f00d68a084abdc87eb | cmoroexpedia/leetcode | /container-with-most-water/container_with_most_water.py | 2,617 | 3.6875 | 4 | import json
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_area = 0
iterations = 0
i = 0
j = len(height)-1
while i != j:
iterations +=1
print("---")
print... |
3648fa2de607161b668429c213516b9acae74047 | ojjang1/learnPython | /python_tutorial/input_3.py | 656 | 3.75 | 4 | ## 주로 형식이 동일한 글들에
## 데이터만 넣어서 완성본을 만들어 주는 경우.
## 매물 정보를 입력해 보자.
street = input("주소 입력 : ")
type = input("종류 입력 : ")
number_of_rooms = int(input("방 갯수 : "))
price = int(input("가격 : "))
print("####################")
print("# #")
print("# 부동산 매물 광고 #")
print("# #")
print("#############... |
4e667f24a2a46b0145b9bd41c72a44d451047a16 | ojjang1/learnPython | /python_tutorial/testtest.py | 227 | 3.75 | 4 | kg = int(input("물체의 무게를 입력하시오(킬로미터): "))
speed = int(input("물체의 속도를 입력하시오(미터/초): "))
print("물체는", 1/2 * kg * speed**2, "(줄)의 에너지를 가지고 있다.")
|
fc41935c4da6c703d5348afa6df59c0e2710b147 | JacobStephen9999/Bactracking-1 | /Palindrom.py | 1,048 | 3.609375 | 4 | #Time Complexity: O(N2^N) where N is number of elements in staring
# Space Complexity : O(N) where N is number of elemtns stored in stack
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
result = []
if len(s) == None:
... |
f1d2f6890064cad59bb7ba2d6809090228f964fb | taehyundev/Python_tutorial | /University_study/Example Problem/ex10.py | 391 | 3.609375 | 4 | import turtle
t = turtle.Turtle()
t.shape('classic')
n1 = int(turtle.textinput('입력창', '변1: '))
n2 = int(turtle.textinput('입력창', '변2: '))
n3 = int(turtle.textinput('입력창', '변3: '))
if (n3*n3) == (n2*n2) + (n1 * n1):
t.forward(n1*100)
t.left(90)
t.forward(n2*100)
t.home()
else:
t.write('... |
3583aa47742c4363eddff21bd06febf3a158a0dd | taehyundev/Python_tutorial | /Basic_Grammer/Chapter02/Py02_05.py | 149 | 3.890625 | 4 | for i in range(0, int(input("별찍기 : "))):
print('*' * (i+1))
# *의 갯수를 곱을 통해서 i+1만큼 추가
#Ex ) input = 3
#*
#**
#*** |
d9f5e5facae54a8b8902e84e422d613f02df5c43 | taehyundev/Python_tutorial | /University_study/Tkinter_example/drawing board_ex.py | 766 | 3.828125 | 4 | from tkinter import *
top = Tk()
top.title("Oval을 이용한 그림판")
penc = "blue"
def paint(event):
x1, y1 = (event.x - 1 ), (event.y -1)
x2, y2 = (event.x + 1), (event.y + 1)
cnvs.create_oval( x1, y1, x2,y2, outline=penc, fill=penc)
def redColor():
global penc
penc = "red"
def greenColor():
global ... |
b56ded4ed1205e9bb355a71f877ac4dcd4770105 | taehyundev/Python_tutorial | /University_study/Tkinter_example/checkbox.py | 798 | 3.78125 | 4 | from tkinter import *
top = Tk()
top.title("체크박스")
def result():
result = ""
if int(chk1c.get()):
result += "체크박스1 "
if int(chk2c.get()):
result += "체크박스2 "
if int(chk3c.get()):
result += "체크박스3 "
print(result)
lb1['text'] = result
chk1c = IntVar()
chk2c = IntVar()
chk... |
eb716fb202e7e9013195ac37bf5127bf6adfce1f | Fhern1954/Python_Challenge | /PyPoll/main.py | 2,929 | 3.703125 | 4 | #Dependencies
import os
import csv
#Path to collect data from Resources folder
poll_csv = os.path.join('Resources', 'election_data.csv')
votes = []
candidates = []
occurance = []
percentage =[]
#Read in the csv file
with open(poll_csv, 'r') as csvfile:
poll_txt = os.path.join('election_results.txt')
with ope... |
dfa356aafc4fb15874999bb4a6eea57e843a4561 | cjoshmartin/AI-algorthims | /utils/priority_queue.py | 864 | 3.609375 | 4 | class priority_queue:
def __init__(self, priority='cost'):
self.queue = []
self.__size = 0
self.priority = priority
def __sorting_agl(self, item):
return item[self.priority]
def __sort(self):
self.queue.sort(key=self.__sorting_agl)
def __change_size(self, beta)... |
34270e6d277d78a053003f18f590adba05ff1381 | cjoshmartin/AI-algorthims | /chapters/ch_5_adversarial_search/alpha_beta_pruning.py | 890 | 3.703125 | 4 | from utils.Node import infinity
from utils.Tree import tree_for_adv_search
def alpha_beta_pruning(tree):
v = max_value(tree, -infinity, infinity)
return v
def max_value(node, alpha, beta):
if node.is_leaf():
return node.value
v = - infinity
for child in node.children:
v = max(... |
9e2aa85e904ba240187c5f9d42dcee8ceaafe74f | maxlvl/techdegree-project-2 | /keyword.py | 3,288 | 4.1875 | 4 | from ciphers import Cipher
class Keyword(Cipher):
def __init__(self):
self.plaintext = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 '
def encrypt(self, text, cipher_pad):
"""
Accepts an alphanumerical string object (text) and an alphanumerical string object (cipher_pad)
as arguments... |
4e226e2ae7200501868beccac3f2696007515240 | AverPower/Algorithms_and_Structures | /3. Search Algorithms/Task F.py | 620 | 3.703125 | 4 | from math import log2
EPS = 0.000001
ITN = int(log2(1 / EPS) / log2(3 / 2))
def h(v_p, v_f, a, x):
return (((1 - a) ** 2 + x ** 2) ** (1/2)) / v_p + (((1 - x) ** 2 + a ** 2) ** (1 / 2)) / v_f
def ternary_search(left, right, v_p, v_f, a, bound):
for i in range(bound):
middle_1 = (2 * left + right) / ... |
6ed35a115920d3004b4a56bdd5ff8d456acbcda1 | EzequielArBr/Maratona_Python | /ovni.py | 291 | 3.953125 | 4 | T = int(input())
for t in range(T):
linha = input().split(" ")
somatoria = int(linha[0]) + int(linha[1])
if somatoria <= int(linha[2]):
print ('CABE!', end="" if t == T - 1 else "\n")
elif somatoria >= int(linha[2]):
print ('NAO CABE!', end="" if t == T - 1 else "\n") |
958951755773a03caf50a55792a43ad629f96bbb | Gabrielomn/DS-learning | /myscripts/poisson.py | 314 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 16:44:45 2019
@author: kyouma
"""
from scipy.stats import poisson
poisson.pmf(3, 2)
'''
a = 0
numeros = range(4)
for k in numeros:
a += poisson.pmf(k,2)
print (a)
mesma coisa que:
'''
poisson.cdf(3,2)
poisson.pmf(12,10)
|
ca6cf560968bc57444debbed3304730d690ba085 | Krishika28/PRO-102-109-classes- | /PRO-104/mean.py | 300 | 3.640625 | 4 | import csv
with open("data.csv", newline='') as f:
data = csv.reader(f)
list_data = list(data)
list_data.pop(0)
print(list_data)
total = 0
for h in range(len(list_data)):
height = list_data[h][1]
total = total+float(height)
mean = total/len(list_data)
print(mean) |
b1a7ab973f90b6073b8850c7af8af63b8426e86b | dblarons/Choose-Your-Own-Python | /classywestern.py | 6,470 | 3.921875 | 4 | from sys import exit
from random import randint
# sets up a class Game()
class Game(object):
# a special initialization method that sets up
# important variables.
def __init__(self, start):
# initializes the self.lols variable
self.lols = [
"You lost? My dog can even beat this... |
8871eacf5463a39ad605d03a21530b6e292b65cd | yusuf-korkmaz/Python | /4- Python'da Modüller/Palindrome.py | 2,163 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 1 11:03:20 2016
@author: yusufkorkmaz
Belirlenen string in polindrome olup olmadığını test eden
ve sonuç olarak True veya False dönen bir modül.
isPalindrome(string,recursive veya iterative) metodu yer almakta
Parametre olarak String ve 0 değeri girdiğinizde recurs... |
8a5a389ccfc60c530c48689d243e4a89ec6b39bd | gabe-le97/MovieData | /Le_G_movies.py | 12,251 | 4.125 | 4 | """
------------------------------------------
CSC 110 Final Programming Project
File: MovieData.py
Author: Gabe Le
Due: 11 December 2017
Note: This program will read a data file containing movies that were released between
2000 - 2009 and display information that the user requests.
The file has: Title, Genre,... |
7e292cd69073a217e99bced03ca43772036e96ef | Minashi/COP2510 | /Chapter 9/course_Information.py | 586 | 3.734375 | 4 | course_Room = {'CS101': 3004, 'CS102': 4501, 'CS103': 6755, 'NT110': 1244, 'CM241': 1411}
course_Instructor = {'CS101': 'Haynes', 'CS102': 'Alvarado', 'CS103': 'Rich', 'NT110': 'Burke', 'CM241': 'Lee'}
course_Meeting_Time = {'CS101': '8:00 AM', 'CS102': '9:00 AM', 'CS103': '10:00 AM', 'NT110': '11:00 AM', 'CM241': '1:0... |
e80688442c643ed05976d0b872cffb33b1c3c054 | Minashi/COP2510 | /Chapter 5/howMuchInsurance.py | 301 | 4.15625 | 4 | insurance_Factor = 0.80
def insurance_Calculator(cost):
insuranceCost = cost * insurance_Factor
return insuranceCost
print("What is the replacement cost of the building?")
replacementCost = float(input())
print("Minimum amount of insurance to buy:", insurance_Calculator(replacementCost))
|
f8b2407d166049316233a3285e2587fdfac40ed0 | Minashi/COP2510 | /Chapter 11/person_and_customer_classes.py | 1,036 | 3.984375 | 4 | class Person:
def __init__(self, name, address, telephone_number):
self.__name = name
self.__address = address
self.__telephone_number = telephone_number
class Customer(Person):
def __init__(self, name, address, telephone_number, customer_number, trueorfalse):
super().__init__(... |
6254eedd431ef73cc98e27c704ecc534443e0691 | Jackson026/AlgorithmQIUZHAO | /Week_03/跳跃游戏2.py | 896 | 3.734375 | 4 |
# 1.定义步数step=0,能达到的最远位置max_bound=0,和上一步到达的边界end=0。
# 2.遍历数组,遍历范围[0,n-1):
# A.所能达到的最远位置max_bound=max(max_bound,nums[i]+i),表示上一最远位置和当前索引i和索引i上的步数之和中的较大者。
# B.如果索引i到达了上一步的边界end,即i==end,则:
# b1.更新边界end,令end等于新的最远边界max_bound,即end=max_bound
# b2.令步数step加一
# 3.返回step
# **注意!**数组遍历范围为[0,n-1),因为当i==0时,step已... |
488814efa60cb7ab1632ed5a4b887fa663a17a55 | Jackson026/AlgorithmQIUZHAO | /Week_01/加1.py | 650 | 3.734375 | 4 | # 取巧的办法是转换成字符串然后变为int,最后再转换回去原来的形式,通用性不强,就不作为一种方法写在这里
# 按位运算,倒序,如果是9,就变为0,向前循环,不为9则直接加1;
# 如果为999这种特殊形式,则在循环结束后,列表头插入1 .insert(位置,数)
def plusOne(self, digits):
if not digits:
return digits + [1]
for i in range(len(digits) - 1, -1, -1):
if digits[i] == 9:
digits[i] = 0
else:
... |
f36130ddb51ef0090df848103242c2f6fb612ec4 | Christian-Gennari/PDFMergerApp | /PDFMerger.py | 863 | 3.578125 | 4 | import PyPDF2
import tkinter
from tkinter import filedialog as fd
# Hides Tkinter root window
tkinter.Tk().withdraw()
filename = fd.askopenfilenames(initialdir = "/",title = "Select files",filetypes = (("PDF files","*.pdf"),("all files","*.*"))) # show an "Open" dialog box and return the path to the selected file
fi... |
c62ea637c51372433a4a2fe56d4ede0f928c50ca | gbordyugov/playground | /coding/codility-and-leetcode/elevator_stops.py | 660 | 3.65625 | 4 | # Compute the number of elevator stops
def solution(A, B, M, X, Y):
"""
Computes the number of elevator stops
"""
N = len(A) # the number of people
i, cnt = 0, 0
while i < N:
# weight - the weight of people in the elevator
# j - the first person in the next batch
weight,... |
60b61b17fdab4fdd4c48a4df68709e713054e259 | gbordyugov/playground | /coding/codility-and-leetcode/password-generator.py | 780 | 3.609375 | 4 | # generate password given sets
import numpy as np
from random import randint
def password(n, sets):
passw = ''
num_sets = len(sets)
for i in range(n):
if i < num_sets:
set1 = sets[i]
k = set1[randint(0, len(set1)-1)]
else:
rand_set = sets[randint(0, len(s... |
bfdf1e91559715e3718fb29c8188fa3e0c5f8ff0 | gbordyugov/playground | /coding/codility-and-leetcode/complement.py | 215 | 3.546875 | 4 | # 476. Number Complement. Leetcode
def findComplement(num):
bin_n = "{0:b}".format(num)
flipped = [str(int(val) ^ 1) for val in bin_n]
return int(''.join(flipped), 2)
print findComplement(5) |
39b12a29534181b594461218ff8f01b78547ef47 | gbordyugov/playground | /coding/codility-and-leetcode/ladder.py | 464 | 3.78125 | 4 | # Codility. Ladder. Complexity is O(N) overall. 62%
def fibonacci(N):
if N < 1:
return 0
fib = [0] * (N + 1)
fib[1] = 1
for i in range(2, len(fib)):
fib[i] = fib[i-1] + fib[i-2]
return fib[N]
def ladder(A, B):
sequence = []
for i, v in enumerate(A):
sequence.append(fibonacci(v+1))
... |
6870fc5da3d257220da144151f62dbac32d942f4 | gbordyugov/playground | /coding/codility-and-leetcode/brackets.py | 768 | 3.71875 | 4 | # Codility. Brackets
def push(val, stack, size):
stack[size] = val
size += 1
return size
def pop(stack, size):
size -= 1
stack[size] = 0
return size
def brackets(S):
if not len(S):
return 1
size = 0
stack = [0] * len(S)
size = push(S[0], stack, size)
for i in range(... |
8f0de2450d01f3d842c08d8ac671340058a8e006 | gbordyugov/playground | /coding/interviewbit/divide-two-integers-bit-operations.py | 550 | 3.65625 | 4 | # Divide Integers
import math
def divide2(dividend, divisor):
positive = (dividend < 0) is (divisor < 0)
dividend, divisor = abs(dividend), abs(divisor)
res = 0
while dividend >= divisor:
temp, i = divisor, 1
while dividend >= temp:
dividend -= temp
res += i
... |
0dac4d9da7a731ea626a58de83ae95c115d19116 | raaedserag/Prefix-Calculator | /Prefix Calculator.py | 8,779 | 4.125 | 4 | # Define the stack structure // Edited==> add a reverse function
""""stack.items ---> list of elements <<<>>>
stack.size() ===> Return length <<<>>> stack.isEmpty ===> Return true/false
stack.push(item) ===> appending item <<<>>> stack.reverse() ... |
0c404764a7b2a2921d926824e0a89883b560ab49 | cajimon04/Primer-Proyecto | /comer_helado.py | 1,403 | 4.28125 | 4 |
apetece_helado_input = input("¿Te apetece un helado? ¿Si/No?: ").upper()
if apetece_helado_input == "SI":
apetece_helado = True
elif apetece_helado_input == "NO":
apetece_helado = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
apetece_helado = False
tienes_dinero_... |
fea183288a5ad0baaa43c8ecd3c2e79f4d2662e5 | cphadkule/python_basics | /next perfect square.py | 193 | 3.921875 | 4 | import math
def find_next_square(sq):
root = math.sqrt(sq)
if root - math.floor(root)==0:
x = root+1
square = x*x
return int(square)
else:
return -1 |
50c700b135835a6a85e06ea5f7427125e9c898dd | nOlegovich/QaLight-Python | /compar.py | 815 | 3.90625 | 4 | from random import randint
a = int(input("Максимальна довжина першого списка: "))
b = int(input("Максимальне значення першого списка: "))
c = int(input("Максимальна довжина другого списка: "))
d = int(input("Максимальне значення другого списка: "))
def comp (x,y,z,l):
firstList = []
for i in range(x):
... |
6ea955986248a391dc46420cbad39b0593372e43 | angieramirez1800/Paint | /paint.py | 5,994 | 3.890625 | 4 | # Código modificado
# David Damián Galán
# Angélica Sofía Ramírez Porras
from turtle import * # Importa la herramienta turtle
from freegames import vector # Importa la biblioteca freegames
from math import sqrt # Importa la funcion sqrt
from math import pi # Importa la constante pi
def line(start, end):
"""
... |
7c8aeadef60a4c9dfb4b53a5bc48fcaa302682b7 | milolou/pyscript | /printTable.py | 800 | 3.609375 | 4 | tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(table):
colWidth = [0] * len(table)
for x in range(0,len(table)):
lengthOfString = []
for y in range(0,len(table[x])):
... |
039b84d58b8410e1017b71395ac44082e19323ec | milolou/pyscript | /stripMethod.py | 1,756 | 4.65625 | 5 | # Strip function.
'''import re
print('You can strip some characters by strip method,\n
just put the characters you want to strip in the parenthese\n
followed function strip')
print('Please input the text you wanna strip.')
text = input()
print('Please use the strip function.')
def strip(string):
preWhiteSpace = ... |
80b7fad43e6a8b0089dfeaa44d3cd4c77be6d3b1 | milolou/pyscript | /PdfParanoia.py | 2,766 | 3.53125 | 4 | # PdfParanoia.py - Encrypt every PDF files in a folder and its subfolder,
# decrypt every PDF files in a folder and its subfolder.
import PyPDF2,os
from pathlib import Path
os.makedirs('encryptedPdfs',exist_ok=True)
# Encrypt every PDF files in a folder and its subfolder.
def encrypt(folder):
absPath = os.path.ab... |
83b51cf94b6d1dae08fa5fb16f7b307e7946b468 | shervin-h/mapsa_prebootcamp_django | /bmm_kmm.py | 189 | 3.578125 | 4 | n, m = map(int, input().strip().split())
def gcd(a, b):
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
print(gcd(n, m), lcm(n, m))
|
35faaec60b05bc09ad1fa7d1f8b78d9dc1448a36 | shervin-h/mapsa_prebootcamp_django | /birthday_party.py | 1,425 | 3.90625 | 4 | '''
یک مهمونی تولد داریم که داخل اون سه نفر خیلی گرسنه هستن ( hungry )
و دو نفر سیر سیر ( not_hungry ) ،
اخری هم اصلا معمولی نه گرسنه نه سیر ( ok )،
چطور صاحب مهمونی کیک رو به حالتی تقسیم کنه که هر شیش نفر به یک اندازه سیر بشوند
hungry = 4 * not_hungry
hungry = 2 * ok
ok = 2 * not_hungry
4 * not_hungry = 2 * ok... |
2289c1c9c94547bd0e81216fce8698b409a85024 | pangeon/PythonStart | /games/hangman/utils.py | 1,168 | 3.515625 | 4 | def print_with_word_decorator(word, decorator):
print("-----------------------------\n")
for sign in word:
print(sign, end=decorator)
print("\n\n-----------------------------")
def fill_breaks(list, sign):
print("not implemented yet")
def index_of_set(set, index):
try:
sorted_lis... |
621692393c7ffe8cdf34af52b114c714915a656d | pangeon/PythonStart | /games/poker/Card.py | 1,313 | 3.796875 | 4 | """
Class representing one card:
value, color and file with image
"""
class Card:
VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'As']
COLORS = ['♥', '♦', '♣', '♠']
def __init__(self, value, color):
"""Init card - value and color."""
self._value = value
... |
2bf9c01949fb9f70a90f7b00d3a1e7590627253d | pangeon/PythonStart | /apps/eng-meme/text_utils.py | 705 | 3.8125 | 4 | def read_file_in_lines(reading_file):
for line in reading_file.readlines():
print(line.strip())
def write_line_in_file(file_to_writing, new_line, encoding):
with open(file_to_writing, "a", encoding=encoding) as file_oject:
file_oject.write(new_line + "\n")
def fill_and_split_line(first_word,... |
4c15aefb6e7b4ffd117851b2387789c407c6fb78 | BenjiKCF/Codewars | /day151.py | 239 | 3.984375 | 4 | def square_sum(numbers):
if numbers:
return reduce(lambda x,y: x+y, map(lambda x: x**2, numbers))
else:
return 0
print square_sum([0, 3, 4, 5])#, 50)
def square_sum(numbers):
return sum(x**2 for x in numbers)
|
fa4d2431bf7ef725516144689ef544df694108af | BenjiKCF/Codewars | /day209.py | 611 | 3.828125 | 4 | def move_zeros(array):
n_array = []
z_array = []
for i in array:
if (i == 0 or i==0.):#and i != False:
if str(i) == str(False):
n_array.append(i)
else:
z_array.append(i)
else:
n_array.append(i)
return n_array + z_array
... |
5ef6af9697f8e7806a579d17567b48bc0b635627 | BenjiKCF/Codewars | /day122.py | 397 | 4.03125 | 4 | def row_sum_odd_numbers(n):
total = sum([i for i in range(n+1)])
return sum([1 + 2 * i for i in range(total)][-n:])
print row_sum_odd_numbers(2)#, 8)
print row_sum_odd_numbers(3)
print row_sum_odd_numbers(4)
# 1
# 3 5
# 7 9 11
# 13 15 17 19
#21 23 25 ... |
bf219935cbf0a55ba517ca44e33b6e179f2ea352 | BenjiKCF/Codewars | /day52.py | 457 | 3.875 | 4 | costs = {'socks':5, 'shoes':60, 'sweater':30}
def getTotal(costs, items, tax):
items1 = [ch for ch in items if ch in costs]
return round(sum([costs[word] for word in items1])*(1+tax),2)
print getTotal(costs, ['socks', 'shoes'], 0.09)
print getTotal(costs, ['shirt', 'shoes'], 0.09)
#-> 5+60 = 65
#-> 65 + 0.09... |
3a9572bd678ccbb324d12d945f3d19f4ae64619b | BenjiKCF/Codewars | /day197.py | 403 | 4.15625 | 4 | def valid_parentheses(string):
new_bracket = []
for i in string:
if i.isalpha():
pass
else:
new_bracket.append(i)
new_bracket = ''.join(new_bracket)
while '()' in new_bracket:
new_bracket = new_bracket.replace('()', '')
return new_bracket==''
print v... |
cacd6d97d087ee0fcbaf0a79d4e1f7f0893a22fa | BenjiKCF/Codewars | /day87.py | 272 | 3.84375 | 4 | def disemvowel(string):
return ''.join([ '' if ch in 'AEIOUaeiou' else ch for ch in string])
print disemvowel("This website is for losers LOL!")
# "Ths wbst s fr lsrs LL!")
def disemvowel(s):
return s.translate(None, "aeiouAEIOU")
|
7a66baf7916bcdb97b2ca3bf15c571d87d2f1bbe | BenjiKCF/Codewars | /day185.py | 411 | 3.546875 | 4 | def sum_of_n(n):
ans = []
accum = 0
if n >= 0:
for i in range(n+1):
accum += i
ans.append(accum)
return ans
else:
for i in range(abs(n)+1):
accum += i
ans.append(-accum)
return ans
print sum_of_n(3)
print sum_of_n(-4)
def s... |
d90fc714468efd0c6837dd9d6ac936cc9cc82156 | BenjiKCF/Codewars | /day108.py | 140 | 3.5 | 4 | def find_next_square(sq):
return int((sq ** 0.5 + 1) ** 2) if (sq ** 0.5 + 1) ** 2 % 1 == 0 else -1
print find_next_square(121)#, 144,
|
975649cbd509d86c761b112b67023166cde1c0fa | BenjiKCF/Codewars | /day76.py | 361 | 3.78125 | 4 | def sequence_sum(begin_number, end_number, step):
if begin_number > end_number:
return 0
else:
i = (end_number - begin_number) / step
ans = 0
for j in range(i+1):
ans = ans + begin_number
begin_number += step
return ans
print sequence_sum(2, 6, 2)... |
dc2fbd1c6744b544b9a1d285db6bd9bd65c2ee09 | BenjiKCF/Codewars | /day8.py | 218 | 3.515625 | 4 | demo = ("22 33 56 2 1.4 67.4 34.5 49 11.2")
# Make it into a list
# split the space and add comma
# Make the string into a floating number
values = [float(i) for i in demo.split()]
print sum(float(i) for i in values)
|
54c854955aeb20cfc3fc8b0c4e35034b83af7bbc | BenjiKCF/Codewars | /day130.py | 278 | 3.6875 | 4 | def xor(a,b):
return bool(a) != bool(b)
print xor(False, False)#, False, "False xor False == False")
print xor(True, False)#, True, "True xor False == True")
print xor(False, True)#, True, "False xor True == True")
print xor(True, True)#, False, "True xor True == False")
|
cb136b8c30bdd6ceb960bbfc07a4b963f1913e91 | BenjiKCF/Codewars | /day189.py | 432 | 3.59375 | 4 | def digital_root(n):
n = n
while counter(n) != True:
n = summer(n)
return n
def counter(n):
if len(str(n)) != 1:
return False
else:
return True
def summer(n):
num_sum = 0
for i in str(n):
num_sum += int(i)
return num_sum
print digital_root(16)#, 7 )
... |
92620f3f63187c9820fe2ebecf8ec6bba4b7ad36 | JasonLeong81/Data_Science | /Flask/theory/decorators.py | 608 | 3.625 | 4 | def df(original):
def wrapper(*args,**kwargs): # args and kwargs is for any number of arguments and keyword argument
print('a',*args)
print('k', **kwargs)
return original(*args,**kwargs)
return wrapper
@df # same as saying display = df(display), which is also = wrapper
def display(x):
... |
8098828158d4bc3f6e3413e7b14a2c6d8f8a2512 | xiongfeihtp/scikit_learn | /naive_bayes/iris_classification_using_naive_bayes.py | 1,000 | 3.640625 | 4 | #! /usr/bin/env python
#coding=utf-8
# Authors: Hanxiaoyang <hanxiaoyang.ml@gmail.com>
# simple naive bayes classifier to classify iris dataset
# 代码功能:简易朴素贝叶斯分类器,直接取iris数据集,根据花的多种数据特征,判定是什么花
# 详细说明参见博客http://blog.csdn.net/han_xiaoyang/article/details/50629608
# 作者:寒小阳<hanxiaoyang.ml@gmail.com>
from sklearn import da... |
2a2e075d62539391532227c3e2db2d6c412dea25 | ken0823/scheduling | /TaskQueue.py | 2,725 | 3.625 | 4 | #! /usr/bin/python
# *-* encoding: utf-8 *-*
import heapq
import itertools
class TaskQueue:
REMOVED = '<removed-task>' # placeholder for a removed task
def __init__(self, name=""):
self.name = name
self.pq = [] # list of entries arranged in a heap
self.entry_finder = {} # mapping... |
615aac56dfb86888d3f017db271bea4a309387cf | mariiamatvienko/OOP | /classes/cart_window.py | 1,283 | 3.890625 | 4 | from tkinter import *
def to_delete():
res = txt.get()
cartList.remove(res)
lbl1.configure(text=cartList)
txt.delete(0, END)
def to_buy():
destroy_object = [lbl, lbl1, lbl2, lbl3, btn, btn2, txt]
for object_name in destroy_object:
if object_name.winfo_viewable():
object_... |
fea81f00604221bd490e564c045d58b0e6b2e554 | madilon/dojos | /phf.py | 799 | 3.90625 | 4 | nume1=input("Salut jucator 1, cum te numesti? ")
nume2=input("Salut jucator 2, cum te numesti? ")
i = "DA"
while i == "DA":
hpf1 = input(nume1+", alege: hartia, piatra sau foarfeca: ")
hpf2 = input(nume2+", alege: hartia, piatra sau foarfeca: ")
if hpf1 == hpf2:
print("Este egalitate!")
elif hpf1 == "piatra... |
7025bdf92b869bc69d624b93899cf1b5d72fb8ce | madilon/dojos | /mmm.py | 400 | 3.828125 | 4 | name = input("What is yur name ? ")
job = input("what job do you wanna aply for ? ")
time = input("How much time woud you take for obtaining this job ? ")
steps = input("what are the steps that you need to follow in order to get to get this job ? ")
first_Day = input("when would you like to start ? ")
print("Candidatul... |
e77d7ad02c2140c45463ccda2e62a3f03468e868 | azpm/django-scampi-cms | /libscampi/utils/string.py | 374 | 3.859375 | 4 | stopwords = '''
i
a
an
are
as
at
be
by
for
from
how
in
is
it
of
on
or
that
the
this
to
was
what
when
where
'''.split()
def strip_stopwords(sentence):
"""Removes stopwords - also normalizes whitespace"""
words = sentence.split()
sentence = []
for word in words:
if word.lower() not in stopwords:
... |
5da6c1c5288dd7fbd5249ab71a80f5f77b462fcb | colbyktang/Assignment9 | /battleship.py | 3,373 | 3.5625 | 4 | import random
# constants
HIT_MARKER = 'X'
MISS_MARKER = 'O'
INIT_MARKER = '#'
PLAYER_MARKER = 'P'
# board size
rowSize = 5
colSize = 5
# enemy ship start
isEnemyAlive = True
enemy_row = random.randint(0,rowSize - 1)
enemy_col = random.randint(0,colSize - 1)
# player ship start
isPlayerAlive = Tru... |
3e8798e7fc4fd6694233b9780ef454bff463bd34 | AdamSiekierski/podpowloki | /main.py | 983 | 3.5625 | 4 | import json
table = json.load(open('./periodic_table.json'))
mode = input('Wybierz tryb (liczba atomowa - 1, symbol - 2): ')
if (mode == '1'):
number = input('Podaj liczbę atomową: ')
for atom in table['elements']:
if (atom['number'] == int(number)):
foundAtom = atom
... |
39218e773ed24e5f2e41874e78765b1e1cd3668e | nephylum/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 809 | 3.828125 | 4 | def intersection(arrays):
hash ={}
# create a list to start checking for duplicate values
for x in arrays[0]:
hash[x] = 0
for x in range(1, len(arrays)):
for y in arrays[x]:
if y in hash:
hash[y] += 1
todrop = []
for item in hash:
i... |
bf1c783c532584c73e1fc01c97ca6ca7d3e5d958 | usmankhan-bit/APS-2020 | /kruskal_union_find.py | 1,083 | 3.59375 | 4 | graph=[]
union_array=[]
def initialize_union_array(N):
global union_array
for i in range(N):
union_array.append(i)
def union(u,v):
global union_array
value = union_array[v]
replace_value = union_array[u]
for i,ele in enumerate(union_array):
if ele == replace_value:
u... |
9fb4e71f024613a95e38d4ee4a5181dcf306e967 | usmankhan-bit/APS-2020 | /bitwise_check_even_odd.py | 97 | 3.765625 | 4 | n = int(input())
cond = n&1
if cond == 1:
print("Odd number")
else:
print("Even number")
|
9391b1f946e40799b19d6339dd5616b797e3a307 | Roman-Sergeichuk/python-project-lvl1 | /brain_games/cli.py | 729 | 3.5625 | 4 | import prompt
def greet():
print('Welcome to the Brain Games!')
def welcome_user(rules):
print(rules)
print()
name = prompt.string('May I have your name? ')
print('Hello, {}!'.format(name))
print()
return name
def request_answer(question):
print(f'Question: {question}')
user_an... |
874325d003ec7e630535b9c95e60fa60a5c04809 | abvita/web-caesar | /caesar.py | 527 | 3.859375 | 4 | def alphabet_position(letter):
lwr_let = letter.lower()
pos = ord(lwr_let) - 97
return pos
def rotate_character(char, rot):
if not char.isalpha():
return char
else:
rotated = chr(alphabet_position(char) + rot + 97)
if not rotated.isalpha():
rotated = chr(ord(rota... |
7933f2a8eea631c8519a2bbb722ba672203bd265 | smrsan/py3-practice-games | /guess/__init__.py | 895 | 3.921875 | 4 | from random import random
# Misc
from utils import clear_term
def guess_game():
resume = True
while resume:
clear_term()
hidden_num = int(random() * 100)
while True:
guess_num = input('Guess the hidden num [0-99]: ').strip()
if not guess_num.isnumeric():
... |
5bbc50d474f269db0d5b09b418ca5ba232d08e26 | smrsan/py3-practice-games | /rocks_papers_scissors/__init__.py | 1,106 | 4.09375 | 4 | from random import random
from utils import get_item_by_index, is_numeric, clear_term
def rps_game():
elements = {
'rock': 'scissor',
'paper': 'rock',
'scissor': 'paper'
}
while True:
clear_term()
pc_choice = get_item_by_index(elements, int(random() * 3))
pr... |
83d0dbb2a5025698e455eb39cd4f218bc8a9fb03 | jerryjerry1128/password_retry | /password_retry.py | 326 | 3.875 | 4 | password = 'a123456'
n = 3
while n > 0:
if input('請輸入密碼: ') == password:
print('登入成功')
break
else:
n-=1
print('密碼錯誤! ')
if n > 0:
print('還有',n,'次機會')
else:
print('沒機會了! 要鎖帳號了啦!')
|
d23e4d70647b5b43cc5b55ff4810d0eb932ed898 | Souravvk18/DSA-nd-ALGO | /Data Structures/element_of_linked_list.py | 156 | 3.921875 | 4 | # Print the Elements of a Linked List
def printLinkedList(head):
node = head
while node != None:
print(node.data)
node = node.next
|
25655f1e9c0e10ec72281b7982c1e0d10c2eef26 | Souravvk18/DSA-nd-ALGO | /Data Structures/print_the_element_linkedlist.py | 312 | 4 | 4 | # print the element of a linked list
def reversePrint(head):
if head is None:
return
else:
out = []
node = head
while node != None:
out.append(node.data)
node = node.next
print("\n".join(map(str, out[::-1])))
|
c541eb7254ed01492794dd75609d24ee897ea708 | NguyenTheAnhBK/Cryptography | /Monoalphabetic/Example2.py | 2,150 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# Mã hóa chuỗi ký tự bất kỳ sử dụng mật mã nhân (không mã hóa khoảng trống)
# Hàm tìm ước chung lớn nhất
def gcd(a, b):
while b > 0:
q = a // b
r = a - b*q
a, b = b, r
return a
# Hàm tìm nghịch đảo của k (k')
def module_inverse(k, n = 94): # với n bất kỳ
t1... |
104b485166ffcde6ab4e6785ab13d57cd5dd12fd | ggolish/GANs | /loader/img_utils.py | 1,897 | 3.671875 | 4 | #!/usr/bin/env python3
""" Module for image utilities. """
import numpy as np
import cv2
def crop(img: np.array, size):
""" Take a numpy array and crop it to size """
y, x, z = img.shape
cx = (x // 2) - (size // 2)
cy = (y // 2) - (size // 2)
return img[cy:cy+size, cx:cx+size, :]
def northwest(... |
57ad9f57bcb654294e3c049b2719224c6ebf7090 | catcatlin/Learn-Python3-the-Hard-Way | /ex13.py | 811 | 3.984375 | 4 | # print("\n")
# 测试1
# from sys import argv
# # read the WYSS section for how to run this
# script, first, second, third = argv
#
# print("The script is called:", script)
# print("Your first variable is:", first)
# print("Your second variavle is:", second)
# print("Your third variable is:", third)
# print("\n")
# 测试2
... |
37f5da993631372d27d2f5670f49663e8eaea566 | DMarchezini/UriOnlineJudge-Python | /Uri1038.py | 367 | 3.546875 | 4 | """Exemplo de Entrada Exemplo de Saída
3 2
Total: R$ 10.00
4 3
Total: R$ 6.00
2 3
Total: R$ 13.50
"""
info = input().split(' ')
cod, qtd = info
cod = int(cod)
qtd = int(qtd)
valores = [(1, 4), (2, 4.5), (3, 5), (4, 2), (5, 1.5)]
for valor in valores:
if valor[0] == cod:
total = valor[1] * qtd
prin... |
97b21f6149326fba8c267ba0dba2ab56ef23a51f | DMarchezini/UriOnlineJudge-Python | /Uri1015.py | 306 | 3.71875 | 4 | """
Exemplo de Entrada Exemplo de Saída
1.0 7.0
5.0 9.0
4.4721
-2.5 0.4
12.1 7.3
16.1484
2.5 -0.4
-12.2 7.0
16.4575
"""
import math
p1 = input().split(" ")
p2 = input().split(" ")
x1, y1 = p1
x2, y2 = p2
res = format(math.sqrt((float(x2) - float(x1))**2 + (float(y2) - float(y1))**2), '.4f')
print(res)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.