blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
007bfa506f9040b3fffef57be4cacfa9c749ac87 | sofiatti/exercism | /pangram/pangram.py | 234 | 3.75 | 4 | import string
def is_pangram(sentence):
alphabet = list(string.ascii_lowercase)
for letter in alphabet:
if letter in list(sentence.lower()):
continue
else:
return False
return True |
58a149e5362358bd04e0e25d4e4f207e3cb4bf42 | babiswas/Graph-Theory | /topsort_kans.py | 1,182 | 3.984375 | 4 | from collections import defaultdict
class Graph:
def __init__(self,V):
self.vertex=V
self.graph=defaultdict(list)
def add_edges(self,u,v):
self.graph[u].append(v)
def topsort(self):
visited=[False]*self.vertex
queue=[]
count=0
indegree=[0]*self.ve... |
e190cef802f2e613fa1f43e9d9e17fe421e70202 | jklemm/curso-python | /pythonbrasil/lista_1_estrutura_sequencial/ex_05_converte_metros_para_centimetros.py | 250 | 3.890625 | 4 | print('Conversor de metros para centímetros')
medida_em_metros = float(input('Informe uma medida em metros: '))
medida_em_centimetros = medida_em_metros * 100
print('Esta medida convertida fica {:.0f} centímetros'.format(medida_em_centimetros))
|
b5837c0feaeca8d25cacf463ea26abb9ebeddd47 | Ozcry/PythonCEV | /ex/ex063.py | 496 | 4.09375 | 4 | '''Escreva um programa que leia um número 'n' inteiro qualquer e mostre na tela os 'n'
primeiros elementos de uma Sequência de Fibonacci.
Ex:. 0 - 1 - 1 - 2 - 3 - 5 - 8'''
print('\033[1;33m-=\033[m' * 20)
n1 = int(input('\033[34mDigite um número:\033[m '))
t1 = 0
t2 = 1
cont = 3
print('{} - {}'.format(t1, t2), end='')
... |
9d4bccaea59e53a0f700c9c6d1da2e7661abbb7e | Aizen741/PythonBasic | /lat_lang.py | 931 | 4.375 | 4 | from math import *
#You need Radius of earth to find the distance between two points
radius_of_earth = 6373.0
# You can use the simple .split(" ") with float to get input but this is fast trick called 'List Comprehension'
my_long, my_lat = [float(my_long) for my_long in input('Enter you location longitude and latitu... |
3234edaab8c87f286fce21f3e8b5386cbb9b2b89 | Fabien-Vauclin/BachelorDIM-Lectures-Algorithms-2020 | /assignements/S3_imgproc_tools.py | 1,426 | 3.5 | 4 | import cv2
import numpy as np
img = cv2.imread('/home/fabien/Pictures/algo_img.jpg')
print("input image shape", img.shape)
cv2.imshow('input', img)
cv2.waitKey()
img_out = np.zeros(img.shape, dtype=np.uint8)
for row in range(img.shape[0]):
for col in range(img.shape[1]):
for channel in range (img.shape[... |
8ed99e8ed166c0be93d09bdf9c1b5f26728482fb | jnlycklama/DataStructures | /binarySearchTree.py | 4,459 | 3.796875 | 4 | import random
import time
#Experiment One
def inList():
bin_count = 0
bin_total = 0
tri_count = 0
tri_total = 0
for j in range (250, 80000, 3000): #number of values in the list, changes by 3000
lis = []
k = []
for i in range (0, j):
num = random.randint(0, 10000... |
473b823d8cf8c386fa54b4b407a2336204ff8b00 | bssrdf/pyleet | /F/FindMinimumRotatedSortedArrayII.py | 1,064 | 3.96875 | 4 | """
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
The array may conta... |
5f0b2f85bd4015416a59474f96bdc47bad63b466 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/chelsea_nayan/lesson08/circle.py | 4,066 | 4.46875 | 4 | # Lesson08: Circle Class Exercise
"""
Create a class that represents a simple circle
"""
import math
class Circle(object):
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
# diameter = radius*2
@property
def diameter(self):
... |
0b4542d44b8502fd31d42087246796cc9583b963 | ChristianVasq/Classes | /Final Project/Final Project.py | 1,579 | 4.1875 | 4 | def main():
import random
import calendar
# import graphics as g
#Store the month selection with days included
MonthWdays = {"1":31, "2":29, "3":31, "4":30, "5":31, "6":30, "7":31,
"8":31, "9":30, "10":31, "11":30,"12":31}
#Statement declaring fruit types
FruitTypes =... |
cbe28f0bb4f96f2b5396f14b48445fbe652c2716 | HyungilNam/IntroductionToSoftwareDesign | /170320_Ex2.py | 1,251 | 4 | 4 | #170320_Exercise2
#Summation/Average/Max/Min
def Totaltotal(a,NumNum):
Total = a + NumNum
return Total
def Max(NowMax,A):
if(NowMax < A):
NowMax = A
return NowMax
def Min(NowMin, A):
if(NowMin > A):
NowMin = A
return NowMin
Count = -1
A = ''
Sum = 0
Ave = 0
NowMax = ''
NowMin... |
7d6d3180d77b867fe194a0eb5a8469c6e9eb8c9b | lmregus/Portfolio | /python/exercism/word-count/wordcount.py | 682 | 4.125 | 4 | #########################
# #
# Developer: Luis Regus #
# Date: 12/11/2015 #
# #
#########################
def word_count(string):
""" Returns the word count in a string
This functions gets a string and counts the
words in it
Args:
... |
73403646eddec60575cbf7b8c055ac153ba8df70 | JuliaPanova/Otus_T | /Task_2/truck.py | 2,325 | 4.1875 | 4 | from Task_2.vehicle import Vehicle
class Truck(Vehicle):
"""
Truck is a subclass of Vehicle
"""
def __init__(self, weight, fuel, engine, tank_volume, number_of_wheels, capacity, cargo):
super().__init__(weight, fuel, engine, tank_volume, number_of_wheels)
self.capacity = capac... |
5295d787e56b91cf2c0da9cfc0ebb630fadba1c4 | ROF618/Think_Python | /CS9.8.py | 324 | 3.75 | 4 |
def check_palindrome(numbers):
num_list = []
i = 0
for digit in str(numbers):
num_list.append(int(digit))
num_list_reversed = list(reversed(num_list))
while i < len(num_list):
if num_list[i] == num_list_reversed[i]:
print(num_list[i])
i += 1
check_palindrome(5... |
518168201f5e9904de47dfc08fd775ffdd1924ba | KerouacAutumn/PyCode | /day01/ForDemo.py | 1,022 | 3.859375 | 4 | # str01 = "安河桥"
# for item in str01:
# print(item)
# # range整数生成器 range(开始值,结束值,间隔)
# for item in range(1, 5, 2):
# print(item)
# # for + range执行预定次数
# thickness = 0.0001
# for item in range(30):
# thickness *= 2
# print(thickness)
# str = ","
# for i in range(1, 10):
# for j in range(1, i + 1)... |
4e3dee470e9cef576508a8085b716571308bce90 | Yunyi111/git_test | /week 9/plotting_matplotlib.py | 574 | 3.625 | 4 | import matplotlib.pyplot as p
my_list=[2, 5.5, 6, 8.9] # x-values by default: 0, 1, 2, 3
my_list_xvalues=[2, 4, 6, 8] # define x-values
my_list_xvalues2=[1, 3, 5, 7]
# Trend plotting
#p.plot(my_list, linewidth=5)
#p.title("Square Numbers", fontsize=24)
#p.xlabel("Value", fontsize=14)
#p.ylabel("Square of values", fon... |
4bbbfdb6d658bcf27f9b0edc9278829734cf0805 | prudhvireddym/CS5590-Python | /Source/Python/ICP 1/Reverse.py | 120 | 4.34375 | 4 |
name = input("enter a string:")
rname=""
for i in name:
rname = i + rname
print("The reverse string is %s"%(rname)) |
92e60e7470577a6e2c55d29272c64d397ce67676 | UmasouTTT/leetcode | /reshapeMatrix566.py | 819 | 3.640625 | 4 | class Solution(object):
def isReshapeLegal(self, nums, r, c):
if len(nums) * len(nums[0]) == r*c:
return True
return False
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
... |
f50e9d0654075f764e7ad892becd1e05451648f4 | bhoomit93/Data-Structures-and-Algorithm-in-Python | /Rotate_LinkedList.py | 1,052 | 3.984375 | 4 | # Node Class
class Node:
def __init__(self,data):
self.data = data
self.next = None
#LinkedList
# functions included:
# push, printList, rotate the list
class LinkedList:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
ne... |
0fc7c901114011fb240adea8b3a2d8f5eea027f3 | CXuTao/Python_source | /python_grammar/时间操作/time.py | 1,665 | 3.765625 | 4 | import time
"""
UTC(世界协调时间):格林尼治时间,世界标准时间
在中国来说是UTC+8
DST(夏令时):是一种节约能源而人为规定时间制度,
在夏季调快1个小时
事件表现形式:
1、时间戳
以整形或浮点型表示时间的一个以秒为时间间隔,这个时间间隔的基础值
是从1970年1月1日凌晨开始算起的
2、元组
一种python的数据结构表示,这个元祖有9个模型内容
year
day
hours
minutes
seconds
weekday
Julia day
flag (1 或 -1 或 0)
3、格式化字符串
"""
#返回当前时间的时间戳,浮点数形式,不需要... |
9ea079f4dcc7dde2ce97a78b7ec93f416d0bee3b | pchen12567/Triangle567 | /TestTriangle.py | 3,602 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Feb 27 17:50:00 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: Pan Chen
"""
import unittest
from Triangle import classify_triangle
class TestTriangles(unittest.TestCase):
# define multiple sets of tests as functions with n... |
9e81cd211d950aff5bb4f58135a2d82609f0df62 | Priyansu-Prit-Maharana/School | /School11/practice and extra.py | 4,263 | 3.953125 | 4 | """
Q1 write a program to calculate the total expense, quantity , price per unit are input by the user & a discount is given
"""
A = int(input("enter the quantity"))
B = int(input("price per item"))
C = A * B
if C > 5000:
print(C - (C / 10))
else:
print(C)
# question 2
S = int(input("enter the selling price:")... |
9a7a0cb55d1215149b3f078671f06ed4318bbc9b | sourav98/Python-For-Coding-Interviews | /HackerRank/repeatedStrings.py | 289 | 3.890625 | 4 | def repeatedString(s, n):
n1=n//len(s)
x1=s.count('a')
c1=x1*n1
c2=s[:n%len(s)].count('a')
return c1+c2
s=input()
n=int(input())
result = repeatedString(s,n)
print(result)
"""
Warm Up HackerRank Challenges
https://www.hackerrank.com/challenges/repeated-string
""" |
8bcb676c5d17e2b73b7aa903a791e0062400eb8d | NathanJesudason/TicTacToe | /TicTacToe.py | 4,222 | 3.53125 | 4 | import pygame
import random
from time import sleep
pygame.init()
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREY = (200, 200, 200)
BLACK = (0, 0, 0)
B = 0
X = 1
O = 2
tilemap = [
[B,B,B],
[B,B,B],
[B,B,B]
]
rectangle = [
[None, None, None],
[None, None, None],
[None, None, None]
]
def init():
... |
a61ed72ea905bc9882fa77915f2d66aaea7685cc | newderezzed/Library-Student | /utils/mypage.py | 3,260 | 3.90625 | 4 | """
自定义分页组件
"""
class Pagenation(object):
def __init__(self, data_num, current_page, url_prefix, per_page=10, max_show=11):
"""
进行初始化.
:param data_num: 数据总数
:param current_page: 当前页
:param url_prefix: 生成的页码的链接前缀
:param per_page: 每页显示多少条数据
:param max_show:... |
27b32c3f0ff2ae7d2086574127135b3708e1409a | ProgFuncionalReactivaoct19-feb20/clase02-Jdesparza | /Practica/Practica1.py | 329 | 4 | 4 | """
Jdesparza
"""
# se pide una valor por teclado
n = input("Ingrese un numero: \n")
# se transforma el valor en entero
n = int(n)
# se hace la operacion para determinar si es par
valor_par = lambda x: x%2 == 0
# se guarda en una variable la operacion realizada
valor = valor_par(n)
# se imprime si el valor es par
prin... |
504e6f8b4ac20790a26e6ddc3acb7e52ae329b35 | natebellanger10/EulerProject | /Problem2.py | 335 | 3.6875 | 4 | """Add all even Fib numbers below 4,000,000"""
def fib(n):
if n==1:
return 1
if n==2:
return 2
else:
return fib(n-1)+fib(n-2)
n=1
countList = []
while fib(n) < 4000000:
j=fib(n)
if j%2==0:
countList.append(j)
n+=1
counter=0
for i in countList:
counter+=i
... |
29f7237b4c39f3a6e12e422dd99fba63dedc17a1 | toddbryant/leetcode | /060_permutation_sequence.py | 640 | 3.90625 | 4 | """
The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
"""
class Solution:
def getPermutation(self, n: int,... |
e8fcbb80cdee81ffb44915207d926ae9994d7b7d | shivani12032002/OMNEHA | /swap.py | 242 | 3.953125 | 4 | x=int(input("enter first number"))
y=int(input("enter second number"))
print("before swapping")
print("the value of x",x)
print("the value of y",y)
temp=x
x=y
y=temp
print("after swapping")
print("the value of x",x)
print("the value of y",y)
|
624c906ab8b04a6529a44975ed9028fc2439954a | Sonmone/Approximate-matching-algorithms | /ged.py | 4,238 | 3.625 | 4 | '''This project adopts global edit distance method to predict possible correct spelling posWords
in the dictionary of given misspelled words.
Besides, it also calculates the precision and recall to evaluate this method.
'''
import numpy #a package used in list[]
misfile = open("data\misspell.txt") #open the mis... |
530ddac0b6c81a0265b60974108e681264a6fcb4 | HuzaifaSaifuddin/python-is-easy | /homework-8/notes.py | 1,894 | 4.15625 | 4 | import os
FileName = input("Please provide filename : ")
def PlayFile(FileName, option):
if option == "A":
ReadFile = open(FileName, "r") # Open File
print(ReadFile.read()) # read File
ReadFile.close() # Close it back
elif option == "B":
open(FileName, 'w').close() # Open and Close to empty File... |
e929b2188b3a1241f5a6b3dfe1d4120141854668 | Pradeep1321/PythonNotesForProfessionals | /Chapter-2-3-4.py | 4,036 | 3.90625 | 4 | """
Chapter 2: Python Data Types
Section 2.1: String Data Type
Python allows for either pairs of single or double quotes. Strings are immutable sequence data type, i.e each time one
makes any changes to a string, completely new string object is created.
Section 2.2: Set Data Types
Sets are unordered collections of un... |
58c7a0db0af5b0e7a04572dd014c2df419d8d6af | akjayant/Data-Structures-Algorithms | /ds_algo_practice/arrays/day1/day1_4singlenumber.py | 1,745 | 3.671875 | 4 | #https://leetcode.com/problems/single-number/submissions/
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = nums[0]
for i in range(1,len(nums)):
s=s^nums[i]
return s
#---advanced version
#https://leetcode.com/problems/single-number-ii/
#Given an integer a... |
fb862a912767ff215dcf7e67662a16fd43bb40d2 | Onyiee/python_practice_exercises | /Strings/Palindromes.py | 845 | 4.125 | 4 | # 3.12 (Palindromes) A palindrome is a number, word or text phrase that reads the same
# backwards or forwards. For example, each of the following five-digit integers is a
# palindrome: 12321, 55555, 45554 and 11611. Write a script that reads in a five-digit integer
# and determines whether it’s a palindrome. [Hint: Us... |
ae19291954ec188e0d634431407fc2d66a32a0ad | NBaiel81/Classes | /21.01.21.ex.classes.py | 1,400 | 3.8125 | 4 | class Beaver:
finished_bridges = 0
def __init__(self, name, age, weight, power):
self.name = name
self.age = age
self.weight = weight
self.power = power
if self.age>=11:
self.power-=5
def __str__(self):
return "{} {}".format(self.name, self.age)
... |
55a49cd00ca66117378afaabd60afe6cfcc307cc | DmOfff/praktika | /1/t49.py | 377 | 3.875 | 4 | # Пользователь вводит четыре числа.
# Найдите наибольшее четное число среди них. Если оно не существует, выведите фразу "not found"
nums = []
for i in range(4):
n = int(input(""))
if n % 2 == 0:
nums.append(n)
print(max(nums) if len(nums) > 0 else "not found")
|
255c126c0848721e06cbeae62320f865e847c9c8 | pittDeng/MACHINE | /machineLearning/AndFunc.py | 391 | 3.5625 | 4 | from Perceptron import Perceptron
def myfunc(x):
return 1 if x>0 else 0
def get_training_dataset():
dataset=[[1,1,1],[1,1,0],[1,0,1],[1,0,0],[0,1,1],[0,1,0],[0,0,1],[0,0,0]]
labels=[1,0,0,0,0,0,0,0];
return dataset,labels
if __name__=='__main__':
percep=Perceptron(3,myfunc,0.1)
dataset,labels=... |
b2eec627c9c5c33e1fffcd3faf91b7ba42bd1984 | xin-liqihua/PythonLearn | /Chapter_1/test2.py | 576 | 3.6875 | 4 | '''
获得用户输入的一个正整数输入,输出该数字对应的中文字符表示。
0到9对应的中文字符分别是:零一二三四五六七八九
'''
Str = "零一二三四五六七八九"
Num = input()
StrNum = str(Num)
for num in StrNum:
print(Str[int(num)], end="") |
a4490e34f74e9f168f2d75765157d506f3097571 | GaoYu/zeroPython | /15_filter.py | 700 | 3.6875 | 4 | def isodd(x):
return x % 2 == 1
for x in filter(isodd, range(10)):
print(x)
even = [x for x in filter(lambda x: x%2 ==0, range(10))]
#练习:
# 1. 将 1 ~20 内的偶数用filter筛选出来,形成列表
even = [x for x in
filter(lambda x : x%2==0, range(1,20))]
print(even)
even = list(filter(lambda x:x%2==0,range(1,20)))
pri... |
63d630f4c251a361a788d527db247a8dacb1297f | jschnab/leetcode | /arrays/subarray_sum_equals.py | 1,395 | 3.78125 | 4 | # leetcode challenge 560: subarray sum equals k
# given an array of integers and an integer k, we need to find the total
# number of continuous subarrays whose sum equals k
# input: [1,1,1], k = 2
# output: 2
def subarray_sum_brute(nums, k):
"""
Brute force solution, check every subarray and make its sum.
... |
3f0ee2826011e17572e2ccef08f3ea01220d6ba3 | heysushil/full-python-course-2020 | /13.class.py | 2,632 | 4.34375 | 4 | # class: varibale + method : object
# hamesa class neame wo capital letter
class Myclass:
name = 'Python'
# create class object
obj = Myclass()
print(obj.name)
# creat a cons. in class
class User:
# createing construcre: it helps to pass values to each methods
# self: it's a current instance which hol... |
9c42ab072586874e5711476ec90637d04357dcae | stephenboothuk/a | /demo_dictionary.py | 220 | 3.671875 | 4 | a = dict(A=1, Z=-1)
print(a)
b = {'A': 1, 'Z': -1}
print(b)
c = dict(zip(['A', 'Z'], [1, -1]))
print(c)
d = dict([('A', 1), ('Z', -1)])
print(d)
e = dict({'Z': -1, 'A': 1})
print(e)
print(a == b == c == d == e) |
ffddb6adc1ef21f81a116723d7ad1635d58f4f96 | Aman-dev271/PythonProjects | /4thexc.py | 425 | 3.8125 | 4 | s= [2,3,4,5,'amandeep',333,444,55,666,77788,77,80,12,1,23]
list1 = []
for item in s:
if type(item) == int and item > 6:
print("your add the" ,',', item ,',',"value in the list")
list1.append(item)
else:
print("not can't be add")
print("your new list is :" ,list1)
f... |
b8c81d302a4b70ec5ac355b73fac7e25880fe08a | siddiqum/Project2 | /Matplotlib_2.3.py | 681 | 4 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = [0,1,2,3,4]
y = [0,2,4,6,8]
plt.figure(figsize=(8,5), dpi=100)
plt.plot(x,y, 'g--', label='2x')
# select interval we want to plot points at
x2 = np.arange(0,4.5,0.5)
# Plot part of the graph as line
plt.plot(x2[:6], x2[:6]**2, 'b', label='X^2')
... |
6eb43172bf8e5c4701885531c6c39eae7e4e01e7 | KeleiAzz/LeetCode | /Google/Jump.py | 517 | 3.75 | 4 | def JumpArray(arr):
count = 0
visited = [0] * len(arr)
index = 0
while count < len(arr):
if visited[index] == 1 and index != 0:
return False
elif visited[index] >= 1:
break
visited[index] += 1
index = (index + arr[index]) % len(arr)
count +... |
de45e28079a431009a68cb3d4fbce61da35c4a35 | LucasBarbosaRocha/URI | /Strings/1248_v2.py | 740 | 3.5625 | 4 | N = int(input())
for i in range(N):
dieta = input()
cafe = input()
almoco = input()
janta = ""
refeicao = cafe + almoco
dietaOrdenada = sorted(dieta)
refeicaoOrdenada = sorted(refeicao)
#print(dietaOrdenada, refeicaoOrdenada)
if (len(refeicaoOrdenada) > len(dietaOrdenada)):
print("CHEATER")
else:
aux = 1
... |
7963927e5e78a670856a798f68c6328f825bdf7d | st4rk95/pruebasPython | /pruebasPython/aprendeconalf.es/tuplas_y_diccionarios/ejercicio13.py | 522 | 3.859375 | 4 | #Escribir un programa que pregunte por una muestra de numeros, separados por comas, los guarde en una lista y muestre por pantalla su media
numeros_introducidos = str(input("Introduce una serie de numeros separados por comas: "))
lista_numeros = numeros_introducidos.split(",")
suma_total = 0
for i in lista_numeros:
... |
f9cf783acce2309eb190bc8d638d2fee205f16ef | TingliangZhang/VR_Robot | /Python/Pythonpa/ch09/TemperatureConverter.py | 880 | 3.5625 | 4 | class TemperatureConverter:
@staticmethod
def c2f(t_c): #摄氏温度到华氏温度的转换
t_c = float(t_c)
t_f = (t_c * 9/5) + 32
return t_f
@staticmethod
def f2c(t_f): #华氏温度到摄氏温度的转换
t_f = float(t_f)
t_c = (t_f - 32) * 5 /9
return t_c
#测试代码
print("1.... |
a33faae818694f698b521fd060033e6973ce47af | Sudheer-Movva/Python_Assignment01 | /Assignment-1/Chap12/ChapTwelve3.py | 1,708 | 3.859375 | 4 |
class Account:
def __init__(self,id,balance=100):
self.__id = int(id)
self.__balance = float(balance)
def getID(self):
return self.__id
def getBalance(self):
return self.__balance
def withdraw(self,amount):
self.__balance -= float(amount)
... |
d75a943e08c427460ddfeba9629e6bef0d656b04 | sasazlat/UdacitySolution-ITSDC | /computer_vision/visualizing_the_data.py | 2,478 | 3.703125 | 4 |
# coding: utf-8
# # Day and Night Image Classifier
# ---
#
# The day/night image dataset consists of 200 RGB color images in two
# categories: day and night. There are equal numbers of each example: 100 day
# images and 100 night images.
#
# We'd like to build a classifier that can accurately label these images as d... |
2e4450a8c46670f23efce414fdec009cead76aed | yunusgok/Naive-Bayes-and-Hidden-Markov-Models | /nb.py | 5,424 | 4.03125 | 4 | from math import log as ln
import os
import re
import numpy as np
def vocabulary(data):
"""
Creates the vocabulary from the data.
:param data: List of lists, every list inside it contains words in that sentence.
len(data) is the number of examples in the data.
:return: Set of words in ... |
971315675af2175540d8bbf088a75e14f45b2fff | brunops/algorithms | /misc/python/maximum-subarray.py | 315 | 3.609375 | 4 | # Kadane's algorithm
# Return maximum continuos sum in an array
# Complexity O(n)
def maximum_subarray(A):
max_so_far = max_ending_here = 0
for x in A:
max_ending_here = max(0, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
print maximum_subarray([1,11,-10,20])
|
aab522dbe4b5af63d7f8a01e12febcc2c7767e82 | TimLeeTY/compPhyEx | /ex2/ODE.py | 8,581 | 3.875 | 4 | """
=========================================
Ex.2 Solving the ODE of a simple pendulum
=========================================
Solve equation: θ''=-(g/l)*sin(θ)-q*θ'+F*sin(Ω*t)
Define: θ=θ, ⍵=θ'
The coupled first order ODES are:
⍵=θ'
⍵'=-(g/l)*sin(θ)-q*⍵+F*sin(Ω*t)
Apply 4th order Runge-Kutta
"""
import numpy as np
... |
c624064df0b4cac02bddc33a2aa1d71ca93c9104 | GustavoGarciaPereira/Topicos-Avancados-em-Informatica-I | /exercicios_strings/exe2.py | 243 | 4.0625 | 4 |
'''. Escreva um programa que leia uma palavra qualquer e veri que se esta palavra é um
palíndromo.'''
string = input('Informe uma palavra: ')
if string == string[::-1]:
print("É palindromo!")
else:
print("Não é palindromo!") |
a25941bf290bd30bc3330d63704be7a212c82f37 | ninux1/Python | /decorators/timedeco.py | 500 | 3.625 | 4 | #!/usr/bin/env python
from datetime import datetime
import time
def timedeco(func):
def action(num):
start = datetime.now()
res = func(num)
print(res)
return datetime.now() - start
return action
@timedeco
def factorial(num):
result = num
while(num != 1):
result... |
12dc6c29533b9fd51fde9bc4927934550f904fac | anthonyraj/py | /interviews/dailycoding/amazon-steps.py | 1,288 | 4.53125 | 5 | """
This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time.
Given N, write a function that returns the number of unique ways you can climb the staircase.
The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1,... |
67785b581ac29d74c123c5a986f872cc1e67164a | PriteshKiri/Basic-Pyhon-Projects | /rolling the dice/dicee.py | 862 | 3.640625 | 4 | from PIL import Image
from random import randint
randomm = randint(1,6)
im = Image.open('dice.jpg')
while True :
inp = input("Please type 'ROLL' to roll the dice : ")
if inp == 'ROLL':
def roll(value):
if value==1:
box = (0,0,333,342)
portion1 = im.crop(box)
portion1.show()
if value=... |
dfa4be1c2fd32777a3ce4855107ecda5226f073a | vksmgr/DA-Py | /src/test.py | 2,451 | 3.796875 | 4 | import bisect
c = [1,2,2,4,9]
pos = bisect.bisect(c, 10)
print("position : {}".format(pos))
bisect.insort(c,10)
print(c)
for (i, value) in enumerate(c):
print(" I : {0} , value : {1}".format(i,value))
itme = 'i love you'
print(sorted(itme))
print(list(zip(c,itme)))
for (i, v) in enumerate(zip(c... |
64ab408d192d3d38ebf9be70772c6373fe1a3ecb | tabletenniser/leetcode | /5442_avoid_flood.py | 5,227 | 3.984375 | 4 | '''
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake.
Given an integer array rains where:
rains[i]... |
d1c34cf7c505b25a714238ffda640cf391132db8 | dongsik93/HomeStudy | /Question/sw_expert/D2/1983.py | 867 | 3.640625 | 4 | def grade(num, rank):
import math
n = math.ceil(rank / (num / 10))
if(n == 1):
return "A+"
elif(n == 2):
return "A0"
elif(n == 3):
return "A-"
elif(n == 4):
return "B+"
elif(n == 5):
return "B0"
elif(n == 6):
return "B-"
elif(n == 7):
... |
dae238ed82e3ba001f9213f6190829b8e9b32bfa | monicador/Python | /Else_Numero_romano.py | 1,049 | 4 | 4 | '''
Elabora un algoritmo que permita ingresar un numero entero,
de 1 a 10, y muestre su equivalente escrito en romano.
'''
numero = int(input("Escribe un numero> "))
if numero == 1:
print("I")
else:
if numero == 2:
print("II")
else:
if numero == 3:
print("III")
else:
... |
970ea9d184376b89e739f89985844cfd1e25afcc | shixinyang666/pyworkspace | /day03/demodef.py | 729 | 4 | 4 | #定义九九乘法表函数
def nine() :
for i in range(1,10) :
for j in range(1,i+1) :
print("{0} * {1} = {2}".format(i,j,i*j),end=" ")
print()
#定义1-100对齐
def num() :
for i in range(1,101) :
num = str(i).rjust(3," ")
print(num,end="")
if i % 10 ==0 :
print()
#... |
705018ff1ff100306f2070607e62d9849015ce69 | nahaza/pythonTraining | /ua/univer/lesson02/__init__.py | 511 | 3.9375 | 4 | def task05_print_season(month_number):
if month_number == 1 or month_number == 2 or month_number == 12:
season = 'Winter'
elif month_number == 3 or month_number == 4 or month_number == 5:
season = 'Spring'
elif month_number == 6 or month_number == 7 or month_number == 8:
season = 'Su... |
35507f01c5093c7c8fd9e7796eaee73b24a1f235 | ScITS-Bern/ddip | /hints/fib.py | 1,229 | 3.578125 | 4 | from functools import wraps
def debug(f):
@wraps(f)
def debug_wrapper(*args, **kwargs):
print(f"{f.__name__} called with arguments:", *args, **kwargs)
return f(*args, **kwargs)
return debug_wrapper
def memoize(f):
cache = {} # Some sort of data structure to store cached ... |
bb657dbc42cdb36af3ed3cb13523c44c1ab27b8a | zhaochl/python-utils | /utils/sort_util_me.py | 4,582 | 3.9375 | 4 | #!/usr/bin/env python
# coding=utf-8
# -*- coding: utf-8 -*-
# 各种排序算法
# author zcl
# date:2016/1/11
#选择排序
def select_sort(sort_array,asc=True):
for i, elem in enumerate(sort_array):
for j, elem in enumerate(sort_array[i:len(sort_array)]):
if asc:
if sort_array[i] > sort_array[j +... |
99d44b2b2a2d1cc03c95820a75c31fc72da95695 | codeblaster7/TypingSpeedGame | /TypingSpeedGame.py | 3,731 | 3.625 | 4 | from tkinter import *
import random
from tkinter import messagebox
def wordTyper():
global count, typing_words
text = "Welcome to Typing Test Game"
if count >= len(text):
count = 0
typing_words = ""
typing_words += text[count]
count += 1
font_label.configure(text=typ... |
bedd856ad1b846504e70083507a8ae31180dff4b | LiamAlexis/programacion-en-python | /clase 3/practica2/funciones.py | 586 | 3.5625 | 4 | from random import random
import random
def login():
usuario = "usuario123"
password = "1234"
nombre = input("Ingrese su Nick : ")
clave = input("ingrese su clave : ")
if usuario == nombre and password == clave :
print("logeado con exito")
else :
print("Nombre... |
3b514fdf6f5e8fc84da44807bbd6627e453d894b | mvanswol/leetCodeSols | /sols/python/6 - zigzag.py | 794 | 3.796875 | 4 | #
#
# Created By : Mitchell Van Swol
# Date : 2/6/2018
#
import sys
# convert the given string to a zigzag pattern
# basic idea is that we map out the string in a zig zag
# pattern and then join the strings together
# O(n) solution
class Solution(object):
def convert(self, s, numRows):
if numRo... |
013e49e277d669dedfb3455080756edff51efa03 | fingerman/python_fundamentals | /intro/2_9_celsius.py | 74 | 3.640625 | 4 |
a = float(input())
a = a * 1.8 + 32
print(float("{0:.2f}".format(a)))
|
dc30aba7ef2f24014fe1aecfbd7eb7226f272e4a | Tavares-NT/Curso_NExT | /MóduloPython/Extras04.py | 803 | 4.1875 | 4 | '''Faça um programa, com uma função que necessite de uma quantidade de argumentos indefinida, e um argumento de operação dos valores. Esta função deverá returnar o resultado da operação destes valores.'''
def soma(valores):
resultado = 0
for x in valores:
resultado += x
return resultado
def calculadora(*va... |
c20ccd58bf0b3aa60838c55010d72f55d8776107 | sannicko/Python | /Python/Scores and Grades.py | 753 | 4.03125 | 4 | import random
# testing the random module
# value = random.randint(1, 6)
# print(value)
# greetings = ['Hello', 'Hi', 'Hola', 'Ciao', 'Howdy']
# value = random.choice(greetings)
# print(value + ', Nick!')
def grade(scores):
print "Scores and Grades"
for i in range (0, scores):
score = random.randint(60... |
1abc4b98c3ba3828d275cf663501fe43a4597ab0 | adit-negi/LeetcodePython | /tree/Btree_zig_zag.py | 1,058 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
def height(root):
if root... |
74f7ba4b795981263fe765dca51e92bf0882e5ff | cmanallen/csv-manager | /csv_manager/parser.py | 1,310 | 3.609375 | 4 | class Parser(object):
def __init__(self, csv, heading):
self.csv = csv
self.heading = heading
def parse(self):
loaded_file = open(self.csv).read()
return self._file_to_object(loaded_file)
def _file_to_object(self, csv):
rows = csv.split('\n')
row_object = {}
if self.heading:
head = rows[0].spli... |
9f20e220171d0a81dee3e827264b8560a62b6404 | Davidhfw/algorithms | /python/offer/56_num_two_counts.py | 473 | 3.53125 | 4 | import functools
def singleNumbers(nums):
ret = functools.reduce(lambda x, y: x ^ y, nums)
div = 1
while div & ret == 0:
div <<= 1
a, b = 0, 0
for n in nums:
if n & div:
a ^= n
print(f'first group nums is {n}')
else:
b ^= n
pr... |
1fad2a4b2ca9231fc7c9167345f589dcaf5de227 | dansmyers/Baby-Name-Popularity | /app.py | 2,168 | 3.5 | 4 | from flask import Flask, request, Response, render_template
import json
import pandas as pd
app = Flask(__name__, static_url_path='', static_folder='./static')
### Constants
MIN_YEAR = 1910
MAX_YEAR = 2019
### Flask routes
@app.route('/')
def root():
return app.send_static_file('index.html')
@app.route... |
ab1b6f516912afd51b886ac577738fb2293ae1bb | ahtornado/study-python | /day6/test.py | 1,032 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author :Alvin.Xie
# @Time :2017/10/27 22:35
# @File :test.py
f = open("aa", 'r')
# read是逐字符地读取,是read可以指定参数,设定需要读取多少字符,无论一个英文字母还是一个汉字都是一个字符
f_read = f.read()
print (f_read)
f.close()
f1 = open("aa", 'r')
# readline只能读取第一行代码,原理是读取到第一个换行符就停止。
f1_read = f1.readline(... |
54a7d6ac2c561d8d3518c53f617f4e18a478aa50 | jackcarter/MIT-ocw-hangman | /hangman.py | 3,574 | 3.84375 | 4 | # Name:
# Section:
# 6.189 Project 1: Hangman template
# hangman_template.py
# Import statements: DO NOT delete these! DO NOT write code above this!
from random import randrange
import string
import os
clear = lambda: os.system('cls')
# -----------------------------------
# Helper code
# (you don't need to understan... |
7d1378c3f16d76dd4ba06d6a6233daea00ec5cb3 | SethHWeidman/algorithms_python | /problem_solving_miller_ranum/05_search_and_sort/05_shell_sort.py | 932 | 4.03125 | 4 | from typing import Any, List
def shell_sort(a_list: List[Any]) -> None:
def gap_insertion_sort(a_list: List[Any], start: int, gap: int) -> None:
for i in range(start + gap, len(a_list), gap):
current_value = a_list[i]
position = i
while position >= gap and a_list[pos... |
36e365dbe265cf257524b4d232ca87efd93eacef | amit-raut/Project-Euler-Python | /pr37/pr37.py | 1,145 | 4.125 | 4 | #!/usr/bin/env python
"""
The number 3797 has an interesting property. Being prime itself it is possible to continuously remove digits from left to right and remain prime at each stage: 3797 797 97 and 7. Similarly we can work from right to left: 3797 379 37 and 3.
Find the sum of the only eleven primes that ... |
b0826bcc7dd69c1a178060b564e58bd214168cfc | love-adela/algorithm-ps | /acmicpc/1247/1247.py | 213 | 3.71875 | 4 | for _ in range(3):
n = int(input())
test_list = [int(input()) for _ in range(n)]
if sum(test_list) == 0:
print('0')
elif sum(test_list) > 0:
print('+')
else:
print('-')
|
13927366798d51dfe47c977d29d5359be18be3d2 | Chehlarov/Python-Advanced | /D04_Fast_Food.py | 496 | 3.890625 | 4 | from collections import deque
existing_food = int(input())
line = map(int, input().split())
customers = deque(line)
print(max(customers))
is_complete = True
while len(customers) > 0:
order = customers[0]
if order <= existing_food and is_complete:
existing_food -= order
customers.po... |
9de2d7796b52a9ebc8ac6e1e489ece8976ba1314 | Ana-geek/Incapsulyaciya | /lib.py | 1,190 | 4.25 | 4 | """
Разработайте ĸласс Book (Книга) и реализуйте в нем
-ĸонструĸтор объеĸтов,
-набор атрибутов,
-набор аĸсессоров,
-и метод __str__().
Для тестирования данного ĸласса создайте списоĸ из
5 ĸниг различных авторов, выведите на эĸран ĸонсоли
"""
# Создаем клас с инкапсуляцией
class Books:
def __init__(self, name: st... |
097ece95985da8fe86e46c4360549073bde20696 | guohaoyuan/algorithms-for-work | /python/进程/消息队列Queue.py | 1,033 | 3.953125 | 4 | """
Queue 为了实现进程间的通信
创建队列,指定长度
.put() 表示插值
.get() 表示取值
"""
import multiprocessing
# 1. 创建队列
queue = multiprocessing.Queue(5)
# 2. 插值
queue.put(1)
queue.put("hello")
queue.put([1, 2, 3])
queue.put((1, 2, 3))
queue.put({"a": 1, "b": 2})
# .put()如果超过长度,会进入阻塞状态, 且程序不会结束, 默认等待队列先取出值,再放入新的值
# queue.put("ghy")
# .put_... |
1f512ae623ce2084392b6e6b4aa8043e418d9bcc | ieee-saocarlos/ia-2019 | /exercicios-membros/Marco/Lista 2 - IA/E3L2.py | 807 | 3.828125 | 4 | # Faça um programa que a partir da lista [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] imprima:
# a) Uma lista com somente números pares.
# b) Uma lista com somente números ímpares.
# c) Uma lista inversa a lista inicial (sem uso de comandos prontos como reverse).
# d) Uma lista com somente números primos.
m=[1,2,3,4,5,... |
077f39ab0d1d67cd18c4d63424a017dfee64e3ed | bohdan-holodiuk/python_core | /lesson5/hw5/Is_this_my_tail.py | 1,062 | 4.09375 | 4 | """
Some new animals have arrived at the zoo. The zoo keeper is concerned that perhaps the animals do not have the right tails.
To help her, you must correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit!
... |
6483264d9da9caeb4085e3ee7a4ffc5124f3c9a0 | jdtully/coursera-python | /ishot.py | 173 | 3.984375 | 4 | tmp = input("what is the temp?")
temp = int(tmp)
def is_hot(tmp):
if temp > 70:
return(" its hot")
else:
return("its not")
print(is_hot(input))
|
074b877b4e4ba99d6a626b533416a15a63bfa3a0 | MattAllen92/Data-Science-Basics | /Practice and Notes/Code Wars/MTV Cribs.py | 837 | 3.546875 | 4 | def my_crib(n):
width = (n * 2) + 2
roof = []
house = []
for i in range(1, n+1):
roof_length = i*2 + 2
house_length = n*2 + 2
roof_buff = " " * int(buffer(width, roof_length))
house_buff = " " * int(buffer(width, house_length))
if roof == []:
... |
9f37209e3563b2d61f1d85b1d59a633cdf6c27e5 | namanshah01/mini-projects | /Text Encrypt-Decrypt/encrypt.py | 965 | 3.5625 | 4 | import sys
import os
import random
# switching to current running python files directory
os.chdir('\\'.join(__file__.split('/')[:-1]))
# handling possible errors
fname = input('Enter name of text file: ')
if fname.split('.')[-1] != 'txt':
print('Please enter the name of a text file')
sys.exit()
if not os.path... |
ea468d381a28e97b5a5706d60e6419aa50772fee | vitroid/PythonTutorials | /PythonSamples/NodeBox/sympl.py | 1,259 | 4.03125 | 4 | from math import * #sqrt()関数のために必要。
speed(30)
size(400,400)
def circle(x,y,r):
oval(x-r,y-r,r*2,r*2)
def setup():
#力学変数はみんなsetup()で初期化し、
#draw()関数と共通に使えるようにする。
global x,y,vx,vy,Dt,k,m,fx,fy
x = 0.0
y = 0.0
vx = 0.0
vy = 0.0
Dt = 0.1
k = 1.0
m = 1.0
fx = 0.0
fy = 0.0... |
171ec03333c9ab4ad43cdd57d59b2a65f5802364 | keinam53/Zrozumiec_Programowanie | /If_else.py | 3,119 | 4 | 4 | # name = input("Jak masz na imię? ")
# print("Miło mi Cię poznać", name)
# if len(name) >= 7:
# print(f"{name} to całkiem długie imię")
# if len(name) < 7:
# print(f"{name} to krótkie imię")
# age = int(input("Ile masz lat? "))
# if age < 18:
# print("Nie możesz jeszcze głosować")
# if age >= 18:
# pri... |
06821247b1de68ca4532de747f74c7fff087edab | rafaelperazzo/programacao-web | /moodledata/vpl_data/330/usersdata/303/93582/submittedfiles/lista1.py | 431 | 3.671875 | 4 | # -*- coding: utf-8 -*-
valores=(int(input('Digite a quatidade de valores:')))
a= []
contpar=0
contimpar=0
somapar=0
somaimpar=0
for i in range (0,valores,1):
a.append(int(input('DIGITE UM NUMERO:')))
for i in range (0,valores,1):
if a[i]%2==0:
contpar+=1
somapar+=a[i]
else:
c... |
fa5357d2a443d88dbb33e2574ed9f27963149bab | followfellow/GS1 | /aa.py | 1,228 | 3.53125 | 4 | from random import randint
from ctypes import *
import time
import os,sys
user32 = windll.LoadLibrary('user32.dll')
def check():
t = 0
while True:
try:
str_num = input("guess number(0~100)")
num = int(str_num)
break
except:
t += 1
if t... |
e155eba699cefa0d39f21a9011668a20f2387f3d | Techne3/Intro-Python-II | /examples/rps.py | 1,471 | 4.21875 | 4 | import random
# Create a rock paper scissors game in Python
# Player should be able to type r, p, or s
# Computer will pick r, p or s
# Game will print out the results and keep track of wins, losses and ties
# Type q to quit
# Build a REPL
choices = ["r", "p", "s"]
wins = 0
losses = 0
ties = 0
# Define a func... |
9962cceb0a6790113028b80be28940540f6acf37 | alamathe1/Algorithms | /python/mergeSort.py | 937 | 4.34375 | 4 | def mergeMain(left, right, arr):
i = 0
j = 0
k = 0
# when i and k both have elements in them
while (i < len(left) and j < len(right)):
if left[i] <= right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
... |
d4a10914aa8db838b9880e03bca58aa91192ba91 | amath0312/py100 | /day17/sample.py | 3,068 | 3.578125 | 4 |
import time
from functools import wraps
from threading import Lock
# 装饰器
def record_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
print('in wrapper record_time')
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f'{func.__name__} => {... |
6856abdb3e57c0d3d9adc6a1d078e7c8a25b8a4d | DollaR84/spider | /checker.py | 1,517 | 3.703125 | 4 | """
Module contain functions with check rules for playing cards.
Created on 26.10.2018
@author: Ruslan Dolovanyuk
"""
from constants import Cards
def change_color_suit(card1, card2):
"""Check change suit two cards."""
if card1.suit in Cards.black_suits:
return True if card2.suit in Cards.red_suits... |
defaf77399fe5eca330e20c23e7e928dcd6b23d0 | Neural-network-assignement/Problem-solving-curve-fitting | /2) XOR/sanstitre0.py | 4,088 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 10 16:39:49 2019
@author: Tim
"""
import numpy as np
# This implementation of a standard feed forward network (FFN) is short and efficient,
# using numpy's array multiplications for fast forward and backward passes. The source
# code comes with a little exam... |
625fb4f68e015e8658402f51a40afa6376aa8686 | elruizz/AdvPy-eRuiz | /Assignmnents/Project_1/OneChickenPerPerson/onechicken.py | 921 | 3.828125 | 4 | #! /usr/bin/env python3
import sys
def answer(a, b):
ans = ''
if a > b:
x = a - b
if x == 1:
ans = 'Dr. Chaz needs 1 more piece of chicken!'
return ans
else:
ans = 'Dr. Chaz needs '+ str(x) + ' more pieces of chicken!'
return ans
else:
x = b - a
if x == 1:
ans = 'Dr. Chaz will have 1 piece o... |
3666997fa6a38d2fcbacd3a6b2db9c4485f77d24 | carlos2020Lp/progra-utfsm | /certamenes/2012-1-certamen-1/edad/solucion.py | 550 | 3.796875 | 4 | ano = int(raw_input('Ano: '))
mes = int(raw_input('Mes: '))
dia = int(raw_input('Dia: '))
if mes < 5 or (mes == 5 and dia < 10):
edad_anos = 2012 - ano
else:
edad_anos = 2011 - ano
if dia <= 10:
edad_dias = 10 - dia
if mes <= 5:
edad_meses = 5 - mes
else:
edad_meses = (12 + 5) - me... |
d793d8585b0375efa6a2326914b24b2851c5ac37 | DL2021Spring/CourseProject | /data_files/814 Binary Tree Pruning.py | 621 | 3.5625 | 4 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from typing import Tuple
class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
root, _ = self.prune(root)
return root
def prune(self, node) -> Tuple[TreeNode, b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.