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 |
|---|---|---|---|---|---|---|
3e3566af015294f6d7e771ea40b9399e2db3a731 | Akshya-M/Contacts_Manager | /query.py | 2,655 | 3.6875 | 4 | def add(db, tname, **data):
col_name = ''
val = ''
values = []
for i in data:
col_name += '{}, '.format(i)
val += '?, '
values.append(data[i])
col_name = col_name[:-2]
val = val[:-2]
try:
cur = db.cursor()
cur.execute('insert into {} ({}) v... |
5a991e06ede2a6026ddfa19292912dabeeef08da | xyq946692052/python-cookbook-exercise | /chapter3-number-date-time/formattest.py | 266 | 3.5 | 4 | x = 1234.567890
def showres(num, pat):
print(format(num, pat))
showres(x, '0.2f')
showres(x, '>10.1f')
showres(x, '<10.1f')
showres(x, '^10.1f')
showres(x, ',')
showres(x, '0,.1f')
showres(x, 'e')
showres(x, '0.2E')
print('The value is {:0,.2f}'.format(x))
|
dfd5bdb66965ec73b8b27196022d0219b057f9e2 | xyq946692052/python-cookbook-exercise | /chapter1-datastructures-algorithms/dictoperation.py | 915 | 4 | 4 | prices = {
'APPLE': 5000,
'HUAWEI': 4998,
'VIVO': 3200,
'XIAOMI': 5999,
'SANSONG': 2890,
'OPPO': 4290
}
min_price = min(zip(prices.values(), prices.keys()))
max_price = max(zip(prices.values(), prices.keys()))
sort_price = sorted(zip(prices.values(), prices.keys()))
print('The price of phone:... |
16f5c3768bac8261570ae5d4c89eebaf3f763103 | maro525/aizu-online-judge | /alds1_6_c.py | 1,674 | 3.640625 | 4 | '''
クイックソート
分割統治法に基づくアルゴリズム。ただし、統治がない
安定ではない、インプレースソート
平均の計算量O(nlogn)
https://github.com/maro525/aizu-online-judge/blob/master/alds1_46_b.pyのパーティションを使う
'''
import sys
INF = sys.maxsize
class Card:
def __init__(self, s, v):
self.suit = s
self.value = v
def merge(A, left, mid, right):
n1 = mid ... |
fa6b44c58fba9356481c733a2adddc94d8f665df | maro525/aizu-online-judge | /alds1_10_c.py | 553 | 3.5 | 4 | '''
dlp
動的計画法
最長共通部分列を求める
'''
def lcs(X, Y):
m = len(X)
n = len(Y)
c = [[0 for i in range(n+1)] for j in range(m+1)]
X = " " + X
Y = " " + Y
for i in range(1, m+1):
for j in range(1, n+1):
if X[i] == Y[j]:
c[i][j] = c[i-1][j-1] + 1
else:
... |
31ac86642f9aac81f78e77e279c79861cc50ebca | maro525/aizu-online-judge | /alds1_12_a.py | 1,018 | 3.546875 | 4 | '''
最小全域木
Minimym Spanning Tree
プリムのアルゴリズム
'''
if __name__ == '__main__':
n = int(input())
M = [list(map(int, input().split())) for i in range(n)]
color = [0] * n
weight = [float("inf")] * n
parent = [None] * n
def prim():
weight[0] = 0
parent[0] = -1
while True:
... |
2ae4e628b4f1cd00aa19f16aaea229d821fa43a3 | hallliu1984831/coding | /src/python/generators.py | 935 | 3.765625 | 4 | # def mygenerator():
# yield 1
# yield 2
# yield 3
#
# g = mygenerator();
# for i in g:
# print(i)
# value = next(g)
# print(f'--{value}')
# print(sorted(g, reverse=True))
# import sys
# def firstn(n):
# nums = []
# num = 0
# while num < n:
# nums.append(num)
# num += 1
# ... |
1d1adb5a6a9aed9874f0917f6d7dca38f6101481 | akshatdokania/pythonfiles | /pythonfiles/char.py | 144 | 3.609375 | 4 |
import sys
a=input()[0]
print("charachter is",a)
print("The ascii value of" +a+ "is ", ord(a))
print("size of char is",sys.getsizeof(a))
|
20f2d9c10472fe6a901f413fea1cb311ae2bb860 | ErrorCode51/ProjectEuler | /Euler_58.py | 793 | 3.984375 | 4 | import math
# As always, my quick and dirty prime test
def isPrime(number):
if number <= 1:
return False
if number in [2, 3, 5]:
return True
if number % 2 == 0 or number % 3 == 0 or number % 5 == 0:
return False
for i in range(7, int(math.sqrt(number) +1), 2):
if number %... |
b24b8e67512741c23d41351d808cdad22cd8f348 | ErrorCode51/ProjectEuler | /Euler_42.py | 487 | 3.546875 | 4 | def isTriangleNumber(number):
i = 1
while True:
term = (i/2)*(i+1)
if term == number:
return True
elif term > number:
return False
i+=1
def getWordValue(word):
return sum([ord(c)-96 for c in word.lower()])
total = 0
with open('ProblemFiles/Problem_4... |
6968e64e6344dd2dfc4664630add68885e8713a4 | ErrorCode51/ProjectEuler | /Euler_29.py | 143 | 3.578125 | 4 | array = []
for x in range(2, 101):
for y in range(2, 101):
if x**y not in array:
array.append(x**y)
print(len(array)) |
b756c00451e22d322a5d877bec0928057b7b17e3 | ErrorCode51/ProjectEuler | /Euler_75.py | 865 | 3.90625 | 4 | import math
# Source: https://en.wikipedia.org/wiki/Pythagorean_triple
def getCoprimes(nr):
coprimes = []
for x in range(1, nr):
if math.gcd(x, nr) == 1:
coprimes.append(x)
return coprimes
MAX_LENGTH = 1_500_000
solutionsPenLength = [0] * MAX_LENGTH
m = 1
while True:
coprimes = ... |
fa544f1b63ce4566200e4c2972bdd50e5bf56219 | ErrorCode51/ProjectEuler | /Euler_38.py | 300 | 3.75 | 4 | highest = 0
for i in range(2, 100000):
string = ''
for x in range(9):
string += str(i*(x+1))
if len(string) >= 9:
break
if ''.join(sorted(string)) == '123456789':
if int(string) > highest:
highest = int(string)
print('highest:', highest)
|
297225d6bc75166d4462bd9b93000c2a71db4424 | ErrorCode51/ProjectEuler | /Euler_49.py | 688 | 3.8125 | 4 | import math
# Quick and dirty prime test
def isPrime(number):
if number <= 1:
return False
if number in [2, 3, 5]:
return True
if number % 2 == 0 or number % 3 == 0 or number % 5 == 0:
return False
for i in range(7, int(math.sqrt(number) +1), 2):
if number % i == 0:
... |
7c725919d983e3339ba715f22ae7c4ea5b5dc2f2 | topher2001/python_Misc | /basics.py | 2,331 | 3.953125 | 4 | import sys
import os
import random
print("Hi")
#Comment
'''
a
long
comment
'''
#vars are sorta like in JS
name = "Chris"
print(name)
#Normal math stuff + - * / % **(Power) //(Round down)
# ' and " are the same
# , to concatenate
print(name, 18)
multi_line_string = '''just
sing'''
print("%... |
04a3bb5d83bdf6748a30fc54ddc84b5987f76fe2 | prosenjitj/Projects | /Puzzles/BFS.py | 979 | 3.78125 | 4 | treeMat = [[1,2,4,5],
[3,5,6,8]]
ROW = 2
COL = 4
class Node :
def __init__(self, key):
self.val = key
self.visited = False
self.left = None
self.right = None
def CreateTree(arr):
return TraverseTree(arr , 0 , 0)
def TraverseTree(arr , row , col):
node = Node(arr[... |
2ada54d5a55394379721e472ebc953f96e5e37a9 | SumaDabbiru/DS-and-Algorithms | /AlgoExpert/threesum.py | 1,203 | 3.84375 | 4 | def ThreeSum(lst, target):
triplet=[]
lst.sort()
for i in range(len(lst)-1):
left=i+1
right = len(lst) - 1
while left < right:
if lst[i]+lst[left] + lst[right] == target:
triplet.append([lst[i], lst[left], lst[right]])
left+=1
... |
49fc88841ec6a0a1ae3acd79737c8329e89e6751 | SumaDabbiru/DS-and-Algorithms | /AlgoExpert/Misc/reverese string.py | 828 | 4.09375 | 4 | import re
def reversesentence(s):
#convert a string to list
s=re.findall(r"[\w']+|[.,!?;]", str(s))
i=0
j=len(s)-1
while i<=j:
# check if the character is punctuation and skip
if not s[i].isalpha():
i+=1
if not s[j].isalpha():
j-=1
else:
... |
5d48ab13654b6b482086591a1d8fe7a27d04b7d0 | SumaDabbiru/DS-and-Algorithms | /AlgoExpert/TwoSum.py | 1,035 | 3.65625 | 4 | def TwoSum( lst, target):
#using two pointer o(nlogn)
left = 0
right=len(lst)-1
while left<right:
if lst[left]+lst[right]==target:
return [left,right]
elif lst[left]+lst[right]<target:
left+=1
elif lst[left] + lst[right] > target:
right-=1
''' ... |
f046d5fc6e4ffd155c2637cb838dc7d7dff4857a | SumaDabbiru/DS-and-Algorithms | /AlgoExpert/SingleCycleCheck.py | 676 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 22 15:13:29 2020
@author: SujithPatnaik
"""
def cycleCheck(array):
visited = 0
currentIdx = 0
nextIdx = 0
while visited < len(array):
if visited > 0 and currentIdx == 0: #rotating in circles
return False
... |
3ec8fbebdfc711546b28174e0b141ad3557aef47 | SumaDabbiru/DS-and-Algorithms | /AlgoExpert/LongestPeak.py | 706 | 3.65625 | 4 | def LongestPeak(lst):
longestpeaklength=0
i=1
while i < len(lst)-1:
ispeak = lst[i-1] < lst[i] and lst[i]>lst[i+1]
if not ispeak:
i+=1
continue
leftindex = i-1
while leftindex>=0 and lst[leftindex] < lst[leftindex+1]:
leftindex-=1
... |
0b3fcdc515d755282bf774bb3ac7423676081d5a | SumaDabbiru/DS-and-Algorithms | /AlgoExpert/zigzagTrvarse_AlgoSol.py | 1,157 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 17 22:03:00 2020
@author: SujithPatnaik
"""
# time: O(n) Space O(n)
def zigzagTraverse(matrix):
row = col = 0
result = []
R = len(matrix)-1
C = len(matrix[0])-1
goingdown = True
while not outofbounds(row,col,R,C):
... |
9017cb2a53b0b99f2a7924f9e8a2ab7a82f0ad49 | SumaDabbiru/DS-and-Algorithms | /AlgoExpert/MonotonicArray.py | 565 | 3.6875 | 4 | def isMonotonicArray(lst):
if len(array) <= 2:
return True
i = 1
while i < len(array)-1:
if array[i-1] < array[i] > array[i+1] or array[i-1] > array[i] < array[i+1]:
return False
i += 1
return True
"""
isnonDecreasing = isnonIncreaseing = True
for i in range(1,len(lst)):
... |
dce36ba64b94201ac62c6472bec70849172c51f9 | amaldare93/myCode | /foobar/1.1-rabbitTest.py | 1,888 | 3.5625 | 4 | '''
Rabbit test subjects
====================
The diabolical Professor Boolean has captured you and a group of your hapless rabbit kin as test sunjects for his terrible experiments! You're not sure what is real plans are, but currently it seems he's trying to make everyone faster and smarter? He's exposing rabbit test... |
e5a93d1a495d3b7af95cd0b7f0962f1d68519d1c | amaldare93/myCode | /foobar/2.1-zombit.py | 2,285 | 3.578125 | 4 | '''
Zombit monitoring
=================
The first successfully created zombit specimen, Dolly the Zombit, needs constant monitoring, and Professor Boolean has tasked the minions with it. Any minion who monitors the zombit records the start and end times of their shifts. However, those minions, they are a bit disorgani... |
2cf480771c533e26de9f8f9177fe4013fd7c3711 | amaldare93/myCode | /projectEuler/euler009.py | 422 | 4.0625 | 4 | '''
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
def euler9():
a = 1
b = 2
c = 3
triples = []
while a < 1000:
while b < 1000 and c > b:
c = 1000 - a - b
... |
7a51c6f204243ed633a4815164d376fb688ceb31 | deepakgit2/Machine-Learning-and-Deep-Learning-Implementation | /polynomial_regression_Animated.py | 1,737 | 3.859375 | 4 | # It is the animated implementation of Polynomial Regression
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import random
# Learning rate
l_rate = 0.023
random.seed(3)
# Data points
x_t = np.arange(1,10)
x = np.array([[1, i, i**2/float(10), i**3/float(10**2),] for i in range(1, ... |
b58b53b9ad6eb128b929dbf8f5a5cc5265935677 | Pronesti/tercera_clase | /dados.py | 913 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 5 09:49:19 2019
@author: diego
"""
import random
res = random.randint(1,3)
def tirar_dado():
return random.randint(1,6)
def tirar_varios_dados(cuantos):
resultado =[]
i=0
while i <= cuantos:
resultado.append(tirar_dado())... |
b66b389306fbb3c0d1d99c192067b9642cd89c11 | hho1985/Ejercicios-HackerRank | /Conversion hora.py | 328 | 3.515625 | 4 | s="1:05:45PM"
hora, minutos, segundos = s.split(":")
print (segundos[2:])
if segundos[2:] == "PM" and hora =='12':
hora = "00"
if segundos[2:] == "PM" and hora !='12':
hora = str(int(hora) +12)
if segundos [2:] == "AM" and hora == '12':
hora = '00'
print (hora+":"+ minutos+":"+ segund... |
2f54b796e30bb8491c9d1ad48a668236bcc6797c | fmojica30/learning_python | /TestLinkedList.py | 13,052 | 3.859375 | 4 | # File: TestLinkedList.py
# Description:
# Student Name: Fernando Martinez Mojica
# Student UT EID: fmm566
# Course Name: CS 313E
# Unique Number: 50725
# Date Created: 4/9/2019
# Date Last Modified: 4/12/2019
from random import randint
class Link():
def __init__(self, data, next = None):
self.da... |
d368e0f0e8acbbf8dbecb6a5e6a9a64f8f3efdd7 | fmojica30/learning_python | /Palindrome.py | 2,851 | 4.21875 | 4 | # File: Palindrome.py
# Description:
# Student Name: Fernando Martinez Mojica
# Student UT EID: fmm566
# Course Name: CS 313E
# Unique Number: 50725
# Date Created: 2/20/19
# Date Last Modified: 2/20/19
def is_palindrome(s): #define if a string is a palindrome
for i in range(len(s)//2):
if... |
69afbeef8bc37abcba6cce6410f8cdfe440721fe | michaelhickman/michael-repos | /test.py | 1,728 | 3.9375 | 4 | """test.py."""
import unittest
import number_to_words
class Test_number_to_words(unittest.TestCase):
def test_get_words(self):
self.assertEqual(number_to_words.get_words("000"), "")
self.assertEqual(number_to_words.get_words("012"), "twelve")
self.assertEqual(number_to_words.get_words("05... |
f0cf885aa095819dcb2ca65b14d73fdb1b0b769c | ananda-sreenidhi/Codewars_Python | /7_kyu/Number_of_People_in_the_Bus.py | 267 | 3.5 | 4 | """
Number of People in the Bus
https://www.codewars.com/kata/5648b12ce68d9daa6b000099
"""
def number(bus_stops):
inside = bus_stops[0][0]
i = 1
while i<len(bus_stops):
inside += bus_stops[i][0] - bus_stops[i][1]
i += 1
return inside
|
043ee36e018ec3e14eb509313c8709d36da851a0 | kunaly1038/100-days-of-code | /code/python/day-6/code.6.3.py | 321 | 3.796875 | 4 | def replacement(x):
y=len(x)
for i in range(0,y):
if(x[i] == 0):
key = x[i]
j=i
print(y)
while(j<y-1):
x[j]=x[j+1]
j+=1
x[y-1]=key
print(x)
x = [3, 0, 1, 0, 5, 9, 0, 6, 7]
replacement(x)
... |
902aeb88d12a1431e94f268b8eee67503b81d259 | kunaly1038/100-days-of-code | /code/python/day-6/code.6.2.py | 243 | 3.546875 | 4 | def sorting_problem(x):
for i in range(1,len(x)):
key = x[i]
j=i-1
while(j>=0 and key<x[j]):
x[j+1]=x[j]
j-=1
x[j+1]=key
x = [1, 0, 1, 1, 1, 0, 0, 1, 0]
sorting_problem(x)
print(x)
|
409157df8b6eb3dddd5b187fb386e029337c0086 | theabinashpanda/Coding_Club_India | /Python/word_rev.py | 178 | 4.03125 | 4 | '''
Reverse words in a given String in Python
Date: 26/10/2021
Time: 08:01:23
'''
sentence=input("Enter a sentence: ")
words=sentence.split(" ")
print(" ".join(reversed(words)))
|
8310afda9786b629d9a27da486fb5b010e115441 | manjusha18119/manju18119python | /function/1541606349748_powerf2.py | 63 | 3.671875 | 4 | a=input("enter the value")
power=lambda i:2**i
print(power(a))
|
eea344e35517ef5ebac15bfb19aae17693def068 | manjusha18119/manju18119python | /function/dictsum.py | 205 | 3.671875 | 4 | dic={}
k=str(raw_input("Enter the key : "))
while k != "":
v=input("Enter the value : ")
dic[k]=v
k=str(raw_input("Enter the key : "))
s=dic.values()
leng=len(s)
sum=0
for i in s:
sum=sum+i
print sum
|
eae5b0e4a0648f90bbe170ce236c7e021e82cd07 | manjusha18119/manju18119python | /function/assignment7.py | 138 | 4 | 4 | list_one = [1,2,3,4]
list_two = ['one','two','three','four']
my_dict = {key:value for key,value in zip(list_one,list_two)}
print(my_dict)
|
f2694af595bdd7f32c43a31a539838a7d78bde02 | manjusha18119/manju18119python | /python/asg3.1.py | 85 | 3.984375 | 4 | def input string(z):
n="a,e,i,o,u,A,E,I,O,U"
z=[i for i in n if i not in n]
print(z)
|
ebe90c9d66e6c7e2ae28d1a344bed3f41b25c3c3 | manjusha18119/manju18119python | /python/div.py | 116 | 3.984375 | 4 | a=int(input(check the number is divisible by 2 and 5)
div=(x for x in range(10) if x%2==0 and x%5==0)
print(number)
|
086131ab344102d2b8f8591b21314f68ab7eef72 | manjusha18119/manju18119python | /function/d5.py | 437 | 4.5 | 4 | # Python's program to iterating over dictionaries using 'for' loops
x = {'z': 10, 'l': 50, 'c': 74, 'm': 12, 'f': 44, 'g': 19}
for key, val in x.items():
print(key, "=>", val)
print("\n------------------------\n")
for key in x:
print(key, "=>", x[key])
print("\n------------------------\n")
for key in ... |
5ba7c19d34025ef2452ee4035cc60ee719e10beb | manjusha18119/manju18119python | /python/mul12.py | 204 | 4.09375 | 4 | #generation of multiplication table
print("multiplication table")
x=[7*j for j in range(2,20)]
y=[8*j for j in range(2,20)]
print("multiplication of 7",x)
print("multiplication of 8",y)
print(x)
print(y)
|
48580a003621f078f0aa99a0679c1dd7f282627a | manjusha18119/manju18119python | /python/build.py | 703 | 3.984375 | 4 | d={}
n=raw_input("Enter the key :")
while n!="":
a=raw_input("Enter the value")
d[n]=a
n=raw_input("Enter the key")
print("dictionary")
print(d)
l=len(d)
print("The length of the dictionary is %d"%l)
d2={}
n=raw_input("enter the key :")
while n!="":
a=raw_input("Enter the value")
d2[n]=a
n=raw_input("Enter the key... |
becd22b5a5052fd488fdb765d112636d4a22ea41 | manjusha18119/manju18119python | /function/sent.py | 354 | 3.65625 | 4 | print("\n")
l1=[]
sentence=("enter the string")
l1.append(sentence)
num="012345"
alpha="awsdfrgtg"
count=0
count2=0
num=len(sentence)
for i in range(len(sentence)):
if l1 in alpha l1 in alpha.upper():
count=count+1
elif l1 in num1:
count2=count2+1
else:
print("wrong output")
print("letter...........:"%count)
pr... |
eb6153b1c76f5418ba320e661249ac099a947ac6 | manjusha18119/manju18119python | /python/tri.py | 165 | 4.34375 | 4 | #18. Write a program to Display Triangle as follow :
e=int(input("Enter the range:"))
for a in range(0,e+1):
for b in range(0,a):
print(a, end=" ")
print(" ")
|
5b9ddf83bad7618b0a340165115b98804ec5aacb | manjusha18119/manju18119python | /python/assign2b.py | 91 | 3.546875 | 4 | n=1
for i in range (0,4):
for j in range (i+1):
print (n,end="")
n=n+1
print("")
|
f69d18508da58f1cbb8568c8f392df36067c5030 | manjusha18119/manju18119python | /function/removeven.py | 147 | 3.59375 | 4 | a=int(input("enter the elements:"))
b = []
for i in a:
if i%2!=0:
filtered elements print(list(filter(lambda x:x%2==o,list)
b.append(i)
print(b)
|
842bc7c6c57b6c0dc42fd62a4569771be9aae993 | manjusha18119/manju18119python | /python/dlist.py | 80 | 3.734375 | 4 | lim=int(input("enter the limit:"))
list={i:i*2 for i in range(lim)}
print(list)
|
1807e2597e8d8c7ac920d57a3dd53ed7d5e14033 | manjusha18119/manju18119python | /python/swap.py | 207 | 4.3125 | 4 | #2.Write a program to swap two variables.
a=input("Enter the value of a :")
#a=int(a)
b=input("Enter the value of b :")
#b=int(b)
temp=a
a=b
b=temp
print("swap value of a=",a)
print("swap value of b=",b)
|
eaf91661369519e8b3ff23f7b79a304c4b653082 | manjusha18119/manju18119python | /python/oddsum1.py | 153 | 3.75 | 4 | def oddsum(n):
"""function to print oddsum"""
s=0
for j in range(1,n):
if(j%2!=0):
print(j)
s=s+j
print("the sum is %d"%s)
return
oddsum(50)
|
967762aaccc4e16a411b125e0554718fcc894d07 | AdrianDomagala/PythonZadania | /Zadanie2/Zad_2_3_String.py | 491 | 3.546875 | 4 | import re
from collections import Counter
def stringStatistic(s):
lstWords = re.findall(r'\w+', s)
words = ''.join(lstWords)
countedLetters = Counter(words.lower())
print('Liczba słów: ', len(words), ' Liczba liter: ', len(words))
print('Liczba wystąpień każdej z liter (wielkość jest ignorowana): '... |
e03bf1e01c786066c7b3733de16d86e319591533 | sumitnce1/Joy-of-Computing-using-Python-NPTEL-2020 | /week 4/week4Assign1.py | 186 | 3.5625 | 4 | list1=input()
a=list1.count('1')
b=list1.count('0')
l=len(list1)
if a==l-1 and b==1:
print("YES",end='')
elif a==1 and b==l-1:
print("YES",end="")
else:
print("NO",end="") |
0f07da6e36a718d38cef8973dc7bf99c02d1d22b | hchaoshun/ML-Coursera | /ex1/linear_regression_with_multiple_variable.py | 1,404 | 3.703125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))
# 批量梯度下降
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(np.zeros(theta.shape))
parameters = int(theta.rav... |
5fbc55a0a43ec470a05956a3b053a532a36f644e | stqu/Messing-with-python | /rps.py | 3,882 | 3.875 | 4 | # Rock, Paper, Scissors game
import random
RPS = ["r","p","s","q"] # to check that inputs are valid
Output = ["rock","paper","scissors"] # to give readable user feedback
# We will append a 1 to one of these empty lists after every game for record keeping
ComputerWins = []
UserWins = []
Draws = []
print("ROCK, PAPER, SC... |
5892e9987eaa238d9dd0153ea3f146516ed2b529 | KauaDeja/Python_Exercicios | /ex017.py | 335 | 3.9375 | 4 | from math import radians,sin, cos, tan
a = float(input('Digite o ângulo que vc deseja: '))
seno = sin(radians(a))
cosseno = cos(radians(a))
tangente = tan(radians(a))
print(f'O angulo de {a} tem o cosseno de {seno:.2f}')
print(f'O angulo de {a} tem o SENO de {cosseno:.2f}')
print(f'O angulo de {a} tem o tangente de {ta... |
3e0c9760a73a7629837f54f67d86ac97157cfa32 | PriceLab/STP | /chapter4/aishah/challenges.py | 575 | 4.25 | 4 | #1 ------write function that takes number as input and returns it squared
def func1(x):
return x ** 2
print(func1(2))
#2---- write a program with 2 functions-- first one takes an int
#and returns the int by 2. second one returns an integer * 4.
#call the first function, save the number, then pass to the second on... |
6f7ebf3cf5157a9110e9861d070b41ee37ad1629 | GeofShoemaker/Python | /main.py | 723 | 4.0625 | 4 | print("Give me three numbers\nDon't try any funny business or you're gonna restart ;)")
while True:
try:
num1 = int(input("1.) "))
num2 = int(input("2.) "))
num3 = int(input("3.) "))
choice = input("GCF or LCM? ")
if(choice.lower()=="gcf"):
gc = min(num1,min(num2,num3))
while gc>0 and ... |
bcc9319ad904322adc87ee76025de07e62a88fa1 | Ronserruya/tbl | /tbl/main.py | 2,111 | 3.578125 | 4 | import os
import csv
import click
import rapidtables
from typing import List, Optional
def find_max_column_width(headers: List[str]) -> int:
try:
console_width = os.get_terminal_size(0).columns
except OSError: # get_terminal_size does not work inside of pycharm, so this is just for developing
... |
7dda52485b6307b6005268ba1ccf7a24b052ecc7 | ka-suvorov/calcs | /simple_calc2.py | 4,227 | 4.03125 | 4 | #usr/bin/python3
#Simple calc
from tkinter import *
from tkinter import messagebox
# Root TK Window Setup
root = Tk()
root["bg"] = "lightblue"
WIDTH = 290
HEIGHT = 420
POS_X = root.winfo_screenwidth() // 2 - WIDTH // 2
POS_Y = root.winfo_screenheight() // 2 - HEIGHT // 2
root.geometry(F'{WIDTH}x{HEIGHT... |
6f2f3648576cdf8da47ca0dc88ee1a8d9ea4d80d | Kotuzo/Python_crash_course | /Follow_Up/OOP.py | 1,284 | 4.34375 | 4 | import math
# This is examplary class
class Point:
# This is constructor
# Every method from class, needs to have self, as a first argument
# (it tells Python that this method belongs to the class)
def __init__(self, x, y):
self.x = x # attributes
self.y = y
# typical method
... |
e116a76298d2b569d30b6a698af42f075dd4e17d | trxw/CDIPS_PandoraTeam | /wikipedia/wiki_crawler_working.py | 11,813 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: utf_8
#Note: In order to use urllib2 python 2.6+ is required.
import sys
import urllib
import urllib2
from collections import Counter
from LinkStorage import UNDESIRABLE_LINKS, TEMPLATE_OR_CATEGORY, FILES, BAD_EXTENTIONS, BOOK_SITE_LIST
#Set the parent link where crawling begins:
url_... |
331533308afa58e9502c85d7d7df1dfcaca9ba6a | DianYe2333/leetcode | /python/0295_Find_Median_from_Data_Stream.py | 846 | 3.671875 | 4 | import heapq
class MedianFinder(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.count = 0
self.max_heap = []
self.min_heap = []
def addNum(self, num):
"""
:type num: int
:rtype: None
"""
sel... |
3f42a3c5456d2c54cd16f1e7b96380647aef0e00 | klvijeth/APS-2020 | /CodeSnippets/reg exp.py | 137 | 3.78125 | 4 | import re
print("Enter your email")
text = input()
y = re.findall('^([^@]*)',text)
z= re.findall('@(\S*)',text)
print(y)
print(z)
|
fdc036580638ce1933a285b680bc112a716a42ea | Jacobinski/Project-Euler | /Problem7.py | 343 | 3.734375 | 4 | from time import clock
start = clock()
primes = [2]
i = 1
end = False
while not end:
i += 1
if all(i%j != 0 for j in primes): # if no prime factors -> number is prime
primes.append(i)
if len(primes) == 10001:
print(primes[10001-1])
end = True
end = clock()
print('Computation Time:... |
7093b1615fba04f6a3f0ca1a5d2542838779c491 | Jacobinski/Project-Euler | /Problem9.py | 686 | 3.515625 | 4 | # -- Solve for b in terms of a --
#[a^2 + b^2 = c^2] & [a + b + c = n]
# a^2 + b^2 = (n-a-b)^2
# a^2 + b^2 = (n^2 - 2an - 2bn + 2ab + a^2 + b^2)
# 0 = n^2 - 2an - 2bn + 2ab
# bn - ab = (n^2)/2 - an
# b = [(n^2)/2-an]/(n-a)
from time import clock
from math import sqrt
start = clock()
n = 1000
a = 0.0 # Starting po... |
f8c785e8b58e3d4c7752b810447bac46550d19b1 | esmaclo/empresa_epd7 | /src/Departamento.py | 2,461 | 3.828125 | 4 | __author__ = 'Esmir Acosta'
from Empleado import *
class Departamento():
"""
Clase que representa un departamento
"""
def __init__(self, nombre_depto, id_depto):
"""
Metodo constructor de la clase Departamento
Inicializa dos atributos con los datos pasados como parametros y ap... |
20eec86ec8896e0fbcb0e3bb6b1e325fd3b71b63 | konstantinosTsoutsis/Socket-Simpe-Calculator | /Client.py | 1,187 | 3.625 | 4 | from struct import *
import socket
import binascii
#Host IP to send to.
serverIP = '127.0.0.1'
#Port to send to
serverPort = 1100
#create client socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#connect
clientSocket.connect((serverIP, serverPort))
msg_type = 0
msg_id = 35
msg_leng... |
79c86a34803b24e48785b96795c65f273a3b799f | saurabhjinturkar/soccer-simulation-openmp | /uianimate.py | 2,326 | 3.765625 | 4 | # Assuming Python 2.x
# For Python 3.x support change print -> print(..) and Tkinter to tkinter
from Tkinter import *
import time
import random
import Main
import thread
import copy
# Ground dimenstions : w x h : (45-90m) x (90-120m)
class FootballGround(object):
def printPoints(self, points):
for poi... |
e6719de4a44d98672037be65f0bbec32072c9f1b | jarkkokovala/nss | /fec_client.py | 2,552 | 3.53125 | 4 | #!/usr/bin/env python3
import sys
import socket
import struct
import random
import time
# Forward error correction client, sends data as UDP packets
# Arguments: packet loss probability as a percentage and FEC method (triple redundancy or XOR)
DEST_IP = "127.0.0.1" # Destination IP address
DEST_PORT = 12345 # Destin... |
000bb7297cc5a1241d7c97e9b39e19c526e5ffa7 | SkyAndCloud/Coursera-AndrewNG-ML-Python | /ex4/randInitializeWeights.py | 767 | 3.71875 | 4 | import numpy as np
def randInitializeWeights(L_in, L_out):
"""randomly initializes the weights of a layer with L_in incoming connections and L_out outgoing
connections.
Note that W should be set to a matrix of size(L_out, 1 + L_in) as the column row of W handles the "bias" terms
"""
# =======... |
5e3eca93bb33d141dae5c414459c9c02c4afe7f0 | SkyAndCloud/Coursera-AndrewNG-ML-Python | /ex2/gradientFunction.py | 808 | 3.8125 | 4 | from sigmoid import sigmoid
from numpy import squeeze, asarray
def gradientFunction(theta, X, y):
"""
Compute cost and gradient for logistic regression with regularization
computes the cost of using theta as the parameter for regularized logistic regression and the
gradient of the cost w.r.t. to the ... |
df96eece6fb6eeca792542599553853f7864aef2 | SkyAndCloud/Coursera-AndrewNG-ML-Python | /ex5/linearRegCostFunction.py | 880 | 3.828125 | 4 | import numpy as np
def linearRegCostFunction(X, y, theta, Lambda):
"""computes the
cost of using theta as the parameter for linear regression to fit the
data points in X and y. Returns the cost in J and the gradient in grad
"""
# Initialize some useful values
m = y.size # number of training example... |
d0fe28b294eff061b18a31416a4af201027082b8 | SkyAndCloud/Coursera-AndrewNG-ML-Python | /ex3/displayData.py | 2,923 | 3.515625 | 4 | import math
import matplotlib.pyplot as plt
import numpy as np
def displayData(X, example_width=None):
#DISPLAYDATA Display 2D data in a nice grid
# [h, display_array] = DISPLAYDATA(X, example_width) displays 2D data
# stored in X in a nice grid. It returns the figure handle h and the
# displayed array if reque... |
713459f79b180b49c44dec9a671f1a08558f58ce | tonytamsf/hacker-rank | /algo/reverse.py | 297 | 4.25 | 4 | #!/usr/bin/env python3
print('''This will take an array and reverse it by
swaping items in place.
''');
def reverse(s):
for i in range (0, int(len(s) / 2)):
tmp = s[i]
s[i] = s[len(s) - 1 - i]
s[len(s) - 1 - i] = tmp
return s
print (reverse ([400,300,200,100]))
|
d8e20efffe8d999c3753663d9462334f438983e7 | neethupauly/Luminarmaybatch | /oops/base.py | 4,646 | 4.125 | 4 | # oop....object oriented programming
# class:design patter/blueprint
# object:real world entity
# reference:to perform operations on object
# self-is an instance keyword-inside class
# methods-functions which are inside the class is called methods
# two types of variables
# 1.static variable-class-access using ... |
d96217ad5dc5bf2eda97a20dbc60b26e4e15fade | neethupauly/Luminarmaybatch | /files/count.py | 392 | 3.78125 | 4 | f1=open("new","r")
dict={}
for i in f1:
words=i.rstrip("\n").split(" ") #rstrip is used to eliminate \n in the output
# print(words) # if there are more than one line in the file
for word in words:
if word not in dict:
dict.update({word:1})
... |
3969476946d2619cd8c6952b91396a456c851265 | neethupauly/Luminarmaybatch | /Questions_Advanced_python/max_mark_file.py | 861 | 3.890625 | 4 | # Create objects of the following file and print the details of student with maximum mark?
# anu,1,bca,200 rahul,2,bba,177 vinod,3,bba,187 ajay,4,bca,198 maya,5, bba,195
class Student:
def __init__(self,name,sid,department,mark):
self.name=name
self.sid=sid
self.dep=department
self.... |
6011f1dddf4af221c4e3a1edbc69b132830c15c4 | neethupauly/Luminarmaybatch | /exception_handling/exceptions.py | 653 | 4.0625 | 4 | # exception handling
# solving unexpected errors
# try block......exceptional code
# except block.....solving code
# finally block.....anything
# zero division error
no1=int(input("enter num1"))
no2=int(input("enter num2"))
try:
print(no1/no2)
except Exception as w:
print("error occured",w)
finally:
print(... |
2bbfa3958ffd332b50f5d647cf8d524198e55eeb | neethupauly/Luminarmaybatch | /Django/decorators/div_decorator.py | 580 | 3.640625 | 4 | def zero_not_required(func):
def wrapper(num1,num2):
if (num1==0) | (num2==0):
raise Exception("invalid parameter")
else:
func(num1,num2)
return wrapper
def decorator_div(func):
def wrapper(num1,num2):
if num1<num2:
(num1,num2)=(num2,num1)
... |
617ec6a342cb58ba08c5da2d837f276a7f841513 | neethupauly/Luminarmaybatch | /Fundamentals/raise_keyword.py | 389 | 3.859375 | 4 | # raise - keyword for exception printing
# same number
# no1=int(input("enter num1"))
# no2=int(input("enter num2"))
# if no1==no2:
# raise Exception("two numbers are same")
# else:
# print(no2+no1)
#age condition exception printing
age=int(input("enter your age"))
if age>18:
print("eligible for vaccina... |
59333ca53c25999300009e7a5e697c7c30c2bb2f | neethupauly/Luminarmaybatch | /regular_expressions/demo.py | 411 | 3.921875 | 4 | # pattern matching
# pattern matching only supported in strings
# re-regular expressions
# re -- package for pattern matching
import re
count=0
matcher=re.finditer('ab','abaabaababab')
# print(matcher) #returns a location
for match in matcher:
print("match availiable at :",match.start()) #returns positions
... |
3c9d22585fbe44b08c62171c6147fbaf899cd832 | neethupauly/Luminarmaybatch | /python collections/List/lists.py | 1,191 | 4.1875 | 4 | # supports duplicates elements
# order keeps
# supports hetrogenous data
# nesting is possible
# mutable - can be updated
# lst=[1,2,3,1,2,3,"hello",True]
# print(lst)
# print(type(lst))
# lst1=[] #empty list creation
# print(lst1)
# print(type(lst1))
# lst1.append("hello")
# lst1.append(8)
# print(lst1)
# iterating... |
66ec4ee68f6db85940fd3bd9e22f91179507e5c2 | sushidools/PythonCrashCourse | /PythonCrashCourse/Ch.4/try it yourself ch4.py | 1,434 | 4.28125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 5 15:55:17 2018
@author: aleksandradooley
"""
spc = "\n"
pizzas = ['Hawaiin', 'BBQ chickcen', 'pepperoni']
friend_pizzas = pizzas[:]
for pizza in pizzas:
print "I like " + pizza + " pizza."
print "I really love pizza!"
pizzas.append('cheese')
... |
206183ab7f7458eff65d356efaccda4800eefd7e | sushidools/PythonCrashCourse | /PythonCrashCourse/Ch. 3/try it yourself ch3.py | 2,099 | 3.90625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 31 12:08:08 2018
@author: aleksandradooley
"""
#try it yourself pg 50
spc = "******************************************"
destinations = ["Bali", "Caribbean", "Paris", "Panama", "Mexico"]
print destinations
print sorted(destinations)
print destinati... |
be65015855a1a5c445e6bb7f50600fc9c272d782 | sushidools/PythonCrashCourse | /PythonCrashCourse/Ch.5/if statements.py | 940 | 4.09375 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 6 23:23:38 2018
@author: aleksandradooley
"""
#this below is a simple if statement
#if conditional_test:
# do something
age = 17
if age >= 18:
print "You are old enough to vote!"
print "Have you registered to vote yet?"
# if else statem... |
d2b4b65174573acef901003778d94802e7149a79 | sushidools/PythonCrashCourse | /PythonCrashCourse/Ch.6/many_users.py | 1,872 | 3.703125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 14 15:18:00 2018
@author: aleksandradooley
"""
spc = "\n"
"""
#many_users pg 113
#how about a dictionary within a dictionary
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'lo... |
c8827628a52d35c3fc41b4124a26f7a685bf01c1 | freddyhenao/pythonm1 | /ejercicios 2/ejercicios4.py | 778 | 3.984375 | 4 | print("Este algoritmo determina de N cantidades, cuantas son mayores o igueles a cero,")
print("cuantas son menores o igueles a cero")
def main():
print("NÚMEROS NEGATIVOS")
numero = int(input("¿Cuántos valores va a introducir? "))
if numero < 0:
print("¡Imposible!")
else:
contador = 0
... |
ae65e53411b7e9f2f27a1c79637d741335622d78 | freddyhenao/pythonm1 | /ejercicios1/ejercicios8.py | 511 | 3.8125 | 4 |
print(' Esta Aplicacion compara las edades ingresadas de dos personas ')
print('Dice si son no iguales ')
edad1 = int(input('Ingrese la edad de la Primera Persona \n'))
print('La Edad De La Primera Persona Ingresada Es: ' + str(edad1))
edad2 = int(input('Ingrese la edad de la Segunda Persona\n'))
print('La Edad De L... |
de34e60100eb8556e59b5f46c7382542a29f8443 | Kalebu/covid-19 | /scripts/step2_mx.py | 5,944 | 3.5 | 4 | """
Generates various plots and insights from the Mexican dataset.
"""
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import pandas as pd
import seaborn as sns
sns.set(style="ticks",
rc={
"figure.figsize": [15, 10],
... |
63f62abaf35e3761c706f879a35418d447eec14c | srikanth787/hacker | /chall3.py | 173 | 3.6875 | 4 | if __name__ == '__main__':
a = int(raw_input())
b = int(raw_input())
if 1 <= a <= pow(10,10) and 1 <= b <= pow(10,10):
print a + b
print a - b
print a * b
|
c765ac6d9de6e36ea5e2446bd0e62db310a955c6 | csiro-data-school/python-files | /files/command_lines/wordcount2_solution.py | 3,101 | 4.34375 | 4 | ### The module name is not capitalised
import argparse # Required to use the argparse module
from wordcount import read_file, word_count, print_counts
def get_program_args():
"""Defines command-line arguments and returns them to caller."""
# Create an argument parser
parser = argparse.ArgumentParser(... |
f3036996cda10e6f8e6cb257075b3be233c2cdec | AlexisKauil/Ejercicios_automatas | /Automatas 2/Estructura/listas.py | 275 | 3.765625 | 4 | #Listas en python
pares = [2,4,6,8,"Juan"]
lista = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,0,21,22,23,24,25]
lista2= [-9,-19-10]
print(lista + lista2)
print(lista2)
for item in lista2:
print (item)
print (len(lista2))
print (max(lista))
print (min(lista)) |
ffd036d8b583ea7ab02d48c1a278c70d0dca6d94 | AveryS00/advent-of-code | /2020/day16/main.py | 3,586 | 3.90625 | 4 | from typing import List, Dict, Tuple
class Range:
def __init__(self, lower: int, upper: int):
self.lower: int = lower
self.upper: int = upper
def __lt__(self, other):
"""If the lower bound of the other range is within this range, return True.
Return False otherwise.
""... |
1123279e493d7273f4f6f36136dadb3d48fadf7b | AveryS00/advent-of-code | /2020/day9/main.py | 1,113 | 3.671875 | 4 | from typing import List
def validate_num(num: int, index: int, preamble_len: int, xmas_list: List[int]) -> bool:
possible_vals = xmas_list[index-preamble_len:index]
for i in possible_vals:
if num - i in possible_vals and num - i != i:
return True
return False
def find_invalid_num(pre... |
dea18ed1dcc6504cf5d31352a5f76485418e18d6 | catalanjrj/Learning-Python | /exercises/ex19.py | 1,560 | 4.21875 | 4 | # create a function named chees_and_crackers with two arguments.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# print the amount of cheeses.
print(f"You have {cheese_count} cheeses!")
# print the number of boxes of crackers.
print(f"You have {boxes_of_crackers} boxes of crackers!")
# print "Man t... |
5bbf167d0de558186b79ad5aade880d6119973fb | catalanjrj/Learning-Python | /exercises/ex4.py | 1,232 | 4.15625 | 4 | # Assign a value of 100 to cars
cars = 100
# Assign a value of 4 to space_in_a_car
space_in_a_car = 4
# Assign a value of 30 to drivers
drivers = 30
# Assign a value of 90 to passengers
passengers = 90
# Assign the result of cars minus drivers to cars_not_driven
cars_not_driven = cars - drivers
# Assign the value... |
bd78e1b03375bf0f0b0e0441d14514c7be9ed90b | whitejetyeh/Insight | /holotalk/holotalk/LRsymmetrizer.py | 2,949 | 3.671875 | 4 | '''
Symmertrizer replicates the right half part of human face to the left half part.
Wether the input yawing left or right, the feed_processor converts the input image
to be yawing left and combines it with the lefthand side image of people yawing left.
The output_processor converts the reconstructed input back to fron... |
6d9e1dcc8a8ae658d7988daa2ebee5ef4d496b54 | rgarcia5/project_euler | /python/problem4.py | 406 | 3.875 | 4 | def is_palindrome(num):
string = str(num)
i = 0
while (i < len(string)):
if (string[i] != string[len(string) - i - 1]):
return False
i += 1
return True
def largest_product():
i = 999
result = 0
while (i > 0):
j = i
while (j > 0):
if (is_palindrome(i * j) and i *j > result):
... |
44fd926313d583e4eb7a8acf819ad43a475abeab | rgarcia5/project_euler | /python/problem12.py | 410 | 3.578125 | 4 | import math
def generate_triangular_num(n):
return reduce((lambda x,y: x + y), range(1,n + 1))
def number_of_factors():
i = 2
while True:
count = 0
triangle_num = generate_triangular_num(i)
j = 1
while (j < math.sqrt(triangle_num)):
if (triangle_num % j == 0):
count += 2
j +=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.