blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
357eb6a0e0fd7c060836bcbb72c650c6184bc17f | tomoki/project-euler | /34/main.py | 446 | 3.84375 | 4 | #!/usr/bin/env python
#coding:utf-8
import math
import string
import fractions
import random
def fact(n):
if n == 1 or n == 0:
return 1
else:
return n * fact(n-1)
def main():
ret = 0
for i in range(3,1000000):
s = str(i)
h = 0
for c in s:
h += fact... |
14e0d77e899a073b92603f5027f68125b87a8037 | luwenchun/Automated_Test | /py26_12day/07¶¯Ì¬ÊôÐÔµÄÉèÖÃ.py | 1,561 | 3.625 | 4 | """
============================
Author:柠檬班-木森
Time:2020/1/20 21:44
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
动态属性的设置:
内置函数setattr:设置属性
参数一:类名/对象
参数二:属性名
参数三:属性值
内置函数getattr:获取属性
参数一:类名/对象
参数二:属性名
内置函数delattr:删除属性
参数一:类名/对象
参数二:属性名
"""
class ... |
1618a47331aaea06250fcb0bc5d7f2378ae9049a | franklingu/leetcode-solutions | /questions/smallest-integer-divisible-by-k/Solution.py | 995 | 3.734375 | 4 | """
Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.
Return the length of n. If there is no such n, return -1.
Note: n may not fit in a 64-bit signed integer.
Example 1:
Input: k = 1
Output: 1
Explanation: The ... |
f65395422e57459810107f1a1d88d321b954047b | lvm0306/pythonDemo | /tell/Task1.py | 856 | 3.75 | 4 | #coding=utf-8
"""
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务1:
短信和通话记录中一共有多少电话号码?每个号码只统计一次。
输出信息:
"There are <count... |
f5c454ad802ffb15f4e84741b2191538fd075a53 | murillopeixoto/experiences | /python/scramble.py | 541 | 4.3125 | 4 | """
The function scramble receives 2 strings values. It returns True if a portion of str1 characters
can be rearranged to match str2.
"""
def scramble(s1, s2):
chars1 = chars_map(s1)
chars2 = chars_map(s2)
for char, count in chars2.items():
if char not in chars1 or count > chars1[char]:
... |
552c18b57ebb23e689c9307c986ea1b2bad01fdc | ylana-mogylova/Python | /Examples/palidrome.py | 480 | 4.34375 | 4 | # if word is palindrome
input_word = "waabbcbbaaw"
def palindrome(input_string):
revert_string = ""
index = len(input_string) - 1
while index >= 0:
revert_string += input_string[index]
index -= 1
if input_string == revert_string:
return True
else:
... |
c688d9676ec1d7ad1be91c622b05c28af8e1a550 | elenaborisova/Python-Advanced | /18. Exam Prep/taxi_express.py | 638 | 3.71875 | 4 | from collections import deque
customers = deque(list(map(int, input().split(", "))))
taxis = list(map(int, input().split(", ")))
total_time = 0
while customers and taxis:
curr_customer = customers[0]
curr_taxi = taxis[-1]
if curr_taxi >= curr_customer:
total_time += curr_customer
customer... |
13effb7ca9ac7121ae5c590556590800925b642a | cfuria/hackuciii | /graphthing2.py | 720 | 4 | 4 | num1 = 1
numC = 1
stepnumber = 0
stepmax = 0
stepplot = []
numbers = []
while (numC != 10000):
while (num1 != 1):
if (num1 % 2) == 0:
num1 = (num1 / 2)
stepnumber = stepnumber + 1
else:
num1 = (3 * num1) + 1
stepnumber = stepnumber + 1
if (stepnumber > stepmax):
stepmax = st... |
fa588f91972ece930b1a47ab7b58c9bfeb53462e | bushschool/AdvCS_RR | /bigO_selfCheck.py | 555 | 4.15625 | 4 | def badMin(array):
"""iterates and checks if every other entry in the list is less than the selected value i
"""
for i in range(len(array)):
min = array[i]
if sum([0 if min <= array[j] else 1 for j in range(len(array))]) == 0:
return min
def goodMin(array):
"""replaces store... |
7dd5998fe12d9411256e13c39c05d2c1e0a123a2 | fabiommendes/pytex | /pytex/src/rmath/old/complexity/globals.py | 618 | 3.5625 | 4 | '''
Functions that control the default complexity value
'''
GLOBAL_COMPLEXITY = 6
def read_complexity(value):
'''Return the global complexity if value is default or the given
complexity'''
if value is None:
return GLOBAL_COMPLEXITY
else:
return value
def get_global_complexity():
... |
3a848fc879e103ad49cac874b421bf6352995e08 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/project_euler/problem_010/sol1.py | 1,097 | 3.75 | 4 | """
Project Euler Problem 10: https://projecteuler.net/problem=10
Summation of primes
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
References:
- https://en.wikipedia.org/wiki/Prime_number
"""
from math import sqrt
def is_prime(n: int) -> bool:
""... |
090972543f88c75d13425113e0dc9897d7cd866f | luciaj283/sturdy-sniffle | /programmingassignment33.py | 1,277 | 4.21875 | 4 | # This is my programming assignment #3 - John Paul Lucia
score1 = 0
score2 = 0
score3 = 0
sumBoris = 0
avgBoris = 0.0
sumNatasha = 0.0
avgNatasha = 0.0
teamAvg = 0.0
# Print the *'s and introduction.....
print("************************************************************************")
print(" Welcome to ... |
df8e882a39ff30b893a94d53921beeb5c5dc0cec | Sergey-Laznenko/Stepik | /Generation Python - A Beginner's Course/2_input_print/2.4.arifmetica/8.py | 299 | 4.03125 | 4 | """
Напишите программу вычисления значения функции f(a,b) = 3(a + b)^3 + 275b^2 - 127a - 41
по введеным целым значениям a и b.
"""
a = int(input())
b = int(input())
c = (3 * ((a + b)**3)) + (275 * (b**2)) - (127 * a) - 41
print(c)
|
e8a504669702edb208093270cdd1cb927604add7 | edison7476/userdashboard | /app/controllers/Welcome.py | 5,460 | 3.984375 | 4 | """
Sample Controller File
A Controller should be in charge of responding to a request.
Load models to interact with the database and load views to render them to the client.
Create a controller using this template
"""
from system.core.controller import *
class Welcome(Controller):
def __init__(s... |
44f4bc62c6325988420d9322e31460e2e4c497d5 | TheAsianProphet/Codeforces-in-Python | /Football [Final].py | 386 | 3.578125 | 4 |
# coding: utf-8
# In[6]:
splt = input()
# In[8]:
beg = 0
end = 7
val = splt[beg:end]
for x in range(len(splt)):
if len(splt) < 7:
break
elif val == '1111111' or val == '0000000':
print('YES')
break
elif val != '1111111':
beg += 1
end += 1
val = splt[be... |
6133f4b27796789762b00753a19ba5c36ab3112a | RoshithR/Leetcode | /3sum_closest.py | 1,230 | 3.96875 | 4 | # Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target.
# Return the sum of the three integers. You may assume that each input would have exactly one solution.
# def threeSum(nums,target):
# nums.sort()
# diff = float('inf')
# for i in ... |
5358c22dc91f5e344764bcae8a319cb32ad45907 | freakraj/python_projects | /in_and_iterations_dict.py | 1,820 | 4.09375 | 4 |
user_info = {
'name' : 'raj gautam',
'age' : 24,
'fav_movie' : ['coco','kimi no na wa'],
'fav_tunes' : ['awakening','fairy tale'],
'mobile_no' : 9865784897
}
# # print(user_info)
# # Check if key exist in dictionary
# # if 'fav_tunes' in user_info : # in keyword sirf dict ki key check krega va... |
129d2a4942eab072c5f818ba3d8fac8f26852c0e | lamagdalena/100dni_kodowania | /dzien6_rock_paper_scissors.py | 997 | 4.1875 | 4 | import random
def one_game():
choices = ['ROCK', 'PAPER', 'SCISSORS']
game_number = 0
you_won = 0
i_won = 0
while game_number < 3:
your_choice = input('ROCK PAPER SCISSORS? (choose one):')
computers_choice = random.choice(choices)
print('I choose {}'.format(computers_choice)... |
ea94e97ae81c46d16d5b7fb99e9776dca336fe57 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/121 Best Time to Buy and Sell Stock II.py | 1,065 | 3.765625 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell
one share of the stock multiple times). However, you may not engage in multiple transactions at the same ti... |
47c838a4a8daa37045c2b560d0847acd9b1c0768 | allisoncoopersmith/IntroToPython | /simple_python_methods.py | 3,895 | 4.15625 | 4 | #prints a string
def printMe(printString):
print printString
return;
#compares two numbers
def compareMe (int1, int2):
if int1 > int2:
print("The first number is bigger than the second number")
elif int2 > int1:
print("The second number is bigger than the first number")
else:
... |
c1f20eb8dbfcb92d3faa08721a7f243a684b7368 | brunomendesdecarvalho/URI-Bruno-Mendes | /uri/u1002.py | 176 | 3.921875 | 4 | # coding: utf-8
# entrada e declaração do pi
pi = 3.14159
r = float(input())
# computação
area_circunferencia = pi*(r**2)
# saída
print('A=%.4f' % area_circunferencia) |
7c3c4974c5c61b749f8d82ce39f90acb6d41afb2 | RickyHal/book_project | /chapter13/delete_data_mysql.py | 991 | 3.5 | 4 | # delete_data_mysql.py
#!/usr/bin/env python3
import pymysql
# 连接数据库,地址:localhost,账号:root,密码:123,数据库:test
db = pymysql.connect('localhost', 'root', '123', 'test', charset='utf8')
# 创建一个游标对象
cursor = db.cursor()
SNO = '2016081111'
# 删除数据SQL语句
DELETE_SQL = '''
DELETE FROM STUDENT WHERE SNO='%s';
... |
3cf37533cf0a28a58c38220706ad47b2ad358991 | renzopachecoj/repoFundamentosProgramacion1T2016 | /ejercicios/GenWord.py | 575 | 3.6875 | 4 | #2007.Termino1.Evaluacion2.Tema1
import random
import numpy
n=int(input('Numero de letras: '))
m=int(input('Numero de palabras: '))
while not n>=2:
n=int(input('Letras en la palabra: '))
letras=0
lista=[]
palabra=''
npalabras=0
consonante='bcdfghjklmnpqrstvwxyz'
vocal='aeiou'
while not npalabras>=m:
#palabra... |
ace6dc4d232b3c9155cdd6d2f99838b9bd7b8d6f | yanhuangxiaoguang/offer-python | /剑指offer/合并两个排序的链表.py | 2,637 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
题目描述:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
背景知识:还是链表的知识,
解题思路(胡说):
方法一:两个链表A,B。分别创建一个指针p_head1, p_head2。并创建一个空链表m_head,根据p_head1, p_head2的值域中小
的值,生成新节点,插入m_head.next 移动小值的指针,然后循环比较,直到任意链表为空。然后将不为空的剩余节点插入到
m_head.next
方法二:递归版本
"""
'''链表值域打印函数'''
def print_node(head):
list_val ... |
87d0cc1a82682b054dbf013f255c414ddb568691 | Bigbadbear1988/epic_python | /Упражнение 4.2.py | 229 | 3.5625 | 4 | s = "У лукоморья 123 дуб зеленый 456"
print (s.find("я"))
print (s.count("у"))
if s.isalpha() == False:
print (s.upper())
if len(s) > 4:
print (s.lower())
b = s[:5] + "М" + s[6:]
print (b)
|
57446d1c0bca17f4650c4ee7b0013331c3d7ff47 | icpc/na-rocky-mountain-2018-public | /problems/qaly/submissions/accepted/qaly-zf.py | 144 | 3.53125 | 4 | #!/usr/bin/python3
qaly = 0
for x in range(int(input())):
a, b = map(float, input().split())
qaly += a*b
print("{0:.3f}".format(qaly))
|
0d6f91fc5c7355a35df2b9efcad8235ca37afeb7 | regoncalves88/python-name-us-states-game | /main.py | 1,235 | 3.71875 | 4 | from turtle import Screen, shape
from writer import Writer
from score import Score
import pandas as pd
background = "blank_states_img.gif"
states = pd.read_csv("50_states.csv")
guessed_states = []
missing_states = []
screen = Screen()
screen.title("Name US States Game")
screen.addshape(background)
shape(background)
... |
82f87c030a550e5039b899af7c5de11521f26b1c | cifpfbmoll/practica-2-python-AlbertoFBM | /p2e4.py | 341 | 3.875 | 4 | # PRÁCTICA 2 --> EJERCICIO 4
# Diagrama para calcular el mayor de dos números.
print("Pon dos numeros y te diré cuál es mayor.")
A= int(input("Pon el número A:"))
B= int(input("Pon el número B:"))
if A>B:
print(A,"es mayor que", B)
else:
print(A,"es menor que", B,"por lo que el número mayor es el núm... |
75b4e57e6db3f09ae2bc22010a99f061cc8266e9 | katipogluMustafa/PythonLangTraining | /04_TopicWise/02_Iterators/03_Infinite_Iterators.py | 1,168 | 4.53125 | 5 | # Infinite Iterators
# It is not necessary that the item in an iterator object has to exhaust.
# The built-in function iter() can be called with two arguments
# where the first argument must be a callable object (function) and second is the sentinel.
# The iterator calls this function until the returned value is equa... |
87b4d68bb9acac5156364e22014215d515aa6952 | saeyma/probdists | /probdists/Triangulardistribution.py | 7,035 | 4.15625 | 4 | import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
from collections import Counter
class Triangular(Distribution):
"""
Triangular distribution class for calculating and visualizing the
triangular distribution: a continuous probability distribution shaped
like a t... |
7fca7c987aa71737601572201468ca2fda6ccd59 | mybatete/Inventory | /inventoryLab.py | 1,238 | 3.953125 | 4 | '''
This module implements a Retail Inventory Class
This is for creating item objects
'''
class Inventory (object):
#Class Variable definition
DISCOUNT= 0.05
def __init__(self, name, price, quantity):
""" Initializes the instance variables"""
self.name = name
self.price = price
self.quantity = ... |
d65e32b49e463dea8b8170820305c3c076a36f33 | vitcmaestro/Linked-List-implementation | /singly_Linked_list.py | 2,795 | 3.734375 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class header:
def __init__(self):
self.head = None
class operations:
def insAtBeg(self,d):
temp = Node(d)
temp.next = h.head
h.head = temp
def insAtEnd(self,d):
temp = Node(d)
... |
d5ce9b74ffb97d3d976568d49a0fec495cab8ae1 | 224nth/leetcode | /apple/valid_parentheses.py | 514 | 3.734375 | 4 |
class Solution:
def isValid(self, s: str) -> bool:
if not s:
return True
stack = []
for c in s:
if c == ')' and stack and stack.pop() == '(':
continue
elif c == '}' and stack and stack.pop() == '{':
continue
... |
0864acc2c60fb8e6d2a6185f73017c7536db2b2b | priscila-rocha/Python | /Curso em video/ex003.py | 119 | 3.796875 | 4 | num1=int(input("Digite um numero"))
num2=int(input("Digite um numero"))
soma=(num1+num2)
print("A soma é ", soma)
|
c614340f25ef81cc23725123643cfc4bbdcd4421 | mohitsh/python_work | /ProbSolv/tic_toc.py | 1,409 | 3.703125 | 4 |
class TicTocToe:
def __init__(self):
self._board = [['']*3 for j in range(3)]
self._player = 'X'
def mark(self,i,j):
if not ( 0<=i<=2 and 0<=j<=2):
raise ValueError('invalid input')
if self._board[i][j] != '':
raise ValueError('place occupied')
if self.winner is not None:
raise ValueError('Game ... |
160d6301ef035323395997b3b674d93ee6b0b554 | airaider/python_algo_study | /12장_그래프/섬의 개수.py | 716 | 3.828125 | 4 | #https://leetcode.com/problems/number-of-islands/
#Nested function, DFS
def solution(grid):
def search(i,j):
if i>=len(grid) or i<0 or j>=len(grid[0]) or j<0 or grid[i][j]=='0':
return
grid[i][j]='0'
search(i, j+1)
search(i+1, j)
search(i-1, j)
search(i, ... |
05c5dd87c058c48323c37f8b12101084e29bd32d | wkwiatkowski/kurs-py | /old/loop_for.py | 550 | 3.984375 | 4 | #!/usr/bin/env python
for number in range(1, 11):
if number % 2 > 0:
print number
for number in range(1, 10):
if number == 5:
print "I have counted to %s" % number
break
for number in range(1, 10):
if number == 5:
print "I have counted to %s" % number
break
else:
print "I have counted fr... |
8374685136c98351592719b7290255b4cb66ab84 | ramonjunquera/GlobalEnvironment | /Python/standard/curso/05 Más tipos/03 funciones de diccionarios.py | 4,460 | 3.5 | 4 | #Autor: Ramón Junquera
#Fecha: 20230124
# Se pueden añadir elementos a un diccionario existente
cuadrados={1:1,2:4,3:9}
cuadrados[5]=25
print(cuadrados)
# Los valores de los elementos se sobreescriben de la misma manera
miDicc={1:1,2:2,3:3}
miDicc[2]="dos"
print(miDicc)
# Podemos saber si un diccionario tiene una cl... |
cad1774cbf197a43015f7088c2868df8128a68a2 | southpawgeek/perlweeklychallenge-club | /challenge-194/vamsi-meenavilli/python/ch-1.py | 1,697 | 3.984375 | 4 | import re
import unittest
"""
Week 194:
https://theweeklychallenge.org/blog/perl-weekly-challenge-194
Task 1: Digital Clock
Submitted by: Mohammad S Anwar
You are given time in the format hh:mm with one missing digit.
Write a script to find the highest digit between 0-9 that makes it valid ... |
f7238afa46b0e84be58ac1e3d829463e883f058f | jesusdmartinez/python-labs | /03_more_datatypes/1_strings/03_01_replace.py | 407 | 4.34375 | 4 | '''
Write a script that takes a string of words and a symbol from the user.
Replace all occurrences of the first letter with the symbol. For example:
String input: more python programming please
Symbol input: #
Result: #ore python progra##ing please
'''
string = str(input("please input a string"))
symbol = str(input... |
6d14f9f573ca118b4586446b1a641021a4070d3f | brandonhumphries/week-1-python-exercises | /string_exercises.py | 9,343 | 4.09375 | 4 | #Uppercase a string
string = "Given a string, print the string uppercased."
lower_case = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
upper_case = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "... |
44c03d80ef9c7dfd7aa9af3262b4685d7803cc14 | ZAKERR/-16-python- | /软件第三次作业/软件161/李盛2016021107/Confucius.py | 1,297 | 4.25 | 4 | '''
开发人: 李盛
开发时间:2018_09_23
程序功能:简单归纳孔夫子一生中各时间段的行为
'''
while True:
age = int(input("Please input Confucius's ages: "))
if 0 <= age < 15:
print("孔氏,名丘,字仲尼,公元前551年9月28日,春秋末期生人。")
continue
elif 15 <= age < 30:
print("孔子立志,从师而学,欲穷游而知世事。")
continue
elif 30 <= age < 40:
... |
c7e792d00df32320182fe4dc284169cffb78787a | kefo7771/Algorithms | /Assignment 4/hw4Huffman.py | 5,308 | 3.84375 | 4 | import math,collections
class huffNode():
#initialize nodes to be empty
def __init__(self):
self.left = None
self.right = None
self.character = ""
self.freq = 0
self.code = ""
#function maintains heap property of tree
def minHeapify(A,i):
l = 2*(i)
r = 2*(i) ... |
ab0fb706621e3cb5f39a92d8b7df5eab7bc615ea | Alena-Ryzhko/python_algorithms | /algorithms_2_num/sum_between_min_and_max_elements.py | 780 | 4.3125 | 4 | """
Find the sum of elements in an array
between the minimum and maximum elements.
The minimum and maximum elements themselves should not be included in the amount.
A function to find a Sum between min and max elements of an array:
"""
def sum_between_min_and_max(array):
maximum = array[0]
minimum = array[0]... |
89fb38865f5cbbb4bb8e2036f459715611ee265f | ferryleaf/GitPythonPrgms | /numbers/palindrome.py | 425 | 3.84375 | 4 | def Solution(element):
new_num=0
while(element!=0):
new_num=element%10 *10 + new_num
element=element/10
if(new_num==element):
print("Yes a Palindrome")
else:
print("Not a Palindrome")
if __name__=='__main__':
element = int(input().strip())
if(len(element)!=0):
... |
a2fc3404eaf680a11631f621dcc8f7b5772ce1fc | leonid-ed/lj-dl | /helpers.py | 168 | 3.609375 | 4 | """
"""
def confirm(question):
answer = ""
while answer not in ['y', 'n']:
answer = str(input("%s (y/n): " % question)).lower().strip()
return answer == 'y'
|
ea46dd8abf7863d444cd128f5fb26e734396bd56 | tianwei1992/Data_Strucure | /基本搜索算法/binary_search.py | 1,335 | 4.0625 | 4 | """
对有序列表,用二叉搜索可以提高效率
"""
def binarySearch(target,sorted_lst):
#mid=int(len(sorted_lst)/2)这里不要用长度来算mid,因为要保留index
#这里不用递归
left=0
right=len(sorted_lst)-1#开两个指针,分别指向第一个元素和最后一个元素
while left<=right:#有等号,等于的时候还需要比较,有交叉跨越才结束
mid = (left + right) //2#//表示整除
if target==sorted_lst[mid]:
return mid
if target>sor... |
03889d1c7f0509c776dafe17b707349e8f95a8d7 | Nickvs99/AmstelHaege | /code/algorithms/hill_climber_steps.py | 3,689 | 4.0625 | 4 | """
hill_climber_steps.py
This interpretation of hill climbing works on a generated solution.
Each house object will be moved in specific steps horizontally and vertically.
All the moves will be checked for validation and the best results stored.
This process will be iterated and stopped(saved) if the best area is fo... |
1cb9ce278f3c6b33d0e9b4cf2e99e2c324bd7dd9 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2513/61135/312382.py | 234 | 3.53125 | 4 | n=int(input())
num1=list()
for a in range(0,n):
mid=eval("["+input()+"]")
num1.append(list(int(i) for i in mid))
k=int(input())
num2=list()
for a in range(len(num1)):
num2.extend(num1[a])
num2=sorted(num2)
print(num2[k-1]) |
8cfa41a33187810ea4982487fa562cef5e4f73b1 | tommulvey/CSC15_python | /9_26/mulvey-t-3-1.py | 736 | 3.828125 | 4 | # File: mulvey-t-3-1
# Purpose : Calculates the total number of bitcoins a miner earn
# if they got 1,2,4, etc blocks per month
#
# Author : Tom Mulvey
#
# Date: 9/26/17
# Version : 0.0.1
def main():
print("Bitcoin Miner Program")
numOfMonths = int(input("How many months did you mine bitcoins ? "))
totalBlocks =... |
f13f15c4cf35bfa101eab05cf5ee0ad9e012aa3f | shaggyday/codes-from-school | /Random Sentence Generator.py | 3,123 | 3.890625 | 4 | import random
import sys
#1. Connection Data
def dictionary(corpus):
'''build a dictionary containing an entry for each unique word in the text'''
data = {}
# find every unique word in the text and create dictionary key and value
for item in corpus:
if item not in data:
data... |
36b4a675eed53426ba9767e2dc4ab96fef1241d8 | lucindaWMS/Interview_Preparation | /Python/Graph/Dijkstra.py | 1,720 | 3.9375 | 4 | # Dijkstra
import math
def dijkstra(graph, source):
if not graph:
return None
#All nodes in the graph
nodes = []
for i in range(len(graph)):
nodes.append(i)
#The node whose shortest path has been found will be put into this set
visited = []
#Put the source node into the visited set
if source in nodes:
v... |
b127716e6f412d7f40eb8f47320f64490afeb0bb | Mokarram-Mujtaba/Python-Practice | /exceptional handling.py | 1,041 | 4 | 4 | '''
code that might through errors
'''
# while(True):
# print("Press Q for quite")
# a=input("Enter the number")
# if a=="Q":
# break
# try:
# print("Trying...")
# a=int(a)
# if a>6:
# print("You have entered a larger number")
# except Exception as e:
# ... |
f2c934425c3b9fd5195c87e51e8f7ce201f6b1e3 | xiaomagh/environment-data | /assign1/test.py | 1,758 | 3.640625 | 4 | # This is a sample test program for assignment1
import utils
from netCDF4 import Dataset
import netcdf_utils
def check_lists_equal(list_1, list_2):
"""
Checks if two sequences contain same elements. Useful for
checking if a list is equal to a numpy array.
"""
if list_1 is None:
if list_2 ... |
d62ce58ff202c2e6dd93fb8cc556d43bf3f79db6 | fazlerabbitanjil/HackerRankCrackingTheCoding | /taleOftwostacks.py | 1,112 | 3.9375 | 4 | class MyQueue(object):
def __init__(self):
self.primary_stack = []
self.secondary_stack = []
def peek(self):
if len(self.secondary_stack) > 0:
return self.secondary_stack[-1]
else:
self.sync_stacks()
return self.secondary_stack[-1]
def po... |
21d472837a1eb08c1f91ae898f739ef9c323b9a7 | anklav24/Python-Education | /Timofei-Khirianov-2019/lesson_002/003_annotation.py | 320 | 3.765625 | 4 | # Аннотация типов Type Annotation и docstring
def add(x: "int, > 0", y: int) -> int:
""" Складывает x и y.
x - число или строка
y - число или строка"""
return x + y
# Функция f
print('add(1, 2) =', add(1, 2))
print(type(add(1, 2)))
print()
|
675ab06bd6f1512e00daa95ab82697de8d3a6f08 | m-m-adams/ChallengeServer | /Solutions/ChallengeClient.py | 3,125 | 3.5625 | 4 | import socket
import time
import select
###########################################################
# Class declarations
###########################################################
###########################################################
# Challenge Interface
# This class is a... |
7facca24960b297f6df0913bd7f9fe58bd5419f2 | boyzig/projet_proffessionnel | /pharmacie_package/produit.py | 3,907 | 3.84375 | 4 | """Module pour la gestion des produits"""
import sqlite3
class Produit():
def __init__(self):
"""Initialiseur des variables de la classe produit"""
self.nomprod=""
self.prix=0.0
self.prisencharge=""
self.types=""
def saisie_produit(self,datap=[]):
"""Fonction d... |
e879683c9ea475c47f254898c718aae4e49fd50f | SWLee1212/python-study | /python_basic/4_6_cal_mean.py | 1,083 | 3.640625 | 4 | # 이차원 리스트 처리하기
kor_score = [49,79,20,100,80]
math_score = [43,59,85,30,90]
eng_score = [49,79,48,60,100]
midterm_score = [kor_score, math_score, eng_score]
loopindex = 3;
sum = 0;
for i in range(0,3) : # for 문은 range를 지정해줘야 함 예를 들어 range(0,3)은 0,1,2 임
sum = sum+ midterm_score[i][0] ... |
95ea1b3159fde7545e8d6fd7379e042874e2e205 | B4rtko/Fraction-class | /Fraction.py | 12,381 | 3.84375 | 4 | # Bartosz Różycki
# nr indeksu: 255740
class Fraction:
"""Class describes objects that can be interpreted as an fraction and contains some of their properties"""
float_allowed = True
display = "improper" # ["improper", "mixed"]
def __init__(self, num, denom):
"""
:param num: if Fracti... |
db8c52eee8478e64ba75581cd9f8440e86c171a6 | everaldobass/curso-devaria | /Curso_04-Python3/aula01/selecao_ex_01.py | 250 | 4.0625 | 4 | # Devaria - aula 23 - Python - Aula 1 de linguagem de programação - parte 3
# Exercicio de Selecão
nota = int(input('Digite sua nota: '))
if nota >= 8:
print("Aprovado")
elif nota <= 5:
print('Reprovado')
else:
print('Recuperação') |
5b9595b36262f16774d4965d653b4376cccb8c6a | ParulProgrammingHub/assignment-1-Anuj1314 | /Program08.py | 185 | 4.09375 | 4 | base = input("enter the base of the triangle : ")
height = input("enter the height of the triangle : ")
area = 0.5 * base * height
print("the area of the triangle is {0}".format(area))
|
c13354934b758f43d9ba41bec8a94ecdd1d6b74d | kjuao9/coisas-de_python | /Python/2° Tri/Provas e Exemplos/nome_programa.py | 171 | 3.71875 | 4 | nome = input("Digite seu nome:")
print("Voce digitou ",nome)
ano = int(input("Digite ano que voce nasceu: "))
idade = 2018 - ano
print("Ola ",nome," sua idade é ",idade)
|
8008dcc943004345bf0aa434c11b3b154796f1f2 | Jay-Patil1/Codes | /Code With Harry/GUI Development/tut3 (Label, Geometry, Maxsize and Minsize).py | 389 | 3.671875 | 4 | '''
Author: Jay Patil
Date: 22 August 2020
Purpose: Learning Python
'''
from tkinter import *
imaginary_tech_root = Tk()
imaginary_tech_root.geometry("444x234") # Width x Height
imaginary_tech_root.minsize(200,100) # Width, Height
imaginary_tech_root.maxsize(795,845) # Width, Height
Jay = Label(text="Jay is a go... |
64e45ed5b28759c052da5525008788ec871abcd1 | taalaybolotbekov/chapter2.1-init | /task9/task9.py | 409 | 4.125 | 4 | def arithmetic(x,y,z):
if z == '+':
print(x+y)
elif z == '/':
print(x/y)
elif z == '-':
print(x-y)
elif z == '*':
print(x*y)
else:
print('Не буду делать')
x = int(input('введите первое числр: '))
y = int(input('введите второе число: '))
z = input('введите опер... |
6fc21858950a45abb827d7236151712ca6e71750 | mycode01/codingtests | /sumint.py | 211 | 3.65625 | 4 | def solution(a, b):
args = sorted([a,b])
answer = 0
for x in range(args[0],args[1]+1):
answer+=x
return answer
print(solution(3,5))
print(solution(3,3))
print(solution(5,3)) |
6d3ab468bb74d8aab1a4ac58de89b1461aaf33e4 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_201/73.py | 1,846 | 3.609375 | 4 | # criteria for choosing next stall:
#
# L_S, R_S are number of empty stalls on left and right of stall
# choose stall with maximal min(L_S, R_S)
# failing that, choose stall with maximal max(L_S, R_S)
# failing that, choose leftmost stall
#
# so what effect does that actually have?
# stall will be chosen at maximum of ... |
6ce14747bc765e78b2ac977b7b0ea13e40a8f2a5 | biswajitkundu93/wallBreak | /main.py | 9,083 | 3.609375 | 4 | import pygame
from pygame.locals import *
pygame.init()
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Breakout By Biswajit Kundu")
#define font
font = pygame.font.SysFont('Constantia',40)
#define color
background = (234, 218, 1... |
07de797b1a7b7ca2f803fdb5890ade6f4e5e4571 | Nihilnia/June1-June9 | /aa.py | 466 | 3.5625 | 4 | # import sqlite3, os
# connectToDB = sqlite3.connect("example.DB")
# cursor = connectToDB.cursor()
# cursor.execute("Create table if not exists fight (Name TEXT, Number INT)")
# cursor.commit()
# cursor.execute("Insert into fight ")
import os
a = 0
for x, y, z in os.walk(r"C:\Users\Nihil\Desk... |
d3631da47c4e18ea8d638d721265e1cf43914dd6 | tangzichengcc/python-study | /算法/leetcode/easy/14.最长公共前缀.py | 1,632 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Autor:tangzicheng
class Solution(object):
def longestCommonPrefix(self,strs):
"""
:type strs: List[str]
:rtype: str
"""
# 自己在做的时候没解决的问题
# 1.如何确定这里面最短的字符串
# 2.如何得到每个字符串的具体某个字符 从而进行比较
result = ""
i =... |
9e8b2a80dc19e77882a221ff414f23d8acd0152b | ajaysurya8888/TCS-DCA-Solutions | /Nth_smallest_in_lis.py | 345 | 3.859375 | 4 | def bubble_sort(l):
for i in range(len(l)-1):
for j in range(i+1,len(l)):
if l[i] > l[j]:
temp = l[i]
l[i] = l[j]
l[j] = temp
return l
def nth(li,k):
return li[k-1]
size = int(input())
lis = []
for i in range(size):
x = int(input())
lis.append(x)
bubble_sort(lis)
key = int(inpu... |
ff9508fec5dadca01276f0edd68a61c26a01ae0a | Coders222/Shared | /Comp Sci Gr 10/Selection/test.py | 347 | 3.796875 | 4 | year = "2007"
year = int(year[-2:])
x = year // 19
y = year // 4
print(x)
print(y)
print(year)
r = 19 * year
print(r)
r -= x
print(r)
r %= 30
print(r)
print()
s = 6 * year
print(s)
s -= y
print(s)
s -= r
print(s)
s %= 7
print(s)
"""
r = (19 * year - x) % 30
s = (6 * year - y - r) % 7
... |
9b25df47250fda284cb3133470b11cf53013337c | gistable/gistable | /all-gists/c425f861de7bbf28ef06/snippet.py | 1,437 | 3.609375 | 4 | #!/usr/bin/env python
# Built-in modules
import logging
import Tkinter
import threading
class TextHandler(logging.Handler):
"""This class allows you to log to a Tkinter Text or ScrolledText widget"""
def __init__(self, text):
# run the regular Handler __init__
logging.Handler.__init__(self)
... |
79e19a88245c5b5e9cd96bacf12ec264d5cdc2bc | pawel-R/Practical_projects | /Christmas_Tree.py | 299 | 3.90625 | 4 |
height = int(input("Put the height of the tree: "))
for i in range(1, (height * 2)):
if (i %2 == 0):
continue
else:
spaces_Amount = height - (i / 2)
spaces = " " * int(spaces_Amount)
star = "*" * i
print(spaces + star)
|
555c08c9001679de90c9c3c2e0c4700205923911 | OMA-Devs/Binance-cluster | /LEGACY1305/client/checker.py | 7,086 | 3.796875 | 4 | #!/usr/bin/env python3
'''checker.py'''
class Checker:
"""Antigua clase ALGO. Esta clase engloba las comprobaciones de los
datos de la clase AT y determina si un par cualifica o no para un trade.
Por el momento, la comprobación se compone de 2 etapas.
"""
def __init__(self, at):
"""Metodo de inicialización. R... |
903c4b4a8ed1f5cd9968ebc62b2f4d578b655bd0 | lixiang2017/leetcode | /leetcode-cn/0677.0_Map_Sum_Pairs.py | 831 | 3.546875 | 4 | '''
执行用时:20 ms, 在所有 Python3 提交中击败了100.00% 的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了49.06% 的用户
通过测试用例:35 / 35
'''
class MapSum:
def __init__(self):
self.seen = dict()
self.m = defaultdict(int)
def insert(self, key: str, val: int) -> None:
if key in self.seen:
old_val = self.seen[... |
21b37c4353f6b59530ed24ba780e700936fe1978 | Built00/Leetcode | /Can_Place_Flowers.py | 1,712 | 3.96875 | 4 | # -*- encoding:utf-8 -*-
# __author__=='Gan'
# Suppose you have a long flowerbed in which some of the plots are planted and some are not.
# However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
# Given a flowerbed (represented as an array containing 0 and 1, where 0 me... |
2dac13e32261b6043e0c9b25bcc4b2e6563ec41e | kurtportelli/tic-tac-toe-checker | /tic-tac-toe-checker.py | 744 | 3.875 | 4 | def isSolved(board):
for row in board:
if row == [1, 1, 1]:
return 1
if row == [2, 2, 2]:
return 2
for j in range(3):
column = []
for row in board:
column.append(row[j])
if column == [1, 1, 1]:
return 1
... |
bc462d48df107e4442d5e86d2e3dbfb2d015f3fb | sniemi/EuclidVisibleInstrument | /sandbox/uploadFTP.py | 1,792 | 3.6875 | 4 | """
This module contains functions related to FTP file transfer protocol and file compression.
:Author: Sami-Matias Niemi
:contact: s.niemi@ucl.ac.uk
:version: 0.2
"""
import ftplib, os, glob, tarfile
def compress(filename):
"""
Compress a file to a gzipped tar ball.
:param filename: name of the file t... |
95cea3f2130e3df4e1717524a6e0a8f7a1250fda | xiantang/grokking_algorithms | /code/4-3.py | 131 | 3.5625 | 4 | a = [1,2,3,4,5]
def count(array):
if array == []:
return 0
else:
return 1+count(array[1:])
print(count(a))
|
e9cca934f305a8c4382be33c61b970812a5ce1d9 | RIMPOFUNK/FirstLyceumCourse | /Lesson 20 (Функции. Возвращение значений из функций)/Special/2. Палиндромы.py | 172 | 3.578125 | 4 | def palindrome(word):
if ''.join(word.lower().split()) == ''.join(word.lower()[::-1].split()):
return "Палиндром"
return "Не палиндром"
|
22aa0f2dc5df2b2528d6ac3b503cae2ec85ce499 | edmarques11/Forca-Python | /jogo.py | 4,409 | 3.859375 | 4 | #Código do samuel: https://repl.it/@crisdebug/Trabalho-Forca
from random import choice
import lib.util as util
def inicio():
util.clear()
Temas_existentes = util.carregar_temas()
util.cabecalho('Bem-vindo ao jogo da forca', [''])
print('Escolha o nível de jogo:')
print('1 - Fácil')
print('2 - Médio')
... |
ac611697b086e45145b4b05a1b1fad48946c5ffd | ChangxingJiang/LeetCode | /0901-1000/0913/0913_Python_1.py | 1,865 | 3.5625 | 4 | import functools
from typing import List
class Solution:
def catMouseGame(self, graph: List[List[int]]) -> int:
@functools.lru_cache(None)
def count(t, x, y):
"""
:param t: 当前移动时间
:param x: 当前老鼠的位置
:param y: 当前猫的位置
:return: 当前的游戏情况
... |
05f893e6220ddde3d36ee133a3ef1e886b685dac | leandrotune/Python | /pacote_download/PythonExercicios/ex049.py | 185 | 4 | 4 | # mostrando a tabuada com o laço for:
n = int(input('Digite um número para saber sua tabuada: '))
for c in range(1, 11):
a = n * c
print('{} * {} = {}'.format(n, c, a))
|
a5bb2bfe7e31333f888e282c048b2c8c3f1c834f | salviolorenzo/python104 | /how_many_coins.py | 262 | 4.03125 | 4 | coin = 0
print('You have %d coins.' % coin)
question = input('Do you want another? ').lower()
#print(tally)
while question == 'yes':
coin = coin + 1
print('You have %d coins.' % coin)
question = input('Do you want another? ').lower()
print('bye')
|
d39d4f87320c0f4ada57919cb8e95ed8bf8cb408 | Skipper609/python | /Sample/class eg/stack/stack.py | 1,695 | 4.0625 | 4 |
class Stack:
def __init__(self):
self.st = []
def push(self, ele):
self.st.append(ele)
def pop(self):
if not self.is_empty():
ele = self.st.pop()
print(f"The popped element is {ele}")
else:
print("Stack is empty")
def search(self... |
1f7bf1ca4add76ca6879f6b57ac0419aa94a1422 | TanmayAB/Coding_practice | /general_questions/gumball.py | 816 | 3.609375 | 4 | def insert_in_dict(key, cost, machines):
print("Inserting : ", key)
if key not in machines:
if len(machines) > 2:
key_min = min(machines.keys(), key=(lambda k: machines[k]))
cost += machines[key_min] * 0.01
print("Taking out : ", key_min, machines[key_min])
... |
ef40153ade152a574b4386e60241c25d71b98abf | jedzej/tietopythontraining-basic | /students/mielczarek_szymon/lesson_06_dicts_tuples_sets_args_kwargs/fantasy_game_inventory.py | 602 | 3.78125 | 4 | """ Projects: 1 & 2 """
def display_inventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(v, k)
item_total += v
print("Total number of items: " + str(item_total))
def add_to_inventory(inventory, added_items):
for item in added_items:
... |
59492f1d31003b5b62eb717751b9899a37295033 | prudhvi3421kumar/.idea | /Conditions.py | 275 | 4.15625 | 4 | age=int(input("Please enter your age: "))
#if age>=16 and age<=65:
if 16<=age<=65:
print("Have a good day at work")
else:
print("enjouy your free time")
print("*-"*50)
if age<16 or age>65:
print("Enjoy your free time")
else:
print("Have a good day at work") |
ea984db07cbaeccdc2d69e78917520b0c3c7e021 | olagesin/Algorithm-Interview-Questions | /Largest_continous_sum.py | 426 | 4.09375 | 4 | """
Code Objective: Given an array of numbers, find the largest continuous sum
"""
def sum_largest_cont(arr):
if len(arr) == 0:
return 0
else:
current_sum = max_sum = arr[0]
for number in arr[1:]:
current_sum = max(current_sum + number, number)
max_sum = max(c... |
65b0251da8d7022ceaa8d995337ed76c2346c9b8 | isarfarajahmad/Data-Structure-Python | /Search/linear_search.py | 411 | 4.0625 | 4 | arr = []
n = int(input("Enter size of the array: "))
for i in range(n):
x = int(input("Enter the element: "))
arr.append(x)
print("The array is: ", arr)
item = int(input("Enter the element to search: "))
flag = 0
for i in arr:
if arr[i] == item:
flag = 1
break
else:
flag = 0
if f... |
019ae80e84a08b32f86ccb1db55fad6556f9caaf | josinho101/python-tutorial | /basic/18.for-range.py | 396 | 4.34375 | 4 | # iterate till 10
for x in range(10):
print(x)
print("------------------------")
# specify start range
for x in range(4, 10):
print(x)
print("------------------------")
#increment by 2
for x in range(5, 20, 2):
print(x)
print("------------------------")
#else in for loop. will be executed at the end o... |
652933eade2a73bd9e5acb6236abc40ff5a749e2 | marilynle/Intro-Python-II | /src/item.py | 1,801 | 3.875 | 4 | class Item:
"""Base class for Items"""
def __init__ (self, name, description):
self.name = name
self.description = description
def on_take (self):
print(f'You have picked up {self.name}')
def on_drop (self):
print(f'You dropped {self.name}')
def __repr__ (self)... |
4d6ecf49802b1b113ccfd2514b2ca972158aa024 | mdtalbot/python-playground | /most_common_words.py | 195 | 3.703125 | 4 | def most_common_words(freqs):
values = freqs.values()
highest = max(freqs.values())
words = []
for k in freqs:
if freqs[k] == highest:
words.append(k)
return (words, highest)
|
c8999c40e6e5158560d3ec3d515dcc5fdab0147d | matt-ankerson/ads | /recursion/recursion.py | 871 | 4.15625 | 4 | # function that takes a list of unsorted integers and returns the maximum value
def find_max(list):
if len(list) == 1: # base case
return list[0]
if list[0] < list[1]: # if first element is smaller than the second
list2 = list[1:] # copy the list with first element removed
else:
... |
b3a9824896a1d3ce924eccfa64e2fb96e864686b | lrrimulo/IvSPythonRepository | /aux/argkwargparser.py | 2,320 | 4.125 | 4 | """
Automatically parse command line args and kwargs.
This module is meant to facilitate the translation of command line arguments to
Python code to parse to methods.
Example usage:
Given an example minimalistic Python module 'example.py'
>>> def testfunc(a,b,calc='sum'):
>>> ... if calc=='sum': return a+b
>>> ... ... |
cfe538407ed4367aa925a4e5d94d61f7ef204ef4 | hofernandes/python3-mundo-1 | /ex008.py | 278 | 4.125 | 4 | # Estreva um programa que leia um valor em metros e a exiba convertida em centimetros e milimetros
m=float(input('Digite um valor em metros: '))
print('O valor de {} em metros equivale a {}km, {}hm, {}dam, {}dm, {}cm e a {}mm'.format(m,m/1000, m/100, m/10, m*10, m*100, m*1000)) |
246f7172ead06b27a7a7609e919fa4bf2652b567 | ForrayGabriel/PROJ631-Arbre-de-decision | /Not working/csv_reader.py | 286 | 3.8125 | 4 | import csv
# Open en read a csv file
def read_csv(fichier):
with open(fichier, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
data = []
for row in reader:
data.append(row[0].split(","))
return data
|
2930318dea304e5d1a3db074fc4be02bb3b273f6 | Ca-moes/FPRO | /RE07/unique.py | 518 | 4.0625 | 4 | #unique.py
#atuple=(8, 8, 1, 3, 1, 3, 5) -> tuple (1, 3, 5, 8)
#atuple=(1, 1, 1, 1) -> (1,)
# sort first tupple
# run one on one
# check, run one on one result tupple - if value is not on result tuple, add
def unique(atuple):
temptuple = ()
count = 0
for a in atuple:
for b in temptuple:
... |
a7fab51318ea521ab988d9504a596c6872050b4c | lisadean/funky-stuff | /multiply.py | 382 | 3.921875 | 4 | # factor = 5
# numbers = [1, 45, -67, 62, 0, -1]
# new_list = []
# for num in numbers:
# new_list.append(num * factor)
# print(new_list)
def multiply(numbers_to_multiply, multiplication_factor):
# numbers_to_multiply = [1, 45, -67, 62, 0, -1]
new_list = []
for num in numbers_to_multiply:
new... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.