blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
4658e4741af62dd512c0834b7165629a52acf528 | kamath7/Automate-The-Boring-Stuff-Al | /Basics/app10.py | 500 | 3.90625 | 4 | #List methods
lalle_arr = ['kams','bums','lambs','crumbs']
print(lalle_arr.index('lambs')) #Returns index
lalle_arr.append('coombs')
print(lalle_arr)
lalle_arr.insert(1,'joomba')
print(lalle_arr)
lalle_arr.remove('kams')
print(lalle_arr)
num_arr = [-8,29,0,23,-19,69,55]
num_arr.sort(reverse=True)
print(num_arr)
l... |
d49d665fbe7260571e8d024e4ab6ada5eb15bd02 | engom/formation_lycee_2020 | /TP_premiere/TANDOUNA_Nathan.py | 640 | 3.71875 | 4 | from math import *
a=float(input("Donner la valeur de a : "))
b=float(input("Donner la valeur de b : "))
c=float(input("Donner la valeur de c : "))
if a==0:
if b==0:
if c==0:
print("Tout réel est une solution")
else:
print("Pas de solution")
else:
print("L... |
827a615402f670ea3abe5a30769b16175f04e3af | engom/formation_lycee_2020 | /TP_premiere/TASCI_Mathieu.py | 726 | 3.8125 | 4 | from math import *
a = int(input("A = "))
b = int(input("B = "))
c = int(input("C = "))
def equation(a, b, c):
print("L'équation est : ", a, "x² + ", b, "x + ", c)
Delta = (b ** 2) - (4 * a * c)
print("Delta =", Delta)
if Delta < 0:
print("Le discriminant est inférieur à 0, il n y a pas de s... |
f0308738dc2a7e58571fdc4ed02afeb8e2b7dc7c | engom/formation_lycee_2020 | /TP_premiere/FERREIRA_Thomas.py | 383 | 3.734375 | 4 | from math import*
A=eval(input('A='))
B=eval(input('B='))
C=eval(input('C='))
delta=B**2-4*A*C
print('delta=',delta)
if delta<0:
print('Pas de solution')
if delta==0:
print('une solution')
x=-B/(2*A)
print('x=',x)
if delta>0:
print('Deux solutions')
x1=(-B-sqrt(delta))/(2*A)
x2=(-B+sqrt(delta))/(2*A)
print('x1=... |
c210f4c397ef22be43081976a526f44600b8ee79 | MasiaMatteo03/SistemiEReti | /pytohn_natale/es3_fibonacci.py | 405 | 3.90625 | 4 | def serieFib(num, max):
if num != int(max):
if num == 0 or num == 1:
print(num)
serieFib(num + 1, max)
else:
print((num - 1) + (num - 2))
serieFib(num + 1, max)
def main():
valMax = input("Inserisci il valore massimo per la serie... |
ced56fa01a75a2f408b4c50409756d85f95c647b | Sineenart0903/workshop-2 | /Operators/Comparison_operators.py | 172 | 3.90625 | 4 | x = 17
y = 2
print("x > y is", x > y)
print("x < y is", x < y)
print("x == y is", x == y)
print("x != y is", x != y)
print("x >= y is", x >= y)
print("x <= y is", x <= y)
|
a6f57ed0d1ca90d96d792b8eed7967674c8d10a9 | starschen/learning | /learn_liaopy/custom-made.py | 2,129 | 3.8125 | 4 | class Student(object):
def __init__(self,name):
self.name=name
def __str__(self):
return 'Student object (name:%s)' %self.name
# print Student('Emma')
s=Student('Emma')
# print s
class Fib(object):
def __init__(self):
self.a,self.b=0,1
def __iter__(self):
return self
... |
6fb14bf38ecae758db74a0a2b8c542e00389925e | starschen/learning | /acmcoding/2020.py | 604 | 3.53125 | 4 | #encoding:utf8
#2020绝对值排序
#思路:这道题原本想到用sorted将绝对值排序,再set去重,但是发现set在去重的过程中会将列表排序,
#我想这道题较笨的方法就是遍历列表元素的绝对值比较大小,同时将重复值去掉
#我又笨了,这明明是一道三行代码就可以搞定的,我又想复杂了,python真是高级啊,其实我真的不大会
#正经的写按大小排序,有现成的还是先用着吧
def seq_abs(l):
lst=sorted(l[1:],key=lambda x:abs(x),reverse=1)
print lst
seq_abs([3,3,-4,2])
seq_abs([4,0,1,2,-3])
|
a7d5ca703fe9036c8929783cd24d680704ae9bf2 | starschen/learning | /introduction_MIT/14_1帕斯卡的问题.py | 511 | 3.578125 | 4 | #encoding:utf8
#14.1帕斯卡的问题
#检验帕斯卡的分析
import random
def rollDie():
return random.choice([1,2,3,4,5,6])
def chekPascal(numTrials):
'''假设numTrials是一个正整数,输出获胜的概率'''
numWins=0.0
for i in range(numTrials):
for j in range(24):
d1=rollDie()
d2=rollDie()
if d1==6 and ... |
6248d8ced78cf9b217c28b88189424dae0b41e01 | starschen/learning | /data_structure/binaryTreeTravle.py | 2,590 | 4.21875 | 4 | #encoding:utf8
#二叉树的遍历(前、中、后)
#代码来源:http://blog.csdn.net/littlethunder/article/details/9707669,仅学习用
class Node:
def __init__(self,value=None,left=None,right=None):
self.value=value
self.left=left
self.right=right
#此部分为后加,代码来源http://www.cnblogs.com/sunada2005/p/3326160.html
class BinaryTree... |
ff9286d2e995377154fbe7dd18040cf61d8b3fe9 | starschen/learning | /introduction_MIT/4_3递归.py | 1,389 | 3.828125 | 4 | #encoding:utf8
#4.3递归
def factI(n):
'''Assumes that n is an int>o
Returns n!'''
result=1
while n>1:
result=result*n
n-=1
return result
def factR(n):
'''Assumes that n is an int>0
returns n!'''
if n==1:
return n
else:
return n*factr(n-1)
#4.3.1斐... |
c0af996b13f2344c5f99da8a75d3daea13d0ab07 | starschen/learning | /introduction_MIT/5_2列表和可变性.py | 1,130 | 3.59375 | 4 | #encoding:utf8
#5.2列表和可变性
# l=['I did it all',4,'love']
# for i in range(len(l)):
# print l[i]
#
# Techs=['MIT','Caltech']
# Ivys=['Harvard','Yale','Brown']
#
# Univs=[Techs,Ivys]
# Univs1=[['MIT','Caltech'],['Harvard','Yale','Brown']]
#
# print 'Univs=',Univs
# print 'Univs1=',Univs1
# print Univs==Univs1
# print... |
d812363f4e8dda103165af8a1a8e304c0b415ec1 | starschen/learning | /introduction_MIT/6_2调试.py | 815 | 3.90625 | 4 | #encoding:utf8
#6.2调试
#一段错误的代码
def isPal(x):
'''假定x是列表
如果列表是回文的返回True,否则返回False'''
temp=x[:]
# temp.reverse #错误,没有加括号
temp.reverse() #修改后
if temp == x:
return True
else:
return False
def silly(n):
'''假定n是正整数
接受用户的n个输入
如果所有输入组成了一个回文列表,返回‘Ye... |
5811174aa1a8d867ea4e93373a366dcd9d8b8389 | starschen/learning | /acmcoding/1108.py | 257 | 3.609375 | 4 | #encoding:utf8
##求最小公倍数
##先求最大公约数
def gcd(x,y):
if x%y==0:
return y
else:
return gcd(y,x%y)
#print gcd(18,10)
def Lowest_Common_Multiple(x,y):
return x*y/gcd(x,y)
print Lowest_Common_Multiple(10,18)
|
03acfa988fb20072a0902441f16d5b3aa1b5233e | starschen/learning | /learn_liaopy/l4.py | 168 | 3.59375 | 4 | #encoding:utf8
##1
l=[]
n=1
while n<=99:
l.append(n)
n=n+2
##2
def filb(max):
n,a,b=0,0,1
while n<max:
yield b
a,b=b,a+b
n=n+1 |
b6bfe040950b239d2b31ad6c15f016827d93b666 | starschen/learning | /introduction_MIT/5_1元组.py | 922 | 3.671875 | 4 | #encoding:utf8
#5_1元组
# def findDivisors(n1,n2):
# '''假定n1,n2是正整数
# 返回一个元组,包含n1,n2的公约数'''
# divisors=()
# for i in range(1,min(n1,n2)+1):
# if n1%i==0 and n2%i==0:
# divisors=divsors+(i,)
# return divisors
#
# divisors=findDivisors(20,120)
# print divisors
# total=0
# for d i... |
c16719a8dac95579baa8c57f385ba1b32caab3c3 | starschen/learning | /introduction_MIT/3_2for循环.py | 624 | 3.671875 | 4 | #encoding:utf8
#3.2 for 循环
# x=4
# for i in range(0,x):
# print i
# x=4
# for i in range(0,x):
# print i
# x=5
#
# x=4
# for i in range(x):
# for j in range(x):
# print j
# x=2
#寻找完全立方数的立方根
# x=int(raw_input('Enter an integer: '))
# for ans in range(abs(x)+1):
# if ans**3>=abs(x):... |
ba71ba6ac4c4c52344bc379d7a3f791e66f73c55 | starschen/learning | /web-spider/s1_urllib2_test04.py | 579 | 3.578125 | 4 | # import urllib
# import urllib2
#
# data={}
# data['name']='WHY'
# data['location']='SDU'
# data['language']='Python'
#
# url_values=urllib.urlencode(data)
# print url_values
#
# #name=Somebody+Here&language=Python&location=Northampton #???
# url='http://www.example.com/example.cgi'
# full_url=url+'?'+url_values
#
# ... |
5c44f49824bbeae2760a45044e671d2a7d349a03 | khurrum-khalil/detailed-assignment-chap03 | /3.3.py | 272 | 3.546875 | 4 | print('khurram khalil')
print(' SECTION A ' , '18B-81-CS')
print('PRACTICE PROBLEM 3.1')
hits = input('how many times you get hitted: ')
shield = input('how many shields are left: ')
if (hits>='10') and (shield=='0'):
print('you are dead...!')
|
3a7019fedee32181a955bbc2794ad9a0b450191c | khurrum-khalil/detailed-assignment-chap03 | /6.1.py | 209 | 3.578125 | 4 | print('khurram khalil')
print('section A , 18B-81-CS')
print('practice problem 3.28')
x=eval(input('enter n: '))
for i in range(0,x):
b=i**2
print(b)
|
7936e380fcfbfd65e89a430d9f37c5f3f09cd2d6 | lyonbach/Dynamic-Programming | /can_sum.py | 1,926 | 4.09375 | 4 | """
Python implementation of the third and the eleventh chapters code.
Original videos can be viewed from the following link:
https://www.youtube.com/watch?v=oBt53YbR9Kk
"""
# Third Chapter
def can_sum(target_sum: int, numbers: list):
"""
Returns a boolean value indicating if it is possible to get the given t... |
7b7ea0f2690579220e1dd50f8151e0214c950ec8 | hxsnow10/BrainNN | /SORN/general_model.py | 2,398 | 4.15625 | 4 | '''一个general的RNN
应该定义的计算结构
'''
class RNN(SimpleRecurrent):
'''
some abstract model to define structural RNN.
abstracts of RNN is dynamic systems, all variables has it's dynamics, \
when in NN some as states some as weights.
when NN become more complex, for example biology models, LSTM, multi\
... |
be538a73a00b741db39e469ba683124f105bc251 | KWolley/Fridge-Friend | /Match Ingredients to Recipes/MatchRecipes_Test.py | 2,370 | 3.59375 | 4 | #!/usr/bin/python3
# Saloni Sharma
import unittest
import MatchRecipes
class MatchRecipesTesting(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
#TEST 1
#Check whether ingredients (ItemsInKitchen) have been stored correctly
def test_ingredient_names(sel... |
5081fb1aabe670d901a8215ac85d44233bf715b2 | biroska/Python-Study | /repeticao/DigitoAdjacente.py | 982 | 4.1875 | 4 | # Este programa contempla a resolução do primeiro exercício opcional do curso:
# Introdução à Ciência da Computação com Python Parte 1
# Disponível no coursera.
#
# EXERCÍCIO OPCIONAL 2
# Escreva um programa que receba um número inteiro na entrada e verifique se o número
# recebido possui... |
089ff3c062a5b18c9f1c318561e8603d5ddc62ee | biroska/Python-Study | /condicionais/Ordenados.py | 633 | 4.34375 | 4 | # Este programa contempla a resolução do primeiro exercício opcional do curso:
# Introdução à Ciência da Computação com Python Parte 1
# Disponível no coursera.
#
# EXERCÍCIO 5
# Receba 3 números inteiros na entrada e imprima crescente se eles forem dados em
# ordem crescente. Caso contrário, im... |
176fb212620acdcf861e9999a496d699c730fc11 | biroska/Python-Study | /repeticao/SomaDigitos.py | 511 | 4.1875 | 4 | # Este programa contempla a resolução do primeiro exercício opcional do curso:
# Introdução à Ciência da Computação com Python Parte 1
# Disponível no coursera.
#
# EXERCÍCIO 2
# Escreva um programa que receba um número inteiro na entrada, calcule e imprima
# a soma dos dígitos deste númer... |
14211c899a064cff7330fba2bd74711c4dc0dda6 | monkeesuit/Intro-To-Python | /scripts/trialdivision.py | 479 | 4.15625 | 4 |
num = int(input('Enter a numer to be check for primality: '))
ceiling = int(pow(num, .5)) + 1 # Get ceiling of sqaure root of number (b/c of how range works
for i in range(2, ceiling):
if (num % i == 0): # if any number between 2 and ceiling-1 divides num
print('{} is composite'.format(num)) ... |
02d7e587fdb388b9ac07b62b255eab351e7873fa | nicholaskier/python-error-lesson | /errors.py | 369 | 3.921875 | 4 | print(1)
int(9)
# int 9
# python functions need parenthesis
print(2)
# print 3
# python functions need parenthesis
a = [1,2,3]
# square brackets mean that python is expecting a list
# syntax syntax syntax
# exceptions
# RUNTIME ERRORS
a = 1
b = '2'
print(int(2.5))
# closing parenthesis
print(a + b)
# trying to add an ... |
6a669977ff5c6a4ad9b6b0027382e9e575758771 | serviru/Python_lessons_basic | /hw03_normal.py | 2,078 | 3.875 | 4 | __author__ = "Кравченко Сергей Иванович"
# Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
res = []
last=0
next=1
for i in range(m+1):
# print ("i={}, last={}, next={}".format(i,l... |
1e80b093f952251d2571694f4b13b012d46df5d3 | peeush-agarwal/LearningDL | /ComputerVision/imageurl_to_image.py | 1,273 | 3.875 | 4 | import cv2
import urllib.request
import numpy as np
import imutils
from skimage import io
def __url_to_image__(url):
''' Steps:
1. Download the image
2. Convert it to NumPy array
3. Read array to openCV format
'''
print ('Using urllib and numpy')
resp = urllib.request.urlopen(url)
image... |
af38d9c59cf055231df194834120dd542de30186 | firetee13/atscale | /app/at_scale.py | 3,208 | 3.8125 | 4 | #!/usr/bin/env python3
from argparse import ArgumentParser
class Or_matcher:
def __init__(self, file_name, criteria_list):
self.f = open("text", "r")
self.criteria_list = criteria_list
self.output_list = []
def match_words(self, word, line_number, word_list):
"""
get t... |
a419874f28a2545b974ff174015c5896a0eca3b4 | treyshel/student-checkin | /student-checkin/checkin_disk.py | 1,630 | 3.875 | 4 | #file used for opening, appending, and writing files ONLY
def open_student_checklist():
'''None -> [[str, str]]'''
students = []
with open('total_student_checklist.txt', 'r') as file:
file.readline()
for names in file:
split_string = names.split(', ')
students.appen... |
d75af544c7327e8862480b9cf2ac003f36eaeeb8 | OOASE/python-restart | /main.py | 2,876 | 4.09375 | 4 | '''
varaible assignment
'''
# add 'solo' to the varibale 'name'
# name = "solo"
# print(name)
#===========================
# assign same values to multiple variables on the same line
# p = j = t = "disciple"
# print(p)
# print(j)
# print(t)
#============================
# reuse variable names, the last assignment ... |
23d454d122bf87f94b81339a45a3ed59c67aabf1 | TheNewThinkTank/sqlite-app | /SQLiteAPP/Command/sqliteapp_command.py | 2,886 | 3.53125 | 4 | """Set up SQLite database connection,
create tables,
load data into tables,
update or delete data.
"""
# from pprint import pprint as pp
import sqlite3
from sqlite3 import Error
from SQL_statements.create import create_tables
from SQL_statements.delete import delete_comment
from SQL_statements.insert import insert_da... |
56a49ba69b3758b8d5c699117445f664875d88e3 | StellaKim1230/Algorithm-study | /BinarySearch.py | 368 | 4.0625 | 4 | def binary_search(arr, search_value):
if len(arr) == 0:
return False
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == search_value:
return True
if arr[mid] > search_value:
high = mid - 1
else:
low = mid + 1
return False
my_list =... |
f17a1cab24588d5cdcc0b9a7eae9143cc74a0ed2 | puhrez/algorithms | /algos/knapsack.py | 881 | 3.734375 | 4 | from typing import Tuple, List, Dict
def knapsack(W: int, items: Tuple[int, int]):
"""Fill a knapsack of W optimally with items of (weight, value)"""
M = init_matrix(W, items)
for i, item in enumerate(items, 1):
for wei in range(W + 1):
M[wei, i] = max(
M[wei, i - 1],
... |
2758acb06ddb1b896b137b1eb2692a3b70eb2c34 | muhammada1/Portfolio | /PythonCode/HackerRank/Power - Mod Power.py | 214 | 3.53125 | 4 | a = int(input(Input mod ))
b = int(input(Input Exponent ))
m = int(input(Input mod ))
ab_ex = ab
ab_modm = ab_ex % m
'''
ab_ex = pow(a,b)
ab_modm = pow(a,b,m)
'''
print(ab_ex)
print(ab_modm)
|
af1331ca539d507ad34cbf7f849d9ce239ea2603 | muhammada1/Portfolio | /PythonCode/HackerRank/Find Angle MBC.py | 636 | 3.671875 | 4 | import math
pi = 3.14159265359
l_AB = float(input("Length AB: "))
l_BC = float(input("Length BC: "))
l_AC = (((l_AB**2)+(l_BC**2))**.5)
l_MC = (l_AC/2)
l_MB = (((l_BC**2)-(l_MC**2))**.5)
a_ABC_p = l_AB/l_BC
a_ABC_rad = math.atan(a_ABC_p)
a_ABC = ((a_ABC_rad * 180)/ pi)
a_ABC_round = round(a_ABC)
a... |
ce1520d6f32ddc5ca905bcd4db649190a7a8a8a8 | martincxx/PythonPlay | /DataAnalysisCognitiveClass/GroupBy.py | 217 | 3.5 | 4 | #Grouping by df.Groupby()
import pandas as pd
#create a subset
df_test = df["drive-wheels", "body-style", "price"]
df_grp = df_test.group_by(["drive-wheels", "body-style"], as_index = False).mean()
print (df_group)
|
1e9e3b7ed550e8f3004fd7af54c44a5b21564259 | martincxx/PythonPlay | /list_slicing.py | 910 | 3.875 | 4 | l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print l[2:9:2]
to_five = ['A', 'B', 'C', 'D', 'E']
print to_five[3:]
# prints ['D', 'E']
print to_five[:2]
# prints ['A', 'B']
print to_five[::2]
# print ['A', 'C', 'E']
my_list = range(1, 11)
# reverse order of elements
back... |
924e46c90bc31ed5fd44ccc3da128734d006fb1a | martincxx/PythonPlay | /PythonforAstronomers/exercise2.py | 356 | 4.125 | 4 | """2. Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.
2.1. Use the module re (regular expressions)"""
def find_m(word):
import re
if re.match("[aeiou]$",word.lower()):
return True
else:
return False
print find_m("A")
... |
6b62c86f421d37b1c946ed3bcf260863e73100fe | martincxx/PythonPlay | /DataAnalysisCognitiveClass/Lab2.py | 5,679 | 3.546875 | 4 | import pandas as pd
#location of data
filename = 'https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data'
#headers for data
headers = ["symboling","normalized-losses","make","fuel-type","aspiration", "num-of-doors","body-style",
"drive-wheels","engine-location","wheel-base", "length... |
e4f639187549e7d88dc35ca03891e35892e20eaa | pluxsuwong/Project-Euler-Algorithms | /020.py | 255 | 3.75 | 4 | # Problem 20 - Factorial Digit Sum
print "Problem 20 - Factorial Digit Sum"
num = 1
for x in range(1, 101):
num *= x
num_str = str(num)
num_len = len(num_str)
num_total = 0
for x in range(0, num_len):
num_total += int(num_str[x])
print num_total
|
d037be8370367fae4246896a472868737a78ef41 | jzacsh/edu-225 | /calc/lexer | 1,563 | 3.53125 | 4 | #!/usr/bin/python
"""
bol
"""
import sys
#exit codes
EC_QUIT = 2
EC_MATH = 3
# P.E.M.D.A.S.
tokens = dict(
pl='('
pr=')'
e='^'
m='*'
d='/'
a='+'
s='-'
)
equate = []
def main():
"""Get the latest data and pass to local method
Parse data in a l... |
474bf9677662d0a7e62d9d94c9e0443fd1fb2a9d | akoshdev/lesson1 | /index1.py | 348 | 3.671875 | 4 | i = int(input('Vvedite chislo uchastnikov: '))
members = []
# if i.isdiggit():
while i > 0:
result = input('Kto zanyal {}: '.format(i))
members.append(result)
i -= 1
# else:
# print('Vvedite chislo')
members.reverse()
resultt = members[:3]
for n in resultt:
print('Pobiditel {} mesto poluchil: {}... |
b7cb4095cc4f9bc41c286472b1e368ab590f8f53 | dustein/Ex-Python_CeV | /exrcicio_63.py | 294 | 3.90625 | 4 | print('Fibonacci')
a = 0
b = 1
count = 3
total = int(input('Quantas posições da cadeia deseja exibir? '))
print('{} -> {} -> '.format(a, b), end='')
while count <= total:
c = a + b
count = count + 1
a = b
b = c
print('{} -> '.format(c), end='')
print('FIM!')
|
8ef07e8ff283a9bd5e1f5c132aca02a171d77bdc | dustein/Ex-Python_CeV | /exercicio_103.py | 302 | 3.671875 | 4 | def ficha(n = "'n/i", g=0):
if g.isnumeric():
g = int(g)
else:
g = 0
print(f'{n} teve {g} marcados nesta temporada.')
#Programa principal
nome = str(input('Nome do jogador -> '))
gols = str(input('Quantos gols marcados -> '))
ficha(nome, gols) |
4cb16d26f07bc7ac24b2ee37bdedacaf346f9641 | dustein/Ex-Python_CeV | /exrcicio_68.py | 907 | 3.78125 | 4 | from random import randint
count = 0
print('Escolha um número. Eu vou escolher outro.\nO total será Par ou Ímpar!?')
while True:
jogador = int(input('Ecolha seu número -> '))
count += 1
computador = randint(0, 10)
total = jogador + computador
escolha = jogo = ' '
while escolha not in 'P... |
dc13bdae61a03ac688bed1af27578ccb72d31773 | poojan14/Python-Practice | /GeeksForGeeks/Non Repeating Character.py | 932 | 3.625 | 4 | '''
Given a string S consisting of lowercase Latin Letters. Find the first non repeating character in S.
'''
'''
// TLE
if __name__ == '__main__':
T = int(input())
for _ in range(T):
N = int(input())
s = input()
res = -1
tmp = s
i = 0
while len(tmp)>0:
... |
fc29be3abc77bb0b5b5d71043514255ce2d498ae | poojan14/Python-Practice | /GeeksForGeeks/Amazon/Count the elements.py | 778 | 3.734375 | 4 | '''
Given two arrays A and B. Given Q queries each having a positive integer i denoting an index of the array A.
For each query, your task is to find all the elements less than or equal to Ai in the array B.
'''
def BinarySearch(low,high,A,ele):
while low<= high :
mid = (low + high)//2
if A[mid] <=... |
6925d7f8c060f6b5b805fe7cd590c00ad675163a | poojan14/Python-Practice | /Automate the boring stuff with python/4_List/Comma Code.py | 317 | 3.859375 | 4 | def commalist(lst):
s = ''
if lst == []:return s
if len(lst) == 1 : return lst[0]
tmp = lst[:len(lst)-1]
s = ', '.join(tmp)
s = s + ', and ' + lst[-1]
return s
if __name__ == '__main__':
l = list(input('Enter elements of list : ').split())
print(commalist(l))
|
22b6f26099d684fefd3ea028e70ef08f77d83f3e | poojan14/Python-Practice | /GeeksForGeeks/Series GP.py | 329 | 3.59375 | 4 | '''
Given the first 2 terms A and B of a Geometric Series, tell the Nth term of the series.
'''
import math
if __name__=='__main__':
T=int(input())
for i in range(T):
l=list(map(int,input().split()))
A,B=l[0],l[1]
N=int(input())
r=B/A
tmp=r**(N-1)
print(math.floor... |
f1a6d759dfb75a850f265a95f6c099a1ccc56adb | poojan14/Python-Practice | /GeeksForGeeks/GCD of Array.py | 475 | 3.796875 | 4 | '''
Given an array of N positive integers. Your task is to find the GCD of all numbers of the array.
'''
def GCD(A,B):
if A==0:return B
if B==0:return A
if A==B:return A
if A>B:return GCD(B,A%B)
if A<B:return GCD(A,B%A)
if __name__=='__main__':
T=int(input())
for i in range(T):
... |
e8ef79bccce99a998abd587a2783f57a6986593d | poojan14/Python-Practice | /GeeksForGeeks/Recursive/Possible words from Phone digits.py | 640 | 3.96875 | 4 | '''
Given a keypad as shown in diagram, and an N digit number. List all words which are possible by pressing these numbers.
'2':'abc'
'3':'def'
'4':'ghi'
'5':'jkl'
'6':'mno'
'7':'pqrs'
'8':'tuv'
'9':'wxyz'
'''
d = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
def Permutations(arr ... |
521214260de7cbbdace82f16f1919ee920e2b52d | poojan14/Python-Practice | /GeeksForGeeks/Hashing/Find all four sum numbers.py | 1,748 | 3.765625 | 4 | '''
Given an array A of size N, find all combination of four elements in the array whose sum is equal to a given value K. For example, if the
given array is {10, 2, 3, 4, 5, 9, 7, 8} and K = 23, one of the quadruple is “3 5 7 8” (3 + 5 + 7 + 8 = 23).
For each test case in a new line print all the quadruples present in ... |
14008f642d4f5176cf4e6c7deb7ee640f179ca13 | poojan14/Python-Practice | /GeeksForGeeks/Alternating elements.py | 663 | 3.5625 | 4 | '''
Given two arrays A and B of size N and M.
The task is to print the array elements of A and B alternatively, i.e, A[i], B[i], A[i+1], B[i+1] ... .
'''
if __name__=='__main__':
T=int(input())
for _ in range(T):
size=list(map(int,input().split()))
N,M=size[0],size[1]
A=list(map(int,inpu... |
2ff6c4150d1972b2bb79fcc5769ba7816a4cc7fc | poojan14/Python-Practice | /GeeksForGeeks/Hashing/Frequencies of Limited Range Array Elements.py | 688 | 3.984375 | 4 | '''
Given an array A[] of N positive integers which can contain integers from 1 to N where elements can be repeated or can be absent from the
array. Your task is to count frequency of all elements from 1 to N.
Note: Expected time complexity is O(n) with O(1) extra space.
For each test case, output N space-separated i... |
c3b5b1b342d2c955616b7cfe4ae3b58aacfe759c | poojan14/Python-Practice | /GeeksForGeeks/Bitonic Array.py | 1,136 | 3.5 | 4 | '''
Given an array A[0 … n-1] containing n positive integers, a subarray A[i … j] is bitonic if there is a k with i < k < j such that
A[i] < A[i + 1] ... < A[k] > A[k + 1] > .. A[j – 1] > A[j]. Write a program that returns the length of the maximum length bitonic subarray.
For Example: In array {20, 4, 1, 2, 3, 4, 2,... |
87031f94d2855382675da6a49829599fca6792a5 | poojan14/Python-Practice | /Automate the boring stuff with python/Pattern_Matching_With_Regular_Expressions/Regex Version of strip().py | 443 | 4.1875 | 4 | import re
def strip(string , sep = None):
if sep == None:
sep = '\s'
return re.sub(r'^[{0}]+|[{0}]+$'.format(sep),'',string) #first {0} is replaced by {sep}
if __name__ == '__main__':
string = input('Enter string : ')
sep = input('Enter character to be strip... |
ffbbafa81924b189eb2faa826cc8698d01e3e169 | poojan14/Python-Practice | /GeeksForGeeks/Searching/Peak element.py | 1,200 | 3.875 | 4 | '''
Given an array A of N integers. The task is to find a peak element in it.
An array element is peak if it is not smaller than its neighbours. For corner elements, we need to consider only one neighbour.
Note: There may be multiple peak element possible, in that case you may return any valid index.
'''
def peakElem... |
eb3fbf662bd1cc4c4b3d6ef6bbfe4addd752b638 | poojan14/Python-Practice | /GeeksForGeeks/Sorting/Sorting Elements of an Array by Frequency.py | 825 | 3.953125 | 4 | '''
Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher frequency come first.
If frequencies of two elements are same, then smaller number comes first.
'''
from collections import OrderedDict
if __name__ == '__main__':
T = int(input())
for _ in ... |
0902f72d26a0a9cc71e41dfa76f0b5b7e62bf07e | poojan14/Python-Practice | /GeeksForGeeks/Good or Bad string.py | 1,378 | 4.125 | 4 | '''
In this problem, a String S is composed of lowercase alphabets and wildcard characters i.e. '?'. Here, '?' can be replaced by any of the
lowercase alphabets. Now you have to classify the given String on the basis of following rules:
If there are more than 3 consonants together or more than 5 vowels together, the S... |
dd17c2f3f10bd4f9c5c45da50621cbab848542f6 | poojan14/Python-Practice | /GeeksForGeeks/Max sum path in two arrays.py | 1,022 | 3.953125 | 4 | '''
Given two sorted arrays A and B. The task is to complete the function max_path_sum that takes 4 argument, the first two arguments
represent the 2 arrays A[] and B[] and the last two arguments l1, l2 denote the size of array A and B respectively.
The function returns the sum of the maximum sum path to reach from b... |
2a5b3bc9c604596916fe910a15e1c13ce02b8e62 | poojan14/Python-Practice | /GeeksForGeeks/Remove Spaces.py | 163 | 3.546875 | 4 | # Given a string, remove spaces from it
if __name__ == '__main__':
T = int(input())
while T>0:
print(''.join(list(input().split())))
T-=1
|
82759cb35602ad3a75121daf3cca40c9b577ac5b | poojan14/Python-Practice | /GeeksForGeeks/Pattern Matcher.py | 489 | 3.765625 | 4 | '''
Given a string S and a pattern P, you need to find if S can be generated by using P one or more times.
For each testcase, print "1"(without quotes), if possible, else print "0"(without quotes).
'''
if __name__ == '__main__':
T = int(input())
for _ in range(T):
pattern , string = input() , input()
... |
d4b51ee637ec7d35deec977c7fcb2e3b0d6514a0 | poojan14/Python-Practice | /GeeksForGeeks/Inversions.py | 866 | 3.859375 | 4 | '''
Count number of inversions in an array in O(log n) time.
'''
def Merge(A,l,m,h):
inv_count = 0
temp = [0]*len(A)
i , j,k = l,m+1,l
while i<=m and j<=h:
if A[i]<= A[j]:
temp[k] = A[i]
i += 1
else:
temp[k] = A[j]
inv_count += (m+1-i)
... |
8022d3654ef94f67f0719e7a3de587d7d9f6ff7e | poojan14/Python-Practice | /GeeksForGeeks/Searching/Searching a number.py | 612 | 3.875 | 4 | '''
Given an array of N elements and a integer K. Your task is to return the position of first occurence of K in the given array.
Note: Position of first element is considered as 1.
For each test case, print the index of first occurrence of given number K. Print -1 if the number is not found in array.
'''
if __name__ =... |
373abf2eba72858cd4c21356e9258a60598fbd75 | poojan14/Python-Practice | /GeeksForGeeks/Contest/Count Students.py | 977 | 3.9375 | 4 | '''
Given N students with marks obtained by them in an exam. The task is to count the students with same name and marks.
For each testcase, print students name, marks and count of same student with same name and marks, all seperated by space.
The output is sorted in lexigraphically sorted order of names and if two nam... |
f9249384c16b11e489dcd346347baa9f55b2b9fc | poojan14/Python-Practice | /GeeksForGeeks/Sorting/Sort an array of 0s ,1s and 2s.py | 609 | 3.546875 | 4 | '''
Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array in ascending order.
'''
if __name__ == '__main__':
T = int(input())
for _ in range(T):
N = int(input())
A = list(map(int,input().split()))
low ,mid ,high = 0 ,0 ,N-1
while mid <= high:
... |
0f2e9e4518d22f242e3ec88613ec50e221fb026e | poojan14/Python-Practice | /9.py | 167 | 3.5625 | 4 | def solve(s):
for x in s.split():
s=s.replace(x,x.capitalize())
return s
if __name__ == '__main__':
S=input()
res=solve(S)
print(res)
|
def77432cc97bb70a22c8e37b0e237b05f3dbb9e | poojan14/Python-Practice | /Data Structures and File Processing/Heap/Heap_Class.py | 2,756 | 4.25 | 4 | import math
class Heap:
heap=[]
def __init__(self):
'''
Objective : To initialize an empty heap.
Input parameters :
self : Object of class Heap.
Output : None
'''
#Approach : Heap is an empty list.
self.heap=[]
def ... |
7241dbf0e02bb3a21f69bf4092840b3d825be4bc | poojan14/Python-Practice | /GeeksForGeeks/Searching/Floor in a Sorted Array.py | 625 | 3.984375 | 4 | '''
Given a sorted array arr[] of size N without duplicates, and given a value x. Find the floor of x in given array.
Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x.
Output the index of floor of x if exists, else print -1.
'''
if __name__ == '__main__':
T = int(in... |
6560fcf0b82ad4f6d534807dfb58e01c1e45ebde | poojan14/Python-Practice | /LeetCode/Array/Median of Two Sorted Arrays.py | 1,455 | 3.890625 | 4 | '''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
'''
class Solution(object):
def determineMedian(self,k,A,size):
if size % 2 ... |
2cdb0d8485ee156bdd918d18239a35168dfa72be | poojan14/Python-Practice | /14.py | 684 | 3.609375 | 4 | if __name__ == '__main__':
s = input()
f1,f2,f3,f4,f5=0,0,0,0,0
for ch in s:
if ch.isalnum()==True:
f1+=1
if ch.isalpha()==True:
f2+=1
if ch.isdigit()==True:
f3+=1
if ch.islower()==True:
f4+=1
if ch.isupper()==True:
... |
0939a06193be6a09549dfa053193ae5b8cb5e1d8 | poojan14/Python-Practice | /GeeksForGeeks/Leaders in an array.py | 539 | 3.921875 | 4 | '''
Given an array of positive integers.
Your task is to find the leaders in the array.
Note: An element of array is leader if it is greater than or equal to all the elements to its right side.
Also, the rightmost element is always a leader.
'''
def Leaders(A,n):
Max=A[n-1]
S=[Max]
for i in range(n-2,-1,-... |
fca3507427727f85eda459a5e38715f1e07480d4 | csbc92/QuestionShuffler | /questionshuffler.py | 2,745 | 3.65625 | 4 | import sys
import random
from parsers import xmlparser as xml, jsonparser as json
def get_question_file():
question_file = "data/questions.json"
if len(sys.argv) > 1:
question_file = sys.argv[1]
return question_file
def load_questions(path):
if path.endswith(".json"):
return json.f... |
b55d4fc5ca01d907380880c672e76fa03dfadb55 | ph1l1pp2/adventofcode2020 | /main.py | 19,899 | 3.5625 | 4 | import copy
import re
from typing import List, Dict, Set, Tuple
import pyparsing
def day1_1():
expenses = []
with open("input.txt", "r") as f:
for line in f:
expenses.append(int(line))
expenses_2020 = get_two_with_sum(values=expenses, target_sum=2020)
return expenses_2020[0] * exp... |
43acca4867890d768f8a23fa857e4d516d439847 | Thedegreeisalie/PythonChallenge | /solved/0004.py | 1,534 | 3.921875 | 4 | #!/usr/bin/env python
#program needs to parse the header and pull a number then parse the header from a website
import urllib.request
import re
import string
URL = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
start = "8022"
strhtml = []
strhtml.append(urllib.request.urlopen(URL+start).read())
new = ... |
514f30c77a21e36f5cbda14e9b2496bba3ca0d4d | widesky867/blackjack | /deck.py | 1,017 | 4 | 4 | # deck class
# code adapted from https://brilliant.org/wiki/programming-blackjack/
# editted to include elements of OOP as a practice
from random import shuffle
values = [_ for _ in range(2,11)] + ['JACK', 'QUEEN', 'KING', 'ACE']
suits = ['SPADES', 'HEARTS', 'CLUBS', 'DIAMONDS']
class Deck(object):
# initialise... |
efe852c8b80139041ce0480d5f069d9b8ccec517 | ReforgedDream/python_learning | /average_numpy.py | 2,225 | 3.78125 | 4 | # coding=utf-8
import time
import numpy as np
# Всё, что у нас есть на входе - длина последовательности.
sequence_length = 100_000_000
# Используя данную длину, сделаем список-арифметическую прогрессию.
sequence = list(range(1, sequence_length + 1))
# То же самое, но используя numpy
array = np.arange(1, s... |
617d3cdc74bcc4d7f1cd3489881efb9da784dfcc | bilaer/Algorithm-And-Data-Structure-Practices-in-Python | /heap_sort.py | 1,922 | 4.25 | 4 | ####################################
# Heap Sort #
# ##################################
# #
# Max_heapify: O(lgn) #
# Build_max_heap: O(n) #
# Overall performance is O(nlgn) #
# #
########################... |
f348bcab1cef2ce7d8b5a318f6f7ca5baf472445 | hpausiello/mars-data-scrape | /scrape_mars.py | 7,147 | 3.640625 | 4 | #dependencies
import pandas as pd
import requests
from splinter import Browser
from bs4 import BeautifulSoup
import html5lib
#create a function that will run mars data scrape and return dictionary of scraped data
def scrape():
#create an empty dictionary to store all mars scraped data
mars_data_dict = {}
... |
c490f6d073b306eb0625a44007fdc4fe6f418376 | pawloxx/CodeWars | /two_to_one_string_distinct.py | 188 | 3.78125 | 4 | #a = "xyaabbbccccdefww"
#b = "xxxxyyyyabklmopq"
#longest(a, b) -> "abcdefklmopqwxy"
def longest(s1, s2):
return ''.join(sorted(set((s1+s2))))
print(longest("aretheyhere", "yestheyarehere")) |
1be2eb9e19b8341b6622460623edd22664d8f5f2 | pawloxx/CodeWars | /CreditCardValidifier.py | 1,340 | 4.34375 | 4 | """
Make a program that sees if a credit card number is valid or not.
Also the program should tell you what type of credit card it is if it is valid.
The five things you should consider in your program is: AMEX, Discover, VISA, Master, and Invalid :
Discover starts with 6011 and has 16 digits,
AMEX starts with 34 or 37... |
78432b90980985c72a231902ad932480dca4d59c | pawloxx/CodeWars | /CreditCardMask.py | 271 | 4.03125 | 4 | """
Your task is to write a function maskify, which changes all but the last four characters into '#'
"""
# return masked string
#input
cc = 'input'
#masking function
def maskify(cc):
mask = '#'*(len(cc) - 4) + cc[-4:]
return mask
#just check
print(maskify(cc)) |
2e08fe94cdab2f453c6c9ed9ad2a14b65d82fc6f | XiangyiCheng/CWRUEECS531 | /A3/exercise.py | 4,320 | 3.671875 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets('/tmp/data/',one_hot=True)
n_classes=10
batch_size=100
# x is the data. y is the label of the data.
x=tf.placeholder('float',[None,784])
y=tf.placeholder('float')
def baseline_neural_network(data):
... |
f193e2185b3ff6788a550b143a1dd588e28fc2e8 | glarson284/Project-Euler | /FizzBuzz.py | 189 | 3.75 | 4 | # 3 - Fizz 5 - Buzz 3 & 5 - FizzBuzz
for i in range(1,101):
if i % 3 == 0 and i % 5 == 0:
print 'FizzBuzz'
elif i % 3 == 0:
print 'Fizz'
elif i % 5 == 0:
print 'Buzz'
else: print i
|
8bee32320119e535b164a912d4651a310ba63947 | Zoe8888/error-handling | /main.py | 2,507 | 3.796875 | 4 | from tkinter import *
from tkinter import messagebox
# Initializing the window
root = Tk()
# Creating a title
root.title('Authentication')
# Setting the window size
root.geometry('400x400')
# Ensuring the window size cannot be adjusted
root.resizable('False', 'False')
# Setting a background color
root.config(bg='#d177... |
ef4501237a29658db20410fa1825da1346b56483 | ArnoldCody/Python-100-exercise | /exercise6.py | 1,066 | 4.21875 | 4 | # coding=utf-8
"""
题目:斐波那契数列。
程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。
在数学上,费波那契数列是以递归的方法来定义:
F0 = 0 (n=0)
F1 = 1 (n=1)
Fn = F[n-1]+ F[n-2](n=>2)
"""
"""
# 这个函数可以输出制定从 0~i 的数列,比较省内存,计算 i 很大的时候很快得出结果
def Fib(i):
Fib = []
Fib.append(0)
Fib.append(1)
n = 2
... |
b5c453b32461e11eb27c42b38ca495a94a33124a | ArnoldCody/Python-100-exercise | /exercise4.py | 1,134 | 4.1875 | 4 | # coding:utf-8
# 题目:输入某年某月某日,判断这一天是这一年的第几天?
birthday = raw_input("please input birthday, like yyyymmdd: ")
# 检验是否为闰年
def leap_year(year):
if year%4 == 0:
return True
else:
return False
# 定义每月的天数
def month_has_days(month):
for i in [1, 3, 5, 7, 9, 10, 12]:
if month == i:
... |
2fa367156d47d1fe1901f7ba9bf9795fc5841cce | Kirk-KD/connect-four-with-ai | /src/text.py | 847 | 3.796875 | 4 | import pygame
pygame.init()
class Text(object):
"""
The Class Text that holds a text surface.
"""
def __init__(self, text, size, color=(0, 0, 0)):
"""
Initializes text, text size, font and text surface.
:param text: The text on the text surface.
:param size: The font ... |
5af22f3a3e59d94453634f40af5fea2429eebad4 | BatLancelot/PFund-June-Sep-2020 | /11_Functions_Ex/09_Factorial Division.py | 254 | 3.96875 | 4 | number_a = int(input())
number_b = int(input())
def factorial(a, b):
for i in range(a, 1, -1):
a *= i - 1
for i in range(b, 1, -1):
b *= i - 1
result = a / b
return result
print(f'{factorial(number_a, number_b):.2f}')
|
9885d2c61004559160679ce113424247a8894a67 | BatLancelot/PFund-June-Sep-2020 | /02_Basic_Syntax_CS_Loops_Ex/06_Next Happy Year.py | 400 | 3.71875 | 4 | import sys
year = int(input())
max_num = sys.maxsize
while year < max_num:
year += 1
ones = year % 10
tens = (year % 100) // 10
hundred = (year % 1000) // 100
thousand = (year % 10000) // 1000
if (ones == tens or ones == hundred or ones == thousand) or (tens == hundred or tens == thousand)\
... |
67b21633db705ee08d59c699940c3c08fefb2fe9 | BatLancelot/PFund-June-Sep-2020 | /11_Functions_Ex/04_Odd and Even Sum.py | 290 | 4.03125 | 4 | number_s: str = input()
even = []
odd = []
def sum_even_odd(number: str):
for num in number:
if int(num) % 2 == 0:
even.append(int(num))
else:
odd.append(int(num))
sum_even_odd(number_s)
print(f'Odd sum = {sum(odd)}, Even sum = {sum(even)}')
|
b2c09e5ad16c14b46baa69a63b6a2995a5374785 | BatLancelot/PFund-June-Sep-2020 | /05_Data_Types_and_Varibles_Ex/08_Party Profit.py | 1,001 | 3.59375 | 4 | import math
party_size = int(input())
days = int(input())
sum_coins = 0
day_earning = 50
food_price = 2
water_price = 3
boss_master = 20
for day in range(1, days + 1):
if day % 10 == 0:
party_size -= 2 # 2 (two) of your companions leave
if day % 15 == 0:
party_size += 5 # 5 (five) new compa... |
2e112c94eaec81b0d3843223e597d42da42fd072 | josefsandoval/Celery | /linear_model_new.py | 1,626 | 4.03125 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
salaries = pd.read_csv('Indeed Salaries with Cities Clean.csv', index_col=0).reset_index(drop=True)
X = salaries['Cost of Living'].values.reshape(-1, 1) # Independ... |
de62297c9e01e9df4e5a619744cce0dfbef4c0e3 | Megatech13/Pythontutor | /Lesson 1. Data input and output/5. Task Hello, Harry.py | 278 | 3.796875 | 4 | # Условие
# Напишите программу, которая приветствует пользователя, выводя слово Hello, введенное имя и знаки препинания
# по образцу:
name = input()
print(f"Hello, {name}!") |
22523d88e2faa931e6535429110634ab47a564e0 | Megatech13/Pythontutor | /Lesson 1. Data input and output/1. Problem Sum of three numbers.py | 451 | 4.125 | 4 | # Условие
# Напишите программу, которая считывает три числа и выводит их сумму. Каждое число записано в отдельной строке.
a = int(input())
b = int(input())
c = int(input())
print(a + b + c)
# Если аргументов намного больше, то можно так
# c = 0
# for i in range(10):
# a = int(input())
# c += a
# print(c) |
261c7974eb1b0231f9acef57986a81e882730ca9 | Megatech13/Pythontutor | /Lesson 2. Conditions/8. The King's Turn Challenge.py | 1,001 | 3.828125 | 4 | # Условие
# Шахматный король ходит по горизонтали, вертикали и диагонали, но только на 1 клетку. Даны две различные клетки
# шахматной доски, определите, может ли король попасть с первой клетки на вторую одним ходом. Программа получает
# на вход четыре числа от 1 до 8 каждое, задающие номер столбца и номер строки снача... |
12007f3bb27198dfa72f22e09fa7197209673ba7 | Megatech13/Pythontutor | /Lesson 2. Conditions/1.The task of the Minimum of two numbers.py | 249 | 3.703125 | 4 | # The task of the "Minimum of two numbers»
#Условие
#Даны два целых числа. Выведите значение наименьшего из них.
a = int(input())
b = int(input())
if a < b:
print(a)
else:
print(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.