blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e667ade01db55a75fdf5cdea204453f0eafe11ff | lissabet/binsearch | /task1-2.py | 527 | 4.09375 | 4 | def findindex(array,element):
if element in array:
return array.index(element)
else:
return None
def binsearch(array,element):
if element in array:
begin = 0
end = len(array)-1
middle = int(end/2)
while array[middle] != element and begin < end:
i... |
5ef5262f13509aafa901bbd4f01befccdb465678 | ashishsubedi/n_queens | /lib/algorithm.py | 1,626 | 3.65625 | 4 | import os
import time
clear = lambda: os.system('clear') #Clear terminal
slow_rate = 0.001
def init(n,show_steps=False,delay=0):
global slow_rate
slow_rate = delay
clear()
x = [-1]*n
if show_steps == False:
print('Solving... Please wait')
if solve(0,n,x):
return x
... |
bab2a406a3484bd5ff93d6f81a2da8e41cbf589e | pestana1213/LA2 | /treino/soma.py | 1,229 | 3.921875 | 4 | """
Implemente uma função que calula qual a subsequência (contígua e não vazia) de
uma sequência de inteiros (também não vazia) com a maior soma. A função deve
devolver apenas o valor dessa maior soma.
Sugere-se que começe por implementar (usando recursividade) uma função que
calcula o prefixo de uma sequência... |
9ac087167ba0a797b686281abad31f68273b3dd7 | nguyenbac5299/LearnPython | /function/scope rule.py | 427 | 3.65625 | 4 | # 1- start with local
# 2- parent local?
# 3- global
# 4- built in python function
# global keyword
total = 0
def count():
global total
total+= 1
return total
def count(total):
total+= 1
return total
print(count(count(count(total))))
# nonlocal
def outer():
x='local'
def inner():
... |
be50147266e3776459fcab48ea7d4bfc5c594ce6 | juancsosap/pythontraining | /training/c11_exceptions/e07_error_applied.py | 253 | 3.921875 | 4 | def is_int(text):
try:
int(text)
return True
except:
return False
if __name__ == "__main__":
num = input('Number: ')
if(is_int(num)):
print('Result:', int(num)**2)
else:
print('Invalid Input') |
e2a7e1dbc6b4a031796f10ebff9cbff13667ed10 | saloni-080601/list.py | /calculationinloop.py | 364 | 3.890625 | 4 | print("1.add", "2.substraction" , "3.multiplication" , "4.division")
a=int(input("enter a number"))
b=int(input("enter a number"))
c=input("enter a number")
if c=="1":
sum=a+b
elif c=="2":
sum=a-b
elif c=="3":
sum=a*b
elif c=="4":
sum=a/b
else:
print("invalid")
i=0
while i<=sum:
... |
40f21070349e79cdcba0f114e4b055f0c35687f4 | StarFighter156/Kannan | /Source/time.py | 301 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 12 21:03:21 2021
@author: Kannan
"""
class Time():
def __init__(self):
self. real = True
def days_to_seconds(self, days):
return days*24*60*60
def second_to_days(self,seconds):
return seconds/(60*60*24) |
61b43d99e1de608bbc217abe9e14ed24e7a9c452 | Nisha16/leetcode | /island.py | 1,290 | 3.515625 | 4 | def search(i, j, grid, mark):
mark[i][j] = False
if i+1 < len(grid) and grid[i+1][j] == 1 and mark[i+1][j] == True:
search(i+1,j,grid,mark)
if j+1 < len(grid[0]) and grid[i][j+1] == 1 and mark[i][j+1] == True:
search(i,j+1,grid,mark)
if i-1 >= 0 and grid[i-1][j]... |
202ca980211baee4d34ad01c872eb2f09ced6b7e | ramtiwary/week_1 | /tuple_colon.py | 267 | 3.828125 | 4 | # Tuple colon
from copy import deepcopy
tuplex = ["Hi",10,[],True]
print(tuplex)
tuplex_colon = deepcopy(tuplex)
tuplex_colon[2].append(40)
print(tuplex_colon)
# repeated Item in Tuple
tuplex = 2,1,2,3,4,2,5,3,3,3
print(tuplex)
count = tuplex.count(3)
print(count)
|
74716c07d2745cdd730ee5b6191a0df6b5605cb3 | ManiSrinivasa1999/codingame-sol-python | /code_busters.py | 5,400 | 3.9375 | 4 | """Optimize the number of ghosts caught by busters
"""
import random
import math
IDLE = 'idle'
CAN_CATCH = 'can_catch'
HAS_GHOST = 'has_ghost'
SEE_GHOST = 'see_ghost'
def calculate_next_point(buster):
"""Returns the next point buster will move to in the current direction
Args:
buster(dict): Info regarding buste... |
e49a9eeafeb7d23738c36a16359feacddd04a2be | joeyzhouyuanli/python_exercise | /bmi.py | 227 | 3.96875 | 4 | height=1.75
weight=80.5
bmi=float(weight/(height*height))
print(bmi)
if bmi<18.5:
print('too slim')
elif bmi<25:
print('normal')
elif bmi<28:
print('overweight')
elif bmi<32:
print('obessity')
else:
print('sever obessity') |
0271005920bfe4bd2a6938be32f4e3535af7ae52 | EviBoelen15/Schooloedeningen | /Hogeschool/Bachelor/Semester 1/IT Essentials/Oefeningen en code/Oefeningen/Oefeningen/ITEssentials(ilias 1TINC)/5_functies/cursus/opgave5_2.py | 795 | 3.734375 | 4 | def print_rechthoek(aantal_rijen, aantal_kolommen, teken):
for i in range(1, aantal_rijen + 1):
for j in range(1, aantal_kolommen + 1):
print(teken, end=" ")
print()
def print_lijn(aantal_tekens, teken):
for i in range(1, aantal_tekens + 1):
print(teken, end=" ")
print(... |
290c390daba49d5e7343c47528a1acefbc9287e2 | DavidGugea/Data-Structures | /Data structures ( code in python )/Linear Data Structures/Stack ( Python Code )/Tutorials and tests/Stack_ReverseString.py | 1,297 | 4.03125 | 4 | import pprint
class Stack(object):
def __init__(self):
self.items = list()
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return not self.items
def peek(self):
if self.items:
return sel... |
deaf6ad85c2e36f2c8eb30397a31caf4ad3c7cb1 | gjwei/algorithms | /MS_Beauty_of_code/gcd.py | 174 | 3.828125 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
#Author: gjwei
def gcd(a, b):
if a < b:
return gcd(b, a)
if b == 0:
return a
return gcd(b, a % b)
|
9f7b7e87116ae5c1fca16b863689a2d7d857cdf6 | jayeom-fitz/Algorithms | /CodeUp/Python기초100/6065-6070[기초-조건]/6066-정수 3개 입력받아 짝-홀 출력하기.py | 373 | 3.953125 | 4 | """
CodeUp
6066 : [기초-조건/선택실행구조] 정수 3개 입력받아 짝/홀 출력하기(설명)(py)
https://www.codeup.kr/problem.php?id=6066
"""
a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
if a%2==0 :
print("even")
else :
print("odd")
if b%2==0 :
print("even")
else :
print("odd")
if c%2==0 :
print("even")
else :
print("odd")... |
81fbef890866509bae2bc1f2215934c6793e1466 | wolfofsiliconvalley/pythonwavass. | /Labs/Lab2of1.py | 217 | 4.125 | 4 | # assigning values to variables
fname = Franklin
age = 20
# writing a print statement using .format() to print out a sentence
txt1 = "My name is {fname}, I'm {age}".format(fname = "Franklin", age = 20)
print(txt1)
|
ff580f8a1b52e09a2d7797cad64b89e2ce60d02a | RounakChatterjee/Assignemet | /modifed_fibo.py | 187 | 3.84375 | 4 | def fibo(n):
b = 1
a = 0
c = 0
print("first ",n," Fibonacci numbers are: \n\n",a,"\n\n",b)
for i in range(n-2):
c = a+b
print("\n",c)
a = b
b = c
c = 0
fibo(100) |
1451549a6abe09413c6623864ce3e81b51690458 | AhmadAymanBahaa/Optimization-Approaches-on-01-Knapsack- | /genetic.py | 3,156 | 3.875 | 4 | import random
import math
# Size of initial population filled with some permutation of 0s and 1s
POPULATION_SIZE = 50
# Maximum number of generations the algorithm will run
MAX_GENERATION_SIZE = 200
# Start initial population with only zeros? If not, random permutation of 0s and 1s will be given
# Starting with 0s an... |
f5a7c4746de09e09bea9757e36066adcc6e0a04d | emanuelcarlan/uri | /u1010.py | 165 | 3.6875 | 4 | numero=int(input())
horas=int(input())
valor=float(input())
salario=float(horas)*(valor)
print('NUMBER = {}'.format(numero))
print('SALARY = {:.2f}'.format(salario)) |
eb8ab39f69e6a85001c8520ab1254ff36eaff459 | acroyear23/fail2ban-logReader | /programFunctions.py | 2,784 | 3.71875 | 4 | import os
# local modules
from Sqlite3Class import *
import interface
# Function to print Column header for terminal views
def print_header():
print("[#] "
"[HOST_IP] [DATE] [TIME]"
" [MESSAGE] [SERVICE]"
" [BAN] [OFFENDER_IP]")
# Choice function on main.... |
0c55606f80bb99f12a1d025dcdc6a3988ff749d2 | mmlcasag/mva_python | /00_about_the_course.py | 3,565 | 4.34375 | 4 | # Introduction to Programming with Python
# Microsoft Virtual Academy
# Christopher Harrison
# Susan Ibach
# 12 hours
#
# Available at:
# http://aka.ms/intropythoncode
# http://aka.ms/introprog-python
# https://www.youtube.com/watch?v=3cZsjOclmoM
# https://mva.microsoft.com/en-US/training-courses/Introduction-to-Progra... |
dc9b0a5839e762c94c10006851b281e28a968133 | kaamesh17/Assignment | /distinct.py | 280 | 3.578125 | 4 | def distinct(s):
d = ''
for i in range(len(s)):
if (indexOf(s[i],d)==-1):
d = d+s[i]
return d
def indexOf(c,s):
r = -1
for i in range(len(s)):
if (c==s[i]):
return i
return r
print(distinct("hello")) |
43f583a077608feae7b40e43c271422fc4573263 | TomJamesGray/data_types | /queue_arr.py | 1,379 | 3.84375 | 4 |
class Queue(object):
def __init__(self,vals,n=10):
self.queue = [None for x in range(n)]
self.head = -1
self.tail = -1
for val in vals:
self.add(val)
def add(self,val):
if (self.tail+1) % len(self.queue) == self.head:
print("Queue full")
... |
c68238c9583c69249590be32b37fdc594549c590 | IDontKnowWhoAmI-T/PythonLab | /homework3.py | 523 | 4 | 4 | Students = {
'Tom':{
'name':'Tom1',
'Surname':'King',
'email':'TomasThe@Train.ru'
}
'Alice':{
'name':'Alice1',
'Surname':'Williams',
'email':'Alice@InWonderland.ru'
}
'Harry':{
'name':'Harry1',
'Surname':'Potter',
'email':'HarryPotter@TheMage... |
34a73e1da391c3dcd7b6bd3e0b46c6d3a0de2648 | shiqi0128/My_scripts | /python_study/myself_test/homework/homework_0323.py | 2,484 | 3.90625 | 4 | # """
# -------------------------------------------------
# @Time : 2020/3/24 20:33
# @Auth : 十七
# @File : homework_0323.py
# @IDE : PyCharm
# @Motto: ABC(Always Be Coding)
# @Email: 1941816343@qq.com
# -------------------------------------------------
# """
# # 一、必做题
# # 1.列表中append和extend方法的区别,请举例说明
# # ... |
96d2d17d3b3b92da8e0a8969eb5fa63b7c92b9b1 | guozhiqi14/Zhiqigit | /TowerOfHanoi.py | 229 | 3.59375 | 4 | #-*- coding:utf-8 -*-
def mov(n,A,B,C):
if n== 1:
print(A,'->',B)
else:
mov(n-1,A,C,B)
mov(1,A,B,C)
mov(n-1,C,B,A)
num = input("Input the number of tower:")
mov(int(num),'A','B','C')
|
5026644837b9a43902a6f4637b8106ec8f89485c | fabiomoreirafms/CES-22-Exercicios | /7-26-12.py | 410 | 4 | 4 | import turtle
alex = turtle.Turtle()
wn = turtle.Screen()
lista = [(90,100),(-30,100),(-120,100),(-75,100*2**0.5),(135,100),
(135,100*2**0.5),(-135,100),(-90,100)]
def turtle_draw (trajetoria,t):
"""Executa a trajetoria para a turtle t"""
for (ang,distancia) in trajetoria:
t.left(ang) # senti... |
98eb7bb3cfb7990f8518c446c84da7c6140b07c1 | mvillamea/Python-Exercises | /Other exercises/ordinal.py | 435 | 4.03125 | 4 |
#da el ordinal en inglés
def ordinal_suffix(value):
s = str(value)
if s.endswith('11'):
return 'th'
elif s.endswith('12'):
return 'th'
elif s.endswith('13'):
return 'th'
elif s.endswith('1'):
return 'st'
elif s.endswith('2'):
return 'nd'
elif s.ends... |
9f00197273d870631e9f15a88d8ac1307f8c3554 | xtreia/pythonBrasilExercicios | /03_EstruturasRepeticao/15_fibonacci_1.py | 337 | 4.03125 | 4 | termo = 0
while (termo <= 0):
termo = int(raw_input('Voce quer a serie de Fibonacci ate qual termo: '))
if (termo <= 0):
print 'O termo deve ser positivo!'
primeiro = 0
print primeiro
segundo = 1
for i in range(1, termo):
print segundo
terceiro = primeiro + segundo
primeiro = segundo
se... |
b0cffeab03330429af04be5fc091992954091942 | jaebradley/leetcode.py | /test_word_search_2.py | 741 | 3.71875 | 4 | from unittest import TestCase
from word_search_2 import Solution
class TestFindWords(TestCase):
def test_finds_subset_of_words(self):
found_words = Solution().findWords(
[
['o', 'a', 'a', 'n'],
['e', 't', 'a', 'e'],
['i', 'h', 'k', 'r'],
... |
6c24ab0b2921de6a261232447e386a61636ecb0c | Nori1117/Function-Argument- | /MyLogic.py | 694 | 4.15625 | 4 | #Write a python function, check_double(number) which accepts a whole number and returns True if it satisfies the given conditions.
#The number and its double should have exactly the same number of digits. Both the numbers should have the same digits ,but in different order.
#Otherwise it should return False. Example:... |
1b81c9896a8e4548dd445932a88a184b0d1e4821 | robgoyal/CodeChallenges | /HackerRank/Algorithms/Warmup/PlusMinus.py | 446 | 3.59375 | 4 | #!/usr/bin/env/python
# PlusMinus.py
# Code written by Robin Goyal
# Created on 10-08-2016
# Last updated on 10-08-2016
n = int(raw_input().strip())
arr = map(int, raw_input().strip().split(' '))
posNums = 0
negNums = 0
zeroNums = 0
for i in arr:
if (i > 0):
posNums += 1
elif (i < 0):
negNum... |
5e577691fa1cf8d21de1ed9cadcf24ee67438469 | ivyleavedtoadflax/kaggle-house-prices | /ml/ml/helper_functions/encoders.py | 437 | 3.640625 | 4 | import pandas as pd
def one_hot_encoder(df, one_hot_list):
'''
Takes a dataframe and a list of (categorical) variables as an input.
One-hot encodes a list of categorical variables, and returns a new
dataframe
'''
for col in one_hot_list:
df_1h = pd.get_dummies(df[col])
df_1h.... |
7b14659c6a28f3b6fdf2baf28e47e114c2557aa9 | sun0406/CTCI_problems | /CTCI_1_4.py | 665 | 4.125 | 4 |
def odd_counter(map1):
counter = 0
for value in map1.values():
if value%2 != 0:
counter += 1
if counter > 1:
return False
return True
def map_store(str1):
map1 = {}
for letter in str1:
if letter != ' ':
if letter not in map1.keys():
map1[letter] = 1
else:
map1[letter] += 1
return map1
... |
5e68232272e26ca25fe4f58fb1dc92e58829c0b5 | ZohanHo/ClonePPZ | /all python/lesson 7.py | 1,689 | 3.921875 | 4 | """"""
"""Цыкл while"""
i = 5
while i > 0:
print(i)
i -= 1
if i == 2:
break
print("Finish")
print ("-------------")
number = 23
running = True
while running:
guess = int(input('Введите целое число : '))
if guess == number:
print('Поздравляю, вы угадали.')
running = False #... |
5083b7c90cd90b800b343add877287e1f8aadfcc | AsmaMohammed1/100DaysOfCode | /Day27.py | 662 | 3.984375 | 4 | # Talk about Conditions and If statements
w = 'HI'
w1 = 'HI'
print('Yes') if w == w1 else print('No')
print("-- Ticket's Movies --")
print('\n\t1: Show Movies')
print('\t2: Exit')
UserInput = int(input('\nYour Choice:'))
while True:
if UserInput == 1:
print('\n\t Movies List:\n\t-1. The Bourne Identity.\n\t-2. Fear... |
4abf1d06927878fde63fb7e12dfa268b73e879d2 | danrodaba/Python_PixelBlack | /Python_PixelBlack/promerio.py | 395 | 3.921875 | 4 | print('Cálculo de la media de una serie de datos')
print('_________________________________________')
#iniciamos variables
suma=0
n=0
#leemos datos y los procesamos
x=float(input('Introduce un valor a la serie (0para finalizar): '))
while x != 0:
suma+=x
n+=1
x = float(input('Introduce un valor a la serie... |
b05664927cff6acb60c2cf3511336abc6689b749 | littlefattiger/My_LC_solution | /python/1.py | 401 | 3.546875 | 4 | # https://leetcode.com/problems/two-sum/submissions/
# very easy two sum and it test hash table, itetation, slide window
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
h = dict()
for i,v in enumerate(nums):
if target - v in h:
... |
57faea88533557036f7107c3f9090eeafcf18d47 | alexlepsky/dlcourse_ai | /assignments/assignment3/layers.py | 15,013 | 3.53125 | 4 | import numpy as np
def l2_regularization(W, reg_strength):
'''
Computes L2 regularization loss on weights and its gradient
Arguments:
W, np array - weights
reg_strength - float value
Returns:
loss, single value - l2 regularization loss
gradient, np.array same shape as W - gra... |
54ce3fc26077c7b3d1aa4890532b1358d252271a | hehuanshu96/PythonWork | /dailycoding/python_UI/ComplicatedHello.py | 3,124 | 3.53125 | 4 | """
Hello World, but with more meat.
更复杂一点的helloworld
"""
import wx
class HelloFrame(wx.Frame):
"""
A Frame that says Hello World
一个框架,显示hello world,还有其他的一些功能
"""
def __init__(self, *args, **kw):
# 调用父类(wx.Frame)的__init__函数
super(HelloFrame, self).__init__(*args, **kw)
# create a panel in the frame
pn... |
89fb2d4946aef1a9060412b24ba502dbf3e4b6ab | davidkellis/py2rb | /tests/basic/listcomp1.py | 179 | 3.84375 | 4 | a = [1,2]
[print("b:%s" % b) for b in a]
a = [(1,2) ,(2,4)]
[print("b:%s c:%s" % (b,c)) for b, c in a]
a = [(1,2,3) ,(2,4,6)]
[print("b:%s c:%s d:%s" % (b,c,d)) for b, c, d in a]
|
8d5f7c02b9e0461961b2075e653b0de0bc3d4699 | claudiodacruz/listasAPE | /Lista 04/lista04_08.py | 1,491 | 4.3125 | 4 | '''Faça um programa que armazene,em um vetor, um conjunto de nomes de pessoas. O programa deve permitir incluir
nomes no vetor e pesquisar por um nome existente e ainda listar todos os nomes.
MENU DE OPÇÕES:
1) Cadastrar nome
2) Pesquisar nome
3) Listar todos os nomes
0) Sair do programa
Digite sua escolha:___... |
7186784321e128381140429088784fb2e4a61d4c | todaboi/CodecademyPython3 | /Getting_Ready_for_Physics_Class.py | 1,008 | 3.5 | 4 | # Uncomment this when you reach the "Use the Force" section
train_mass = 22680
train_acceleration = 10
train_distance = 100
bomb_mass = 1
# Write your code below:
# point 1
def f_to_c(f_temp):
c_temp = (f_temp - 32) * 5/9
return c_temp
# point 2
f_to_c(100)
# point 3
def c_to_f(c_temp):
f_tem... |
5cb5f6c1609a41f1333614bafd6f977a433ce6f0 | nberger62/_GIS_Python | /Module_1/Scripts/Mod1_NBerger.py | 3,792 | 4.125 | 4 | # Step 5: Complete the comments section, below
##################################################
# Script name: Mod1_NBerger.py
# Author: Nathan Berger
# Email: nab45@students.uwf.edu
# Date: 5/18/2021
# Description:
##################################################
print("Step 1")
## Step 1 -> Print your last name... |
fca03195f1fa186fc07a14103158f1c15ae4f6c1 | shubhamTeli/PythonAutomationMachineLearning | /Assignment6_3.py | 892 | 3.9375 | 4 | class Arithmatic:
def __init__(self):
self.value1=0;
self.Value2=0;
def accept(self):
self.value1=int(input("Enter value1: "));
self.value2=int(input("Enter value2: "));
def Addition(self):
return self.value1+self.value2;
def Substraction(self):... |
1d8b3c2ac044301c0addb74681bced833a56d296 | OtacilioN/cesar-school-fp-lista-de-exercicios-02-OtacilioN | /questoes/questao_8.py | 2,037 | 4.34375 | 4 | ## QUESTÃO 8 ##
# Escreva um programa que leia uma data do usuário e calcule seu sucessor imediato.
# Por exemplo, se o usuário inserir valores que representem 2013-11-18, seu programa
# deve exibir uma mensagem indicando que o dia imediatamente após 2013-11-18 é
# 2013-11-19. Se o usuário inserir valores que represent... |
8a061570df60b36ec5e6d30254baa89519ac060a | demarcocarlosa123/datacampLearning | /Basico/comprenhension and Generators/Comprenhension_Dic.py | 270 | 3.921875 | 4 | pos = {num:-num for num in range(10)}
print(pos)
### A partir de una lista creo un diccionario.
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli']
dicFellowship = {elemento:len(elemento) for elemento in fellowship}
print(dicFellowship) |
a9c285a6e9499228639bce46f3f2c3669ba0f751 | CarolineFs/Python | /SOLVED/Years.py | 215 | 3.671875 | 4 | x=int(input('Введите год: '))
if x%4==0 and x%100!=0:
print ('год високосный')
elif x%400==0:
print ('год високосный')
else:
print ('год не високосый')
|
bc42d8dcef73a81968df04058b46f16dc4a6ddaa | Figfavture/shiyanlou-code | /jump7.py | 210 | 3.53125 | 4 | for a in range(1,100):
if a % 7 == 0:
print('jump7.1')
elif a % 10 == 7:
print('jump7.2')
elif a // 10 == 7:
print('jump7.3')
else :
print('a is:{}'.format(a))
|
f827937aea477d4a6d04cc4c5af5cd293b276b89 | wangbobby/dangdang | /1_to_3/1_to_3.py | 6,125 | 3.640625 | 4 | # apple_num = pear_num * 2
# every group needs 3 pear + 4 apple
# after pears are gone and now apple = 16
"""
x = group
total_fruit = x * ( 3 + 4) + 16
"""
# for group in range(1, 100):
# apple = 4 * group + 16
# pear = 3 * group
# if apple == pear * 2:
# print("Total group number is ", group)
#... |
a0cee7d7f780ba871551f2fd5b24df08e1d1dea5 | Android-Ale/PracticePython | /exercicio01/ex016.py | 248 | 3.75 | 4 | print('$'+'='*20+'$')
n = str(input('Coloque os valores da mega sena: ')).strip()
c = str(input('Digite um número que vc quer saber quantas vezes caiu: '))
#print('A numeração {} aparece {} vezes.'.format(c, n.count(c)+1))
print('$'+'='*20+'$')
|
c67ac824c651f302bddb21602c7c9f783fe07b36 | hareeshkr/simpleBMIApp | /app.py | 768 | 4.125 | 4 | import tkinter as tk
from tkinter import Text
root = tk.Tk()
root.title("Simple BMI Calculator")
weight = tk.StringVar()
height = tk.StringVar()
def calc():
weight = float(weight_entry.get())
height = float(height_entry.get())
bmi = weight / (height * height)
tk.Label(root, text="Your BMI is " + str(... |
8256a13d711ae4228d7a3cf3c4579897d8bed27f | anildn14/online_coding | /Codewars/Not_very_secure.py | 728 | 4.21875 | 4 | # In this example you have to validate if a user input string is alphanumeric. The given string is not nil, so you don't have to check that.
# The string has the following conditions to be alphanumeric:
# At least one character ("" is not valid)
# Allowed characters are uppercase / lowercase latin letters and digits ... |
b7021b563cb8505f9938eeee69b131ccac9de73b | guoyue01/python | /CMS-WEB/practice/test05.py | 533 | 3.796875 | 4 | '''
2018-09-06
题目:输入三个整数x,y,z,请把这三个数由小到大输出。
程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,
如果x>y则将x与y的值进行交换,然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。
'''
l=[]
for i in range(0, 3):
x = int(input('请输入数字:'))
l.append(x)
#冒泡排序
for i in range(0,3):
for j in range(i,3):
if l[i] > l[j]:
l[i], l[j] = l[j], l[i]
... |
a7005cfb38696e0af42e2dc724c877e003e735c8 | mozarik/quicksortPython | /quickSort.py | 1,951 | 4.0625 | 4 |
# Create random array
from random import randint
import array
def randomArray():
array_list = []
len_list = input("Banyak nya list : ")
i = int(len_list)
for x in range (i):
item_list = randint(1 , 100)
if item_list in array_list :
continue
int_item_list = int... |
38b58e8443c2b799e7c09bdcdc0cb0f414a12814 | zhangjun007/mypython | /Weeks4/高阶函数.py | 877 | 3.515625 | 4 | #!/usr/bin/python3
#Name:zhangjun
#Email:aceg452161724@qq.com
#Time:2018/9/4 15:14
# 高阶函数1:把一个函数名当作实参传值给另外一个函数(不修改被装饰函数的源代码,为其添加功能);
import time
def bar():
time.sleep(3)
print("in the bar")
def test(func):
start_time=time.time()
func() #此刻运行的实际是 bar 的功能
stop_time=time.time()
print("the func ... |
5e6869b150569167d34cb8b8ed62b177c49503de | gabriellaec/desoft-analise-exercicios | /backup/user_196/ch34_2020_03_31_00_39_20_973731.py | 332 | 3.546875 | 4 | def eh_primo (num):
i=2
if num == 2:
return True
elif num == 0 or num == 1:
return False
while i < num:
if num % i == 0:
return False
i = i+1
return True
def maior_primo_menor_que(n):
c=n
while n>1 :
if eh_primo(c):
return c
else:
return -1
c-=1
... |
db3128a5af54480dfaa6c1dc7680eb09885aec8f | MRtiwariji/CommonFileRover | /commonfiles.py | 750 | 4.3125 | 4 | print('''Remove Duplicate Files''')
import os
def remove_file():
MainFolder = r'{0}'.format(input("Copy & Paste the path of folder containing duplicate files")) #Main folder where all files some of them were duplicate
duplicatfiles = os.listdir(MainFolder)
ChosenFolder =r'{0}'.format(input("Copy paste the path of f... |
b9418c2c06c8a0282b33c79dd22c29cabe304c14 | Electrolink/python-electrolink | /modules/electroBoilerplate.py | 1,110 | 3.734375 | 4 | # Simple function, no returning values
def printValue(arg):
# Use variable here to name inocming elements from array
someParameter = arg[0]
print(someParameter)
# Function with returning value and error checking
def summing(arg):
a = arg[0]
b = arg[1]
c = None
try :
c = a+b
... |
db719751992624a8b7cdeeaf1e79142c1536a80f | arslanhashmi/datascience | /scraping-data/regex_/metacharacters.py | 765 | 3.578125 | 4 | import re
# meta characters --> .^$*+{}[]\()
#regex = re.compile('a')
#regex = re.compile('[abc]')
#regex = re.compile('[a-zA-Z]') # match
regex = re.compile('[^a-zA-Z]') # donot match ( compliment )
print (regex.match('2'))
r = re.compile('[a*]')
print (r.match ('aaaaaaaaaaaaaaaaaaaaaaaaa'))
r = re.compile('[a-c]*'... |
30680b1dc1997bd9d34eff48fc47a01a56d6e507 | himanshuks/python-training | /basics/inputOperation.py | 247 | 3.9375 | 4 | # Take multiple inputs from single line using SPLIT function
z = [
int(x) for x in input("Enter numbers separated by space to create list : ").split()
]
print(z)
sum = 0
for val in z:
sum += val
print("The sum of all elements :", sum)
|
772271882a27bb4d660e2af47ab455b585e846a3 | Ruymelo10/CursoemvideoPy | /exercicios/mundo2/ex52.py | 266 | 4.03125 | 4 | num = int(input('Digite um numero: '))
bool = True
for i in range(num,0,-1):
if i!=num and i!=1:
if num%i==0:
bool=False
if bool == False:
print('O numero {} não é primo'.format(num))
else:
print('O numero {} é primo'.format(num)) |
aedbd4fb6a3e53823d88d62445dedd1a735c7baa | Nikx999/AdA | /Binary_linear_time.py | 657 | 3.890625 | 4 | def binarySearch (arr, l, r, x):
if r >= l:
mid = l + (r - l) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, l, mid-1, x)
else:
return binarySearch(arr, mid + 1, r, x)
else:
return -1
def linea... |
d9765abe8c109cf5261ae1b70a32f7ca6e2d2795 | mitul3737/My-Python-Programming-Journey-from-Beginning-to-Data-Sciene-Machine-Learning-AI-Deep-Learning | /Python diye Programming sekha 3rd/Page 31.py | 2,368 | 3.53125 | 4 | def average(L):
if not L:
return None
return sum(L)/len(L)
def test_average():
test_cases=[
{
"name":"simple case 1",
"input":[1,2,3],
"expected":2.0
},
{"name":"simple case 2",
"input":[1,2,3,4],
"expected":2.0
... |
9b43159e83b0d4b6fe21a359723cfbbd074d0df4 | yenng/UnitConverter | /unit_converter.py | 4,878 | 4.34375 | 4 | """
0. Number system
1. Temperature
2. Weight
3. Length
4. Area
5. Angle
"""
def get_type(unit_type):
"""Return the unit types with user's choice"""
# Create a dictionary with unit types.
type_dir = {
0: ["Dec", "Bin", "Hex", "Oct"],
1: ["Celsius(°C)", "Fahrenhe... |
1f263afc50b89a210696b1a3fa59e2f328d73876 | vmarcella/CS13 | /Code/hashtable.py | 18,035 | 4.125 | 4 | #!python
from linkedlist import LinkedList
class HashTable(object):
def __init__(self, init_size=8):
"""Initialize this hash table with the given initial size."""
self.buckets = [LinkedList() for i in range(init_size)]
self.size = 0 # Number of key-value entries
def __str__(self):
... |
7fc9c8deb093d4383d8417810096590dcc8f01a9 | hansx7/AI | /Lab6_BPNN/BPNN_Dataset/ttt.py | 171 | 3.59375 | 4 | import math
print "The output after 1 iteration(s):",
print 1/(math.pow(math.e,-2)+1)*2
print "The output after 2 iteration(s):",
print 1/(math.pow(math.e,-1.84)+1)*2*0.33 |
a468451be5d423034d373b02ef101c03151335f2 | TOM-SKYNET/AL_NIELIT | /NLP/Day7_Dec13/q3.py | 1,451 | 3.859375 | 4 | """
Create a few sentences . Find the frequency count of the words in the vocabulary.
2. Cluster the words in the sentences based on the count.
4. Visualise the results.
"""
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
from sklearn.feature_extraction.text import TfidfVector... |
e30abd99cf7e5e91f6e0e760a7a8d16ee20cad7a | GunnerX/leetcode | /剑指offer/面试题32 - III. 从上到下打印二叉树 III.py | 1,808 | 3.921875 | 4 | # 请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
#
#
#
# 例如:
# 给定二叉树: [3,9,20,null,null,15,7],
#
# 3
# / \
# 9 20
# / \
# 15 7
# 返回其层次遍历结果:
#
# [
# [3],
# [20,9],
# [15,7]
# ]
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-... |
270cf49fdf71cca6078b240cde7e733b81038440 | WDongYuan/NLP_Project | /nltk_wordnet.py | 1,704 | 3.546875 | 4 | from __future__ import print_function
from nltk.corpus import wordnet as wn
from sets import Set
import nltk
# syn = wn.synsets("Shanghai")
# print(syn)
# for lemma in syn[0].lemmas():
# print(lemma.name())
# # for synset in syn:
# # print(synset)
# nltk.help.upenn_tagset('RB')
# tokens = nltk.word_tokenize("He takes... |
69247fea4ac00854ab9d36bd632dfaae114cac40 | chuck1l/assignment_process | /src/code_validations.py | 3,147 | 3.5 | 4 | import numpy as np
import pandas as pd
def validated_codes(data, pu_state_filter, regional_granularity, con):
'''
This function takes in the ranking data from each regional granularity
and checks the zip, city or county codes against the codes that currently
exist in LCAD. The data file is returned wi... |
c40f327209a76004197b0e6fac74e7daf6ae3105 | SirChao/School_Projects | /Python Othello Player/nkc2116.py | 3,402 | 3.765625 | 4 | from engines import Engine
from copy import deepcopy
class StudentEngine(Engine):
""" Game engine that implements a simple fitness function maximizing the
difference in number of pieces in the given color's favor. """
def __init__(self):
self.alpha_beta = False
def get_move(self, board, color,... |
d6f3a2bff4e543212bba73348a8e86ba63e66998 | bossk-ig88/SecureSet-stuff | /Python/Labs/SSF/magic8.py | 286 | 3.625 | 4 | import random
choices=("Stay classy", "Loud Noises!", \
"I have a headache", "Cannot predict now", "Great story...compelling and rich", \
"Ask again later", "Yes", "No", "Thanks for stopping by", \
"James Westfall", "Dr Kenneth Noisewater")
value = random.randint(0,len(choices)-1)
print(choices[value])
|
46d62f385da3762becb40cbdedb82fa2798633f3 | rohitvish30/CSE-587-Big-Data-Processing-with-Hadoop | /Part 1/mapper1.py | 1,195 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[15]:
import nltk
#nltk.download("stopwords")
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import re
import sys
import os
def text_preprocess(word):
stop_words = set(stopwords.words('english'))
word = word.lower() # making all the lette... |
f34cf352004e66f7ced34484f3186a19f3127855 | YijiangNemo/Python | /Quiz/quiz_8-2.py | 12,047 | 3.6875 | 4 | # Randomly fills a grid of size 10 x 10 with 0s and 1s,
# in an estimated proportion of 1/2 for each,
# and computes the longest leftmost path that starts
# from the top left corner -- a path consisting of
# horizontally or vertically adjacent 1s --,
# visiting every point on the path once only.
#
# Written by *** and ... |
469254103a7a9e3b6f8a3117f401008f54dd1f0f | JimBaumgartner/Python-Fundamentals | /challanges/loops_challenge.py | 545 | 3.609375 | 4 | puzzle = open('frequencies.txt', 'r').read().split("\n") # "\n" means new line
numbers = [int(i) for i in puzzle]
# what is ther final frequency
# #this challenge is to find out the final location of the person,
# starts at 0, then -18, +4 etc ( these numbers are in the txt functions)
final_step = 0
for each_item i... |
0c0f1c1a96867ecf57b7d8b7ec7e62428fcbaefe | sameerkitkat/geeksforgeeks | /bit_wise_operators/check_power_of_two.py | 201 | 4.1875 | 4 | def checkPowerofTwo(num):
#check value of num&(num-1)
if (num &(num-1) == 0):
print("number is power of two")
else:
print("number is not power of two")
checkPowerofTwo(15)
|
7314fcd2cc8714f80337bb2f7cdc5ccb26e1531f | febinstephen/Python-Practice-Book | /chapter2/prob17.py | 120 | 4.375 | 4 | #program to print lines of a file in reverse order.
f = open("foo.txt",'r')
for i in reversed(f.readlines()):
print i
|
282310abf7989ec4dc511be11243dc78e0a6eda3 | paribello/spellingBeeSolver | /solveSpellingBee.py | 238 | 4.1875 | 4 | import sys
from nltk.corpus import words
letters = sys.argv[1]
allWords = words.words()
requiredLetter = letters[0]
for word in allWords:
if(requiredLetter in word and (all(x in letters for x in word)) and len(word) >= 3):
print(word) |
936c3e853f28646bd46c6e07b753c9e8943b4dc9 | nvkreddy07/EE2703 | /EE2703_ASSIGN4_EE19B100.py | 4,974 | 3.5 | 4 | """
EE2703 Applied Programming Lab
Nallagari Varun Kumar Reddy
EE19B100
Assignment-4
"""
#Importing numpy and matplotlib
from pylab import *
from scipy.integrate import quad
def periodic(a, b):
interval = b - a
return lambda f: lambda x: f((x - a) % interval + a)
#Function cos(co... |
a78fc543eed4957b29a2974c70cd724442a77a10 | felipefoschiera/Competitive-Programming | /URI Online Judge/Iniciante/1983 - O Escolhido/nota.py | 329 | 3.734375 | 4 | quant_alunos = int(input())
dados = []
maior_nota = matricula = 0
for _ in range(quant_alunos):
num, nota = input().split()
num, nota = int(num), float(nota)
if nota > maior_nota:
maior_nota = nota
matricula = num
if maior_nota < 8.0:
print("Minimum note not reached")
else:
print(m... |
dd7493e16fd5e466a5f38767571131f66f783371 | olehb/ita3 | /sorting/binary_search.py | 319 | 3.703125 | 4 | def binary_search(a, v, start, end):
if end < start:
return start
m = (start+end) // 2
if a[m] == v:
return m
elif v < a[m]:
end = m-1
else:
start = m+1
return binary_search(a, v, start, end)
if __name__ == '__main__':
a = [4, 5, 6, 8, 9]
b = binary_search(a, 5, 0, len(a)-1)
assert b == 1
|
8a66bf585d46a3d65a4c7f66a454ab92f06b9720 | RowleySanchezm/Yr12ComputerScience | /Encryption and decryption/Caesar cipher decryption program.py | 558 | 4.0625 | 4 | #Caesar Cipher decryption program
### SRC - This is neat and simple, but I did get "n" for space.
def decrypt(cipher_text,s):
result = ""
for i in range(len(cipher_text)):
char = cipher_text[i]
#Next i
if (char.isupper()):
result += chr((ord(char) - s-65) % 26 + 65)
e... |
850573c01f4564a72eddaa7b2090169bb69e631e | luiz-pr/enter_to_site | /main.py | 5,959 | 3.515625 | 4 | # This is my library with Python
# Esta é a minha Biblioteca em Python
# これは私のPythonライブラリです
from selenium import webdriver
import time
import pyttsx3
# entrar no site Em portuges brazileiro
class entrarPt():
def __init__(self) :
engine = pyttsx3.init()
voice = engine.getProperty('voices')
... |
7d48738ad18f212be43a3f2344597bdd3cf20262 | YArek-VAdiLA/homwor_Yarik | /home_work5.py | 61 | 3.5625 | 4 | name=(input("ведите имя "))
s=name.upper()
print(s)
|
ed2b11c6eff1d5351b7734dc1ae08513aaf957a5 | aishwarya-agrawal/Python-programs | /mergesort.py | 749 | 3.5 | 4 | a = [310,285,179,625,351,423,861,254,450,520]
b = [0]*len(a)
def mergesort(_self,l,h):
if(l<h):
mid = (l+h)/2
mergesort(l,mid)
mergesort(mid+1,h)
merge(l,mid,h)
else :
return
def merge(_self,low,mid,high):
h=low
i=low
j=mid+1
while((h<=mid) a... |
e235be4087bbd71c163bbebbf8e90432f5e4b8a1 | ZyWang666/Semi-supervised-Text-Classification | /A2_256_sp19/classify.py | 990 | 3.734375 | 4 | #!/bin/python
def train_classifier(X, y,ws):
"""Train a classifier using the given training data.
Trains logistic regression on the input data with default parameters.
"""
from sklearn.linear_model import LogisticRegression
#from sklearn.model_selection import GridSearchCV
#param_grid = {'C': [0.001, 0.01, 0.1,... |
39a45599e7922fad91a9779e9e35e42a60ff0d15 | sridevpawar/AlgoRepo | /CodeingQuestions/CodeingQuestions/reverseWords.py | 469 | 3.75 | 4 | def reverseWords(str):
res = ""
for i in reversed(range(len(str) - 1)):
if str[i] == ".":
res += push(i + 1, str)
if str[0] != ".":
res += push(0, str)
return res[1:]
def push(index, str):
res = "."
while(index < len(str) and str[index] != "."):
res += str[... |
0f433e70f27528ff08f161a734c188814bd4a9e6 | yoma75/ejemplos-python | /for_and_while.py | 1,232 | 4.0625 | 4 | # For: permite recorrer cada uno de los elementos
frutas = ['banano', 'pera', 'uvas', 'melocoton']
for fruticas in frutas:
if fruticas == "uvas":
break # banano, pera, porque se cumple la condicion de arriba y deja de imprimir el resto de elementos
print(fruticas)
print('----------------------------... |
2fa7d4b80c5df5a4bbbff749d4ecfc9c34950fa8 | xrr314/python | /01-python基础/2-oop/01.py | 525 | 3.578125 | 4 | '''
定义一个学生类,用来形容学生
'''
# 定义一个空的类
class Student():
pass
# 定义一个对象
mingyue=Student()
# 定义一个类,用来描述python学生
class PythonStudent():
# 用None给不确定的值赋值
name = None
age = 18
course = 'python'
def doHomework(self):
print('在做作业')
# 推荐在函数末尾使用return语句
return None
yueyue = PythonStud... |
35321357b8b2175a71a380e754fd0f6acc7d7b57 | tcandzq/LeetCode | /TwoPointer/ContainerWthMostWater.py | 1,761 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/10/27 18:44
# @Author : tc
# @File : ContainerWthMostWater.py
"""
题号11 盛最多水的容器
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图片请参考:https://leetcod... |
446c47473d76368611561f9aaa1a8f4bb76a4ab2 | Fendo5242/Semana-8 | /semana8/semana8-7.py | 161 | 4.03125 | 4 | divisor=1
n=int(input("Ingrese un número:"))
while divisor<=n:
resto=n % divisor
if resto == 0:
print(divisor)
divisor = divisor + 1
|
38396317d817541265ff9532a6774d2600cdd955 | traceyt/ubtech | /evan.py | 1,260 | 3.96875 | 4 | import btnlib as btn
import ledlib as led
import time
#the led.startup() function cycles through the leds
#led.startup()
time.sleep(1)
print("Hello")
#to turn on all leds, use the led.turn_on_all() function:
led.turn_on_all()
time.sleep(2)
#to turn off all:
led.turn_off_all()
time.sleep(1)
led.turn_off_all()
time.sle... |
ce209119eae3ee14b9991047fef427545fb30b08 | babyfaceEasy/Algorithms | /algorithms/graphtheory/EulerianDirectedPathAdjacencyList.py | 4,180 | 3.671875 | 4 | '''
Implementation of finding an Eulerian Path on a graph. This implementation
verifies that the input graph is fully connected and supports self loop and
repeated edges between nodes.
Time Complexity : O(E)
@author Olakunle Odegbaro, oodegbaro@gmail.com
'''
from collections import defaultdict
class Graph(objec... |
01c6c06f6f4e4e988230ee6b22edb32098fd9854 | GelouKaroll/LPy_day2 | /homework1_1.py | 639 | 4.09375 | 4 | def age_detector(in_age):
if in_age.isdigit():
in_age = int(in_age)
if in_age <= 0:
return "Please insert your reale age"
elif 0 < in_age <= 7:
return "go to the kindergarten!"
elif 7 < in_age <= 18:
return "you are only schoo... |
b958d8d6473c5808154a0c41c6bc2774f8842f44 | atan59/A01175168_1510_assignments | /A4/question_7.py | 902 | 3.90625 | 4 | """Refactor code."""
# Global Constant
_calories = {"lettuce": 5, "carrot": 52, "apple": 72, "bread": 66,
"pasta": 221, "rice": 225, "milk": 122, "cheese": 115,
"yogurt": 145, "beef": 240, "chicken": 140, "butter": 102
}
# Input loop
new_item = input("Enter food item to add, or ’... |
89d510c4380ca70acb0420f2033601cd1f35b25e | weiguangjiayou/LeetCode | /LeetCode/LeetCode892surface-area-of-3d-shapes.py | 997 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/8/19 10:06 AM
# @Author : Slade
# @File : LeetCode892surface-area-of-3d-shapes.py
class Solution(object):
def surfaceArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
col = len(grid)
r... |
d3898cd0f15e09f9857bc24357626bab02c8a1f7 | TracyDai23/Leetcode | /55_Jump_Game.py | 1,528 | 3.5 | 4 | # 97%
# 这个题目的痛点在于逻辑分析完以后,实现方法上的loop flow没有理清楚。 包括1)把一个corner case 当成一个scenario在讨论(line17);
# 2)然后flag的设置和break,continue的跳出loop的方式和范围理解不清楚; 3) line 32的这种方式没有想到,总想着简化
class Solution:
def canJump(self, nums: List[int]) -> bool:
#reverse nums and check zero
if len(nums)<=1:
return True
... |
79c2410da6ffc85790acdbad084aa67bdfa1567e | Aditi-Billore/competitive_practice | /LinkedList/mergeTwoLinkedList.py | 1,843 | 4.15625 | 4 | # implementation of linked list and merge the numbers in list
# two sorted list are given, return new merged list
class Node:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
def addEnd(self, num):
newNode = Node(num)
if self.next is None:
se... |
9ee61b2988c620eeb7c414833d685772ccf9bec0 | GryffindorisSuperior/project-100 | /atm.py | 548 | 3.921875 | 4 | balance = 500
purpose = input("Are you here for a withdrawal or balance enquiry? [w/b]")
if(purpose == 'w'):
pinnumber = input("Enter your pin number here: ")
withdrawalamount = input(int("How much do you wish to withdraw? "))
if(withdrawalamount >= 500):
print("Sorry, you don't have enough mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.