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 |
|---|---|---|---|---|---|---|
fcfe7333a63629913ea0c3cd56b447477182f188 | ides15/learn-python | /defaultdict.py | 744 | 3.796875 | 4 | from collections import defaultdict
dd = defaultdict(int) # int parameter is just the function int() which returns 0
words = str.split('red blue green red yellow blue red green green red')
for word in words:
dd[word] += 1
print(dd)
print(dd)
# above works because defaultdict will generate a key instead of t... |
8e389b4f34ffe1de88cd94f147001e2a2bf27762 | vsseixaso/atal | /lista-1/6.py | 2,194 | 3.671875 | 4 | # https://www.geeksforgeeks.org/traveling-salesman-problem-using-branch-and-bound-2/
import math
MAX_N = float('inf')
def copy_to_final(curr_path):
final_path[:N + 1] = curr_path[:]
final_path[N] = curr_path[0]
def first_min(adj, i):
min = MAX_N
for k in range(N):
if adj[i][k] < min and i != k:
min = adj[i... |
f486c40cb86fd4dce28ca2ab462b71104dfb1b9a | esix/competitive-programming | /e-olymp/~contest-9863/E/main.py | 77 | 3.546875 | 4 | from math import sqrt
a = int(input())
print (3 * a, a * a * sqrt(3) / 4) |
60effd6c7470cf511ddf65addba07459c7f19799 | artkra/stuff | /algos/incr_sub_seq.py | 361 | 3.703125 | 4 | def incsum(nums):
sumlist = nums[:]
for i in range(1,len(nums)):
for j in range(0,i):
if nums[j] < nums[i] and nums[i] + sumlist[j] > sumlist[i]:
sumlist[i] = nums[i] + sumlist[j]
print(sumlist)
return max(sumlist)
if __name__ == '__main__':
arr = [1, 101,... |
d5be6be0426c6e5e9852da9f2abf48827077b92d | dev-himanshu/TA__Internship_Assignment_Solution | /Question-2.py | 2,300 | 4.09375 | 4 | import re
def supermarket_shopping(budgets):
product_name = input("\nEnter product : ")
product_quantity = float(re.findall(r"[-+]?\d*\.\d+|\d+", input("Enter quantity : "))[0])
product_price = float(input("Enter price : "))
amount_left = 0
for values in shopping_list.values():
... |
8c4b99c9226b67d9eef862620087664a1ef78c73 | Priyankasgowda/90dayschallenge | /p71.py | 1,030 | 4 | 4 | # A recursive Python3 program to print maximum
# number of A's using following four keys
# A recursive function that returns
# the optimal length string for N keystrokes
def findoptimal(N):
# The optimal string length is
# N when N is smaller than
if N<=6:
return N
# ... |
882aaf1d82b6e26c2139b4ff0e8453cd4b1eba46 | 553672759/xxgit | /python/old/sort/bubble_sort.py | 256 | 4.125 | 4 | '''
Created on 2017-1-4
@author:
'''
def bubble_sort(lists):
count=len(lists)
for i in range(0,count):
for j in range(i+1,count):
if lists[i]>lists[j]:
lists[i],lists[j]=lists[j],lists[i]
return lists
|
309eb4aecb11478948d6ee6286213efb5f88c92f | RajDeliwala/PythonPractice | /WholefoodMarketAssesment.py | 907 | 3.84375 | 4 | #Assesment from WholeFoods Market that invloved dealing with queues which have values and prioritys
class PriorityQueue:
def __init__(self):
self.size = 0
self.q = []
def enqueue(self, value, priority):
if self.size >= 5:
self.q.sort()
if self.q[-1] < pri... |
446daa60cf9e5145dce7c145ec3be6053f0ade78 | Visorgood/CodeBasics | /Python/BubbleSort.py | 165 | 3.75 | 4 | def BubbleSort(A):
p = True
while p:
p = False
for i in range(1, len(A)):
if A[i - 1] > A[i]:
t = A[i - 1]
A[i - 1] = A[i]
A[i] = t
p = True |
dab6bd15e17b6c29651d359e8b5d223c2e162dc6 | kayodeomotoye/Code_Snippets | /timezones.py | 1,154 | 3.5 | 4 | import pytz
from datetime import datetime, tzinfo
MEETING_HOURS = range(6, 23) # meet from 6 - 22 max
TIMEZONES = set(pytz.all_timezones)
def within_schedule(utc, *timezones):
"""Receive a utc datetime and one or more timezones and check if
they are all within schedule (MEETING_HOURS)"""
try:
... |
695b7faa4a5c1128c2dcf4f07f148a78ea8f46b1 | heyker/LeetCodeCoding | /src/Contest/16B_1.py | 514 | 3.625 | 4 | #encoding=utf-8
'''
Created on 2016年12月22日
@author: heyker
'''
class Solution(object):
def constructRectangle(self, area):
"""
:type area: int
:rtype: List[int]
"""
if area<=0:
return [0,0]
import math
inter=int(math.sqrt(area))
for i in ra... |
112dc0431aefe42a952cef20822febbc4220bd0f | dtung011/dtung011 | /Fundamental/Session_3/mxn_ostars.py | 271 | 3.9375 | 4 | m = int(input("Enter number of colummns: "))
n = int(input("Enter number of rows: "))
# print ("*" * n)
for i in range (n):
for j in range (m):
if (i+j) % 2 == 0:
print ("*", end="")
else:
print ("o", end="")
print ("\n") |
2e412d24d1cff9ab36648c80f5ae6d8fd8aca43c | vatasescu-predi-andrei/lab7-Python | /lab 7 task 7.1 chal.py | 375 | 4.21875 | 4 | even=0
odd=0
print("Enter a series of integers, when you are done entering, enter '0'")
userInput=int(input("Please enter a series of integers:"))
while userInput!=0:
if userInput%2==0:
even=even+1
else:
odd=odd+1
userInput=int(input("Please enter a series of integers:"))
print("... |
9129c5ca239f03b2e96fa35b0718202cf2835c35 | JiHyeonMon/-pre-Algorithm | /bak-class1/day5/bak10886.py | 452 | 3.546875 | 4 | #10886
#준희는 자기가 팀에서 귀여움을 담당하고 있다고 생각한다. 하지만 연수가 볼 때 그 의견은 뭔가 좀 잘못된 것 같았다. 그렇기에 설문조사를 하여 준희가 귀여운지 아닌지 알아보기로 했다.
cnt = 0
for i in range(int(input())):
if int(input()) == 1:
cnt+=1
else:
cnt-=1
if cnt>0:
print("Junhee is cute!")
else:
print("Junhee is not cute!")
|
ee5e7d04569a6a72a3bb3d7f32c0d39d4943f02d | jainendrak/python-training | /Examples/9NetWorking,Multithreading,re/re/re3.py | 417 | 3.71875 | 4 | import re
text = 'abbaaabbbbaaaaab'
pattern='ab'
occur= len(re.findall(pattern , text))
e=0
while(occur>0):
match = re.search(pattern,text[e:] )
s = match.start()
e = match.end()
print("occurence at (%d--%d)"%(s+e,e+e))
occur-=1
"""
for m... |
6867d43c20c5b709d219921b8ecb40bbcd351d51 | soph714/6.00.1xFall2017 | /Midterm/midterm_5.py | 514 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 15 15:58:08 2017
@author: Ted
"""
def dict_invert(d):
'''
code by theosopher
10/15/2017
6.00.1x MITx edX midterm
d: dict
Returns an inverted dictionary according to the instructions above
'''
newD = {}
for key... |
9c726588d9174979efdb88e236a16af3e017198d | jamiebrynes7/advent-of-code-2017 | /day_3/challenge2.py | 1,952 | 3.828125 | 4 | import sys
import math
def main():
# Get input arguments.
try:
target_value = int(sys.argv[1])
except IndexError:
print("Usage: python challenge1.py <target_value>")
exit(1)
nodes = [Node(0, 0)]
nodes[0].value = 1
square_size = 1
while True:
... |
923e5714e5ad0c9fb3da55e4c8ff3e5a5a1ef338 | paukey/python_pra | /learn_4.5.py | 315 | 4 | 4 | #2017年7月15日
#元组tuple()不能修改,但是可以给存储元组的变量赋值 list[]支持修改
dimensions=(200,40)
for dimension in dimensions:
print('原始元组'+str(dimension))
print('\n')
dimensions=(100,100)
for dimension in dimensions:
print('重新赋值后'+str(dimension))
|
e30869245d2df582300dc65a40d735dc11cf80b7 | nayyanmujadiya/ML-Python-Handson | /src/ml/pca_data_visualization.py | 3,408 | 3.71875 | 4 | '''
Load Iris Dataset
The Iris dataset is one of datasets scikit-learn comes with that do not require the downloading of any file from some external website. The code below will load the iris dataset.
'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from ... |
2ef9752d84bbb0cb63ba346daef045407b502e6d | mrimj106/MriMJ | /check_path_exits.py | 211 | 3.640625 | 4 | #Program to check if path exists or not
import os
f1=os.path.exists("C:/Users/mritsing/Desktop/Python/test1/test3")
if f1==True:
print ("path exists")
else:
print ("path does not exists")
|
b3526d901669658727390ba18365b374a38d84b5 | Mateusmsouza/Rascrapdinha | /BS1.py | 1,473 | 4 | 4 | html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" cl... |
80252d9addcfa50b14ea7999bbb26b30b6afbdd5 | mai20-meet/meetyl1201819 | /lab6.py | 1,149 | 3.984375 | 4 | import turtle
from turtle import Turtle
from random import randint
class Square(Turtle):
def __init__(self, size, color):
Turtle.__init__(self)
self.shapesize= size
turtle.shape("square")
turtle.colormode(255)
# turtle.color(color)
'''
r = randint(0,255)
g = randint(0,255)
b = randint(0,255)
turtle... |
b59e3d6be4d3c9a9fd56aa98468bf138e1617392 | qw20140729/vip5 | /day3/Day3_Assignment.py | 3,210 | 4.25 | 4 | # 1、打印小猫爱吃鱼,小猫要喝水
class Cat(object):
def __init__(self,name):
self.name = name
def eat(self,food,water):
print("{0}爱吃{1}, {0}要喝{2}".format(self.name,food,water))
def main_ex1():
cat = Cat("小猫")
cat.eat('鱼','水')
"""
2、小明爱跑步,爱吃东西。
1)小明体重75.0公斤
2)每次跑步会减肥0.5公斤
3)每次吃东西体重会增加1公斤
4)小美的体重是45.0... |
c140cae71898811776201177f3394afcce683f02 | lhj0518/shingu | /11월3일 수업/yesterday.py | 490 | 3.625 | 4 | f=open("yesterday.txt",'r')
yesterday_lyric = ""
while 1:
line = f.readline()
if not line: break
yesterday_lyric=yesterday_lyric+line.strip()+"\n"
f.close()
n1_of_yesterday=yesterday_lyric.upper().count("YESTERDAY")
n2_of_yesterday=yesterday_lyric.count("Yesterday")
n3_of_yesterday=yesterday_lyric.count("ye... |
8e84ba212d23c8a5a4f3000afbb04eef1d0b2912 | jkirlans5282/Seymour | /algorithm.py | 3,175 | 4.0625 | 4 | #Algorithm Test
#nested dictionary, {username:{resturant:rating}}
users = {
"tom":{"a":1,"b":1,"c":0,"d":-1,"h":1,"f":1},
"beth":{"a":1,"d":-1,"e":1},
"mike":{"b":1,"e":1,"h":1},
"emma":{"d":1,"g":0,"e":1}
}
def addUser(username):
users[username]={}
def addRestaurant(restaurant,username):
while True:
... |
b85955254f4fa2cb76da8df4638e01e2d29936c9 | kevinelong/tyg | /pilot/lib/board.py | 566 | 3.5625 | 4 | class Board:
def __init__(self, width=9, height=9):
self.width = width
self.height = height
self.content = []
def add_item(self, item):
self.content.append(item)
def draw(self):
for y in range(0, self.height):
for x in range(0, self.width):
... |
99dbfb4fd94a3edc96418bb54237374cdba94061 | Sampreet/Competitive-Programming | /HackerRank/Domains/001 Algorithms/001 Warmup/E - Compare the Triplets [Score If Else]/compare-the-triplets.py | 387 | 3.875 | 4 | def compare_the_triplets(arr_a, arr_b):
n = len(arr_a)
a = sum([1 for i in range(n) if arr_a[i] > arr_b[i]])
b = sum([1 for i in range(n) if arr_a[i] < arr_b[i]])
print(str(a) + ' ' + str(b))
if __name__ == '__main__':
arr_a = list(map(int, input().rstrip().split()))
arr_b = list(map(int,... |
7a68d5f286c1b7608380418528fa93e8f557d08f | aparnapr121/python_practice | /mro.py | 390 | 3.546875 | 4 | class A():
def __init__(self):
print("inside A")
super().__init__()
class B(A):
def __init__(self):
print("inside B")
super().__init__()
class C():
def __init__(self):
print("inside C")
#super().__init__()
class D(B,C):
def __init__(self):
pr... |
6daee9e1c22c4113fffb60dbe92b1f7b736a379d | marinaoliveira96/python-exercises | /curso_em_video/0069.py | 615 | 3.78125 | 4 | maiores = masc = fem20 = 0
while True:
idade = int(input('Qual a sua idade? '))
if idade > 18:
maiores += 1
sexo = input("Qual é o seu sexo? [F/M] ").strip().lower()[0]
if sexo == 'm':
masc += 1
elif sexo == 'f':
if idade < 20:
fem20 += 1
c = ' '
while c n... |
48733fd50e000ea4b216ff6debcdf231747e5a0d | AnaBVA/pythonCCG_2021 | /scripts/ejemplos/read_fasta.py | 314 | 3.515625 | 4 | my_file = open("data/4_dna_sequences.txt", "r")
my_file_contents = my_file.read()
print(my_file_contents)
print(len(my_file_contents))
# Abir archivo
file = open("data/4_dna_sequences.txt", "r")
# Leer las lineas
for line in file:
print("Length: " + str(len(line)) + " " + line)
# Cerrar archivo
file.close()
|
9c82bfb41fe94c2992c435746e516b2647d6ed07 | chenzhiyuan0713/Leetcode | /Easy/Q48.py | 483 | 4.03125 | 4 | """
709. 转换成小写字母
实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。
示例 1:
输入: "Hello"
输出: "hello"
示例 2:
输入: "here"
输出: "here"
示例 3:
输入: "LOVELY"
输出: "lovely"
"""
class Solution:
def toLowerCase(self, str: str) -> str:
return str.lower()
answer = Solution()
print(answer.toLowerCase... |
3ccf0b4d342313ba0714bc6378c5c24ff71b27fe | marceloamaro/Python-Mombaca | /Lista Aula07 - Dicionários e Sets/02.py | 1,107 | 4.25 | 4 | """Escreva uma função que faça a verificação de existência de uma chave dentro de um dicionário. Caso a chave exista a função deve retornar o valor da chave, caso ela não exista, a função deve adicioná-la e retornar o dicionário."""
"""
def verificacao(d, chave):
if chave in d:
print(" Chave exist... |
82468988688a878e148712b1744ef607e1bfbff6 | AbhiniveshP/Competitive-Coding-4 | /PalindromeLL.py | 1,913 | 3.90625 | 4 | '''
Solution
1. Find the mid of the LL using slow and fast pointers.
2. Reverse the second part of the LL.
3. Check each value in each half of the LL in parallel and return False if not equal, else return True
Time Complexity: O(n) and Space Complexity: O(1)
--- Passed all testcases on Leetcode successfully
'''
... |
6dd515adb8689fb2079893bad3a0347cecd9daf4 | NearJiang/Python-route | /stopwatch/test seven.py | 485 | 3.53125 | 4 | import time as q
class stopwatch:
def start(self):
self.begin=q.localtime()
print('开始')
def stop(self):
self.end=q.localtime()
self._calc()
print('结束')
def _calc(self):
self.lasted=[]
self.prompt='共运行了'
for index in range(6):
... |
3ae3f69f13deff622499a9d28025cd8f50798106 | Tanakornguy/Tanakorn_Khuntamanee-CS01 | /CS01-Grading.py | 976 | 3.5625 | 4 | a = int ( input ( ' กรอกคะแนนเก็บ! *คะแนนเก็บไม่เกิน 30 คะแนน : ' ) )
b = int ( input ( ' กรอกคะแนนสอบกลางภาค! *คะแนนสอบกลางภาคไม่เกิน 30 คะแนน : ' ) )
c = int ( input ( ' กรอกคะแนนสอบปลายภาค! *คะแนนสอบปลายภาคไม่เกิน 40 คะแนน : ' ) )
d = a + b + c
if ( d >= 80 ) :
print ( ' ได้เกรด A ' )
elif ( d >= 75 ) :
pri... |
a592acca804a50637567eb968d3b9118de7dc4f2 | freylis/pyritms | /sort_utils/selection_sort.py | 1,158 | 3.953125 | 4 | """
Сортировка выбором
Бежим по массиву из N элементов N раз, запоминая позицию I
Бежим по массиву от позиции I до конца, запоминая минимальный встреченный элемент и его позицию K
Меняем местами элементы в позиции I и K
n^2
"""
from sort_utils import base
def sort(items):
for index in range(len(items)):... |
2fa31b41928f3ff212ae8e1c24ca63580ebb0880 | vsuriya93/Coding-Practice | /Hackerrank/Project Euler/1_multiplesOf3and5.py | 306 | 3.578125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n=raw_input()
n=int(n)
for i in range(0,n):
m=raw_input()
m=int(m)
output=0
k=3
a=(m-1)//3
b=(m-1)//5
common=(m-1)/15
output=(3*(a*(a+1))//2)+(5*(b*(b+1))//2)- (15*(common*(common+1))//2)
print output |
5711fb107c6b0136c85a27c6769767055d6e75c4 | overbe/alien_invasion | /data.py | 440 | 3.53125 | 4 | import json
class Storage:
"""A class to manage the data."""
def __init__(self):
self.file = 'db/data.json'
def get_score(self):
try:
with open(self.file) as f:
score = json.load(f)
except FileNotFoundError:
return 0
else:
... |
156638b071e4ae0e12e59da75da6c0733e85722d | nikita1610/100PythonProblems | /Problem89/Day89.py | 202 | 3.703125 | 4 | def check_binary_palindrome(n):
l=[]
while(n>0):
l.append(n%2)
n=n//2
b1="".join(map(str,l))
b2=b1[::-1]
return b1==b2
n=9
ans=check_binary_palindrome(n)
print(ans)
|
fc6b82ceef8a25ef923b62d18e46cb0b03e64166 | Aasthaengg/IBMdataset | /Python_codes/p02401/s270151385.py | 307 | 3.921875 | 4 | #coding:utf-8
def cal(a, b, op):
if op=="+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
return a//b
else:
return -1
while True:
buff = input().split()
a = int(buff[0])
b = int(buff[2])
op = buff[1]
if op == "?":
break
print(cal(a, b, op)) |
d35f55c3d17304bd24f14052553d79f524e7bf0e | vinsonlee/projecteuler | /14.py | 534 | 3.65625 | 4 | N = 1000000
# Cache of Collatz results.
C = {}
C[1] = 1
def collatz(x):
"""
Calculate the number of terms for the sequence starting with x.
"""
if x in C:
return C[x]
elif x % 2 == 0:
answer = 1 + collatz(x / 2)
else:
answer = 1 + collatz(3 * x + 1)
C[x] = answer
... |
d9ffde7cd3e857be7afde55d4e654c51a3d31acf | maurya-subhashini1/List | /maigic_sqour.py | 714 | 3.59375 | 4 |
maigic_square = [
[8, 3, 4],
[1, 5, 9],
[6, 7, 2]
]
i=0
sum=0
while i<len(maigic_square):
col=0
while col<len(maigic_square):
sum=sum+maigic_square[i][col]
col=col+1
j=0
s=0
while j<len(maigic_square):
col=0
while col<len(maigic_square):
s=s... |
69b7dec5566d40b2d62945c2c3477042d22de49f | ThomasHartmannDev/CursoPython | /Programas/01 - Fundamentos/01 - Tipos basicos/exemplo.py | 656 | 4.09375 | 4 |
# Verdadeiro, Falso, nulo
print(True)
print(False)
print(None)
# Tipos numericos
print(1 + 2) #Valor inteiro
print(1.2 + 1) # Valor Float
#Tipos de escrita.
print('Texto dentro de aspas simples')
print("Texto dentro de aspas duplas")
print("você é " + 3 * 'muito ' + 'legal')
#print(3 + '3') --> neste caso g... |
f9caf4f6b4655269d10315338cdc7fb86313c5b9 | riturajkush/Geeks-for-geeks-DSA-in-python | /Recursion/Power Of Numbers.py | 725 | 4 | 4 | #User function Template for python3
#Complete this function
def power(x,y):
#mod = 10**9+7
if(y == 0): return 1
temp = power(x, int(y / 2))
if (y % 2 == 0):
return ((temp%1000000007) * (temp%1000000007))%1000000007
else:
if(y > 0): return ((x%1000000007) * (te... |
738110b1165d168eaba9da1fb10da23ad870e30f | Upasana360/All-My-Python-Programs | /adv_min_max.py | 732 | 3.875 | 4 | # def func(item):
# return len(item)
# name=['maggie','souravu','sujata','abc','xc']
# print(max(name,key=func))
# #this can also be done by lambda func
# name1=['maggie','souravu','sujata','abc','xc','harshit vasihistha']
# print(max(name1,key=lambda item:len(item)))
# student=[{'names':'upasana','score':90,'age':... |
bac8cdc603195c5b17e6bf46fcd9811ed373507f | HadilOwda/Project2 | /cfp/final2 (copy).py | 4,236 | 3.8125 | 4 | #final project : space invaders by Hadil and Deema
#0-import the libraries which we need
import turtle
import os
import random
#1-set up the screen
wn = turtle.Screen()
wn.title('Space Invaders')
wn.setup(width=700 ,height=700)
wn.bgpic('space_invaders_background.gif')
wn.tracer(0)
#Register the shapes
turtle.register... |
fc4ce06356d48bfc7c463236583e9eb87a9bcfef | fingerroll/wip | /sort-transformed-array/s1.py | 331 | 3.5625 | 4 | # return sort results
# x^2 should be x*x or x**2
class Solution(object):
def sortTransformedArray(self, nums, a, b, c):
"""
:type nums: List[int]
:type a: int
:type b: int
:type c: int
:rtype: List[int]
"""
return sorted(map(lambda x: a* (x*x) + b*x +... |
6d29c26567939e69b424fa33696eed98e34fcf39 | ostrandr6399/CTI-110-1001 | /M4HW2_Pennies_Ostrander.py | 342 | 4.03125 | 4 | #Calculate amount a person earns if salary is one penny a day
#6/19/17
#CTI-110-M4HW4_7
#R.Ostrander
NofDays = int(input('How many days do you want to calculate for?' ))
for day in range (NofDays):
print ('day', day + 1)
pennies = 2**day
print ("This would be your Salary if you earned a penny ... |
a9769296aa7bbd95c1b2a4b960d9f3be7b093eef | DarkAlexWang/leetcode | /laioffer/insert_node_sorted_list.py | 463 | 3.921875 | 4 | class Solution:
def insert(self, head, value):
node = ListNode()
if head is None:
node.val = value
node.next = head
head = node
elif head.val >= value:
node.next = head
head = node
else:
cur = head
wh... |
2b7bafe48f08178a276526d412aad9b746b59dbc | MaksTresh/python-hw-course | /hw18/main.py | 960 | 3.765625 | 4 | import argparse
from PIL import Image
def resize_image(input_image: str, output_image: str, scale: float):
image = Image.open(input_image)
width, height = image.size
size = int(width * scale), int(height * scale)
resized_image = image.resize(size)
resized_image.save(output_image)
if __name__ ==... |
f5ba6e745291b470a4178ef6666a73b0e5577b1a | ZehuaWang/python_ladder | /python_ladder/python_ladder/BST/BinaryTree.py | 5,551 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 6 17:25:05 2020
@author: ewang
"""
class Stack(object):
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items... |
cae173457f536050c15faff7d02e4a61aeb67b14 | VladimirBa/python_starter_homework | /006_Functions 2/006_homework_1.py | 382 | 3.703125 | 4 | z = 0
print(z)
def greeting(z):
while z < 2:
print('Hello!')
z += 1
print(z)
greeting(z)
def out_f():
x = 1
def inn_f():
global x
print(x)
x = 2
print(x)
inn_f()
print(x)
def in_inn_f():
nonlocal x
x = 3
print(x)
... |
8085318e2af09eee96dfb9ff6cfe42a58c03ae0c | YusefQuinlan/PythonTutorial | /Intermediate/2.2 Tkinter/2.2.12_Tkinter_Lambda_Command.py | 3,209 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 18:10:54 2020
@author: Yusef Quinlan
"""
"""
The following demonstrates that using the button without passing an argument
to the function xreturn() an error is produced.
"""
from tkinter import *
Window =Tk()
Window.title("Lambdas")
Label1 = Label(Window,text="The... |
87fb68d880f6c4c05161b8a531de14274a971661 | rodhoda2020/PyCharm-Library | /REST APIs with Flask and Python/1. Full Python Refresher/32_custom_error_classes.py | 1,315 | 3.921875 | 4 | class TooManyPagesReadError(ValueError): # Inside the parameter is the parent class that we can inherit from
pass
class Book:
def __init__(self, name: str, page_count: int):
self.name = name
self.page_count = page_count
self.pages_read = 0
def __repr__(self):
return (
... |
90ddb7c77c93c5d35d5f53c39128d4eb30630f17 | Wesleysou/Exer-CRS- | /Programas/Aula-10/Aula 07 04/exer 2.py | 481 | 3.828125 | 4 | nomes=[]
nota=[]
resp='S'
while(resp=='s'or resp=='S'):
n=input('Digite o nome dos alunos')
parcial=float(input('Digite a nota da parcial'))
nome.append(n)
nota.append(parcial)
resp=(input('Digite s para continuar'))
acum=0
for i in range(len(nota)):
acum=acum+nota[i]
media=acum/len... |
8a11ee715aa143a95b245dcc0bce050a24fdaa05 | ace231/CS299_Labs | /lyP3.py | 1,373 | 3.671875 | 4 | # Alfredo Ceballos
# CS 299
# Project 3
# Problem 1 #
# Farenheit to Celsius formula : Tc = (Tf - 32) / 1.8
def faren_to_cels(f):
return (f - 32) / 1.8
f_temp = -459.67 # Just start off at absolute zero
while f_temp <= 200:
if f_temp == -459.67:
print("%7.2fF %7.2fC absolute zero" % (f_temp, faren... |
f573943c8878046121855d538f199cab790b0b35 | Parfen1984/pythonproject-Public | /Zadanie2.py | 202 | 3.875 | 4 | for i in range(1, 101, 1):
print (i)
if i % 3 == 0:
print(f" {i} Good")
elif i % 5 == 0:
print(f" {i} BETTER ")
if i % 3 ==0 and i % 5 == 0:
print(f" {i} Best ")
|
f188eccae4970a4a38aa79d9f316cb0979f153fa | HagenGaryP/lpthw | /ex12.py | 802 | 4.5 | 4 | # Exercise 12: Prompting People
# When you typed input() you were typing the "(" and ")" characters,
# which are parenthesis characters. This is similar to when you
# used them to do a format with extra variables, as in f"{x} {y}".
# For input you can also put in a prompt to show the user, so they
# know wh... |
f5e20133d54f0411ce970c0e99abfd68bd1dfcc7 | uannabi/DesignPatterns | /CreationalPatterns/abstractFactory.py | 1,136 | 4.3125 | 4 | class Owl:
"""one of the objects to be returned"""
def speak(self):
return "whooom!"
def __str__(self):
return "Owl"
class OwlFactory:
"""concrete factory"""
def get_pet(self):
"""return a owl object"""
return Owl()
def get_food(self):
"""return a ow... |
d756f9ef654ec60400b8538b19b97439a38d4eb7 | niklashauschel/minesweeper | /src/logic.py | 10,442 | 3.6875 | 4 | # !/usr/bin/python
"""
@ author : Till Fetzer
@ e-mail : till.fetzer@googlemail.com
@ date : 23.05.2019
"""
import random # stantard liberies
import numpy as np
from logging import *
filename = 'logic'
class Board():
"""
creating and working an the board
"""
def __init__(self, col... |
4535916ed1aaca9cf5134108991d872ce3a938f4 | Husayn17/Code-Lagos-Trials | /project-guessing.py | 1,364 | 3.9375 | 4 | import random
def compare_number(numbers, user_guess):
wrongright = [0,0] #wrong, then right
for i in range(len(numbers)):
if numbers[i] == user_guess[i]:
wrongright[1]+=1
else:
wrongright[0]+=1
return wrongright
if __name__=='__main__':
playings = T... |
3f3c65621a8c08e005a3efe10aeb16c43524a08a | amandathedev/Python-Fundamentals | /12_string_formatting/12_01_fstring.py | 1,791 | 4.34375 | 4 | '''
Using f-strings, print out the name, last name, and quote of each person in the given dictionary,
formatted like so:
"The inspiring quote" - Lastname, Firstname
'''
famous_quotes = [
{"full_name": "Isaac Asimov", "quote": "I do not fear computers. I fear lack of them."},
{"full_name": "Emo Philips", "quo... |
0e3629079a7462207d09e209cc7041df8e8be539 | jliversi/advent_of_code | /2021/python_version/d14/solution.py | 2,496 | 3.65625 | 4 | # INPUT_FILE = 'input.txt'
INPUT_FILE = 'test_input.txt'
def parse_input(file_name):
with open(file_name, 'r') as f:
start, rules = f.read().split('\n\n')
rules = {rule.split(' -> ')[0]: rule.split(' -> ')[1].strip() for rule in rules.split('\n')}
return start.strip(), rules
def part_one_s... |
bc576e57bcba7a8c18f437a5ffb8adfc7012d8bf | GutiEsteban/FundamentosDeProgramacionOrdenado | /ejercicio 4.py | 436 | 3.84375 | 4 | num1=int(input("ingrese el primer numero:"))
num2=int(input("ingrese el suegundo numero:"))
num3=int(input("ingrese el tercer numero:"))
num4=int(input("ingrese el cuarto numero:"))
sumadelos2primerosnumeros=num1+num2
productodel3y4=num3*num4
print("el resultado de los dos primeros numeros es :")
print(sumadelos2primer... |
dfa387d4cc1e04da47f5b3a40d4024a19c9f7f74 | dimtsap/UQpy | /src/UQpy/SampleMethods/MCMC/mcmc.py | 21,671 | 3.546875 | 4 | import numpy as np
from UQpy.Distributions import Distribution
class MCMC:
"""
Generate samples from arbitrary user-specified probability density function using Markov Chain Monte Carlo.
This is the parent class for all MCMC algorithms. This parent class only provides the framework for MCMC and cannot
... |
5ecee8c8ee06f6bb2e16ff1566a02c355783d44a | yiming1012/MyLeetCode | /LeetCode/动态规划法(dp)/322. Coin Change.py | 2,388 | 3.8125 | 4 | '''
You are given coins of different denominations and a total amount of money amount. Write a function to compute
the fewest number of coins that you need to make up that amount.
If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Out... |
255ff9b4c292216d37ae823cb095f335d68644b8 | QLGQ/learning-python | /map.py | 131 | 3.65625 | 4 | #output the square of 0,1,2,3...100 into a list
def square(n):
return n*n
L1 = range(101)
L2 = list(map(square, L1))
print(L2)
|
c8013fadd47b2207036b30f261d113a16370e244 | RafaelSanzio0/FACULDADE-PYTHON.1 | /AULAS ATT/AULA08-ATT/AT01-AULA08.py | 128 | 3.6875 | 4 | #ATIVIDADE DE LABORATÓRIO 01 - AULA 08
#EXIBIR OS 10 PRIMEIROS MULTIPLOS DE 30
x = 0
while x <= 30:
print(x)
x = x+3 |
b6ce95ba6b0a9a43d64fae5f0fb2d8d6673bdfa1 | FahimFBA/Python-Data-Structures-by-University-of-Michigan | /Dictionary/main.py | 276 | 3.90625 | 4 | # Many Counters with a Dictionary
# One common use of dictionaries is counting how often we "see" something
ccc = dict()
ccc['ccev'] = 1
ccc['cwen'] = 1
print(ccc)
# Output: {'ccev': 1, 'cwen': 1}
ccc['cwen'] = ccc['cwen'] + 1
print(ccc)
# Output : {'ccev': 1, 'cwen': 2} |
27ad56538c8ccaebd8eabc54b6e98588888b799f | alokaviraj/python-program-3 | /circle.py | 115 | 4.03125 | 4 | r=int(input("enter the radius of the circle"))
pie=3.14
area=pie*r*r
c=2*pie*r
print("area=",area)
print("cir=",c)
|
5d015a849beac9cf504cd4480f69f8f2755e616b | DevenMarrero/KTANE-Bot | /Password.py | 1,416 | 3.671875 | 4 | from Voice import speak
def password(text):
curr_password = []
crow1 = []
crow3 = []
txt = text.lower()
text = txt.split(' next ')
try:
row1 = text[0].split()
row3 = text[1].split()
except IndexError:
speak('Say Next in between rows')
return
for word ... |
cf020c231163feb33010b2de13fa8aad0c9cb32d | zhanglintc/leetcode | /Python/Trapping Rain Water.py | 1,391 | 3.796875 | 4 | # Trapping Rain Water
# for leetcode problems
# 2014.10.27 by zhanglin
# Problem Link:
# https://leetcode.com/problems/trapping-rain-water/
# Problem:
# Given n non-negative integers representing an elevation map where the width of each bar is 1,
# compute how much water it is able to trap after raining.
# For examp... |
c99d5459c4ba2dee61238efdec6a2e1d06ac20cd | Kaustav-Biswas/Practice | /Regex Substitution.py | 945 | 4.53125 | 5 | '''
The re.sub() tool (sub stands for substitution) evaluates a pattern and, for each valid match, it calls a method (or lambda).
The method is called for all matches and can be used to modify strings in different ways.
The re.sub() method returns the modified string as an output.
Task
You are given a text of lines.... |
a26f269bbf1b1661d44635e49e32033f7c4928ba | Malkeet786/Python | /Chapter4/03_listmethod.py | 205 | 3.53125 | 4 | l1=[1,7,8,21,4,15,6]
# print(l1)
# l1.sort() sort list
# l1.reverse() reverse list
#l1.append(45) #adds att end of List
l1.insert(2,100) # Insert 2 at index
l1.pop(4)#remove
l1.remove(15) #remove
print(l1) |
9a34a32b8720648ae0b66cc835b4c8aec13faeb2 | luohaha66/MyCode | /leet_code/python/#23_merge_k_lists.py | 2,262 | 3.6875 | 4 | """
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists: list) -> list:
if not lists:
return []
... |
12144c6aaed7acb04bd38928d7c6c6609b94e90d | wshis77/leetcode | /best-time-to-buy-and-sell-stock-ii.py | 912 | 3.546875 | 4 | class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
i = 0
size = len(prices)
buy = None
sell = None
result = 0
direction = []
while i < size:
if i+1 == size:
direction.append("DOWN")
else:
if prices[i] < prices[i+1]:
direction.append("... |
0c56780e1a4341e7f9b5b7f44e2f30db4de277e7 | Systemad/OOP-Python | /lists-dicts/list2.py | 703 | 3.8125 | 4 | ## Only print odd numbers
'''
tal = [3, 2, 8, 9, 7, 2]
odd = [num for num in tal if num % 2 == 1]
print(odd)
'''
productList = []
class kop:
product = ""
price = 0
productNumber = ""
amount = int(input("Hur många varor: "))
for i in range(amount):
prod = input("vilken product? ")
pric = int(i... |
dfcec46b826e32778b088e65e9b2ee61ac06a31c | JoseCardena365/practicas | /entrada.py | 177 | 3.609375 | 4 | #capturamos la entreda de teclado y la guardamos en una variable
esto_es_una_entrada = input("ingrese algo: ")
#imprimimos lo capturado por teclado
print(estos_es_una_entrada)
|
1c7c74551d97a5a8bf44fc425a7f1e69d621710a | HelenaJanda/pyladies-7 | /zaverecny-projekt/asteroids/v07_fly_out/spaceship.py | 1,666 | 3.5 | 4 | import pyglet
import math
# Degrees per second
ROTATION_SPEED = 200
ACCELERATION = 200
class Spaceship:
def __init__(self):
self.x = 0
self.y = 0
self.x_speed = 0
self.y_speed = 0
self.rotation = 0
image = pyglet.image.load("../assets/PNG/playerShip1_blue.png")
... |
88037302efb31cbd034dfcedba9bb888ba9bac06 | ps4417/algorithm | /Codeup/코드업 기초 100제/1088.py | 293 | 3.765625 | 4 | # 3의 배수는 통과?
# 1부터 입력한 정수까지 1씩 증가시켜 출력하는 프로그램을 작성하되,
# 3의 배수인 경우는 출력하지 않도록 만들어보자.
a = int(input())
for i in range(1,a+1):
if(i%3==0):
continue
else:
print(i,end=" ") |
c2f97fab7e4abd3cb196b87280ea93a0023115ab | Javty/Python_Learning | /Web_APIS/Loop_dic.py | 2,385 | 4.0625 | 4 | favorites = {'color': 'purple', 'number': 42, 'animal': 'turtle', 'language': 'python'}
dictionary = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
for key in dictionary:
print(key)
for key in dictionary.keys():
print(key)
for value in dictionary.values():
print(value)
for entry in dictionary.ite... |
c78f5ae78fbba039794e0159fba8eed302487c9a | DaveRiv/Euler_Project | /project_euler.py | 632 | 4.34375 | 4 | '''
1. List all the natural numbers from 0 to 10 that are mulitples of 3 and 5
2. List all natural numbers from 1 to 1000 that are mulitple of 3 and 5 and the return the sum
'''
def if_multiple(nat_number):
''' return True if it is a multiple of 3 or 5'''
if nat_number % 3 == 0 or nat_number % 5 == 0:
... |
f16c4b3141683628250a7f6245fb2f360437822f | kpessa/CodeSignal | /py/floorDivision.py | 491 | 3.578125 | 4 | def division1(x, y):
return x // y
def division2(x, y):
return int(x / y)
testInput = [
{
'x': 15,
'y': -4
},
{
'x': 17,
'y': 13
},
{
'x': 5,
'y': 10
},
{
'x': -10,
'y': -3
},
{
'x': -8,
'y': 2
... |
97219c62a5f57e378ca8217081f60499906471ac | hectorlopezmonroy/HackerRank | /Programming Languages/Python/Strings/What's Your Name?/Solution.py | 884 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# You are given the first name and last name of a person on two different lines.
# Your task is to read them and print the following:
#
# Hello firstname lastname! You just delved into python.
#
# Input Format
#
# The first line contains the first name, and the second line contains the last
#... |
6397379e6c67538607d5d6b9025980830877b539 | fatimaparada/Linear-Regression | /Linear_regression_nosklearn.py | 5,145 | 3.890625 | 4 | #Writing code that implements gradient descent to perform linear regression
#Yeswanth Bogireddy & Fatima Parada-Taboada
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import random
from sklearn.linear_model import LinearRegression
from sklearn.model_selec... |
fd7461e07c537977c05be0024432dfcbcc677c5d | JiaquanYe/LeetCodeSolution | /Tree/sword_SymmetryTree.py | 938 | 4.0625 | 4 | """
问题描述:判断二叉树是否为对称的二叉树,如果一棵二叉树和其镜像二叉树一样,那么它就是对称的
references : symmetrical Tree: https://blog.csdn.net/ustcer_93lk/article/details/80373736
mirror Tree: https://blog.csdn.net/ustcer_93lk/article/details/80373690
"""
class TreeNode():
def __init__(self, data=-1, left=None, right=None):
self.da... |
dabfaa57bb7de346012def3c984541909a571462 | devLorran/Python | /ex0075.py | 634 | 4.0625 | 4 | '''Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final mostra:
A) Quantas vezes apareceu o valor 9. Usar length()
B) Em que posição foi digitado o primeiro valor 3.
C) Quais foram os números pares.'''
par = 0
num = tuple(int(input('Digite um número: ').format(n+1))for n i... |
35e62eda0b812e1e06f5d40d13b538e63df188dd | abhaybd/AoC2020 | /day2/day2part2.py | 324 | 3.71875 | 4 | with open("input.txt") as f:
lines = f.readlines()
def is_valid(line: str):
positions, letter, password = line.split(" ", 3)
letter = letter[0]
p1, p2 = [int(x)-1 for x in positions.split("-")]
return (password[p1] == letter) ^ (password[p2] == letter)
print(sum([is_valid(line) for line in lines... |
615461843c643d53b05359368e62feac992c6ecc | arrimonhere/Python-Calculator | /Python Calculator With Function.py | 2,507 | 4.21875 | 4 | # Calculator With Function
# Code By Ar Rimon Ahmed
# Function For Addition
def Addition(x,y) :
return x+y
# Function For Substraction
def Substraction(x,y) :
return x-y
# Function For Multliplication
def Multliplication(x,y) :
return x*y
# Function For Division
def Division(x,y) :
... |
14b5eca6f4fd9fd68fcbb3842941a58c3c7b07bb | jsarraga/week1 | /Quiz_1/Quiz1_Solution/solution.py | 757 | 3.71875 | 4 | import json
# * Write a function ```readcurrency(filename)```
def readcurrency(filename):
# read the lines of a file
with open(filename, 'r') as file_object:
lines = file_object.readlines()
new_list = []
# Separate lines into two values
for line in lines:
new_dict = {}
... |
de46e0cae69ac24a678ca7b7404ab5eda3852bc4 | zacharybraxton-lpsr/class-samples | /dawgz.py | 196 | 3.734375 | 4 | print("How many dogs do you have")
puppie = raw_input()
puppie2 = int(puppie)
puppie2 = puppie2 + 4
puppie2 = puppie2 + 4
print("In two months, you will have " + str(puppie2) + " puppies")
|
5f6b409db562ff6ae2324ece1da712a66c7c5495 | amalija-ramljak/advent-of-code-2018 | /day25 - hot chocolate delivery/25.py | 1,002 | 3.625 | 4 | def get_manhattan(loc1, loc2):
return sum([abs(a-b) for a, b in zip(loc1, loc2)])
stars = []
while True:
line = input()
if line == "":
break
line = line.split(",")
for i, el in enumerate(line):
line[i] = int(el)
line = tuple(line)
stars.append(line)
constellations = dict(... |
1aa877893d8caefda91a1749b95cf381de2248ca | kyakusahmed/talent_show | /reception.py | 587 | 3.734375 | 4 | file = open('VIP.txt','r')
file1 = open('Ord.txt','r')
ORD = []
VIP = []
for line in file:
VIP.append(line)
for line in file1:
ORD.append(line)
def registration_checker(name,data):
result = "User Not Registered"
for fullname in data:
if fullname.casefold().find(name.casefold()) !... |
70ca90a56a5c87dbc3e8f2e7d427591f46c24c92 | untiwe/citrom_test | /usermanager/package.py | 642 | 3.78125 | 4 | import string
import secrets
import random
#пример из документации https://docs.python.org/3/library/secrets.html
def gen_new_password():
'''Функция возвращает пароль 6-10 символов'''
alphabet = string.ascii_letters + string.digits
while True:
range_password = random.randint(6, 10)
passwor... |
660545710fb4151683cc94aba57c55c31f043a41 | chixujohnny/Leetcode | /Leetcode2020/剑指offer/树/剑指 Offer 32 - I. 从上到下打印二叉树【树的BFS队列打印】[2刷].py | 1,254 | 3.875 | 4 | # coding: utf-8
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... |
f0600c53972831fd5c600166e66ef536596cdede | rushirg/LeetCode-Problems | /solutions/how-many-numbers-are-smaller-than-the-current-number.py | 873 | 3.75 | 4 | """
1365. How Many Numbers Are Smaller Than the Current Number
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/submissions/
"""
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
ans = []
for x in range(len(nums)):
coun... |
031ed345b1ac49b3d312ecaecb49aeaa53db5910 | luwinher/Python_Practice | /gPython/fifteen.py | 279 | 3.5 | 4 | #
"""Q15:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。"""
score = int(input("请输入该同学分数:"))
S = 'A' if (score>=90) else ('B' if (score>=60) else 'C')
print(S)
|
e21748123819863d928a1ed5363e8f8a1ee0ebce | carlitomm/python_prog_course | /practica9.py | 464 | 3.921875 | 4 | def dec2bin(number):
bin = ""
if number == 0:
return "0"
while number > 0:
bin = bin + (str(number%2))
number = int(number / 2)
return bin[::-1]
try:
number = int(input("ingrese el numero a convertir "))
print (dec2bin(number))
except:
print(".....ERROR...ingrese un ... |
423b768d5fb196bbcd77e5d7be41f90036639870 | Pobe16/python-labs | /strings_and_functions/returnvalues3.py | 1,543 | 4.1875 | 4 | # Modify the program so it check that the temperature value is numeric
# Temperature conversion program
def centigradeToFahrenheit(cent):
fahr = (9.0 / 5.0) * cent + 32
return fahr
def fahrenheitToCentigrade(fahr):
cent = (5.0 / 9.0) * (fahr - 32)
return cent
def isNumber(value):
try:
v... |
88dc8de7f934476fbf22635cdb0a7c15c3362f7d | yashu762001/Python-Tutorial | /DataType/Set.py | 504 | 4.15625 | 4 | animals = {"lion","lion","lion","tiger","giraffe","elephant"}
print(animals)
print(len(animals))
print(animals.__contains__("lion"))
# print(animals[2])
# Since there is a random distribution so we can't say that at this particular location this string is gonna come.
print(animals.add("peacock"))
print(animals)
animal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.