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 |
|---|---|---|---|---|---|---|
88719d77a0a0f053589a0a8feb034f60ecbac703 | renatofj/Project-Euler | /solved/20.py | 205 | 3.5625 | 4 | # Find the sum of the digits in the number 100! Solution: 648
def factorial(x):
f = 1
for i in range(1, x + 1):
f = f * i
return f
f = factorial(100)
print(f)
print(sum(list(map(int, str(f))))) |
a632fd4f6adf90783903be2d7332190be74c436b | renatofj/Project-Euler | /44.py | 449 | 3.578125 | 4 | import math
def ispentagonal(n):
s = (math.sqrt(24*n+1)+1)/6
return s == int(s)
def pentagonal():
n = 1
while True:
yield (n*(3*n-1))/2
n += 1
def solution():
for pj in pentagonal():
for pk in pentagonal():
if pj != pk and ispentagonal(abs(pj-pk)) and ispe... |
528cae8b3a8f1cec3815e57f9302e9bd03685e29 | panditprogrammer/python3 | /python69.py | 199 | 3.609375 | 4 | # input from user using numpy
from numpy import *
a=int(input("Enter number of students :"))
b=zeros(a,dtype=int)
e=len(b)
c=0
while c<e:
d=int(input("Enter "))
b[c]=d
c+=1
print( "total =",b) |
a2996b73f852529591a8cbe4681e94fa110db8a3 | panditprogrammer/python3 | /python89.py | 188 | 3.8125 | 4 | #Formatting String video 94
#format () method part3
a="PanditProgrammer.com"
b=10
print("My Website is {} and rating is {}".format(a,b))
c=30
d=40
print("{:.2}".format(c/d))
print("{:.2%}".format(c/d)) |
c5f57f101774f386c9c208f4934425cd090364a3 | panditprogrammer/python3 | /python131.py | 215 | 3.5 | 4 | #Higher order function in python
# reduce function in python
from functools import *
# importing for reduce( )
a=[11,22,33,44,55,66,77,88,99,100]
result=reduce(lambda n,m:n+m,a)
print(result)
print(type(result)) |
c5e45a7b9a60af7fb26e05c5bee4b0ae56626039 | panditprogrammer/python3 | /Python Practice code/Arithmetic.py | 151 | 3.890625 | 4 | #Arithmetic Operator
a=10
b=12
total=a+b
print(a+b)
a=10
b=12
total=a-b
print(a-b)
a=10
b=12
total=ab
print(a-b)
a=10
b=12
total=a-b
print(a-b)
|
0459d6caa8b5aacf99a1e9fb0e4208d70c72c09c | panditprogrammer/python3 | /python88.py | 1,374 | 4.25 | 4 | #Formatting String video 94
#format () method part2
"""this is
multiline comments in python """
print("fomating string and method rules")
print("----------integer---------")
print("{}".format(15))
print("{:d}".format(15))
print("{0:d}".format(15))
print("{num:d}".format(num=15))
print("----------float---------\n")
pri... |
09aba74311bf75a9ac8531475ade7f2a09475242 | panditprogrammer/python3 | /python63.py | 369 | 3.515625 | 4 | #68.any and all Functions in Python
from numpy import *
a=array([15,12,13,34,15])
c=array([15,12,13,34,15])
b=array([11,12,83,34,18])
print(any(a==b)) #any elements equal in array a and b, a==b its return True
print(all(a==b)) #all elements equal in array a and b, a==b its return False
print(all(a==c)) #all elemen... |
0444c0896bdbd8c4a6f8cc235cb25f200e1baa24 | panditprogrammer/python3 | /Python Practice code/if.py | 78 | 3.671875 | 4 | int=a(print("Enter a number" a))
if a>=0:
print("positive number")
|
83c33d7ffe87715f233c63902d36bcfdab77460a | panditprogrammer/python3 | /python72.py | 354 | 4.40625 | 4 | # creating 2D array using zeros ()Function
from numpy import *
a=zeros((2,3) ,dtype=int)
print(a)
print("This is lenth of a is ",len(a))
n=len(a)
for b in range(n):
# range for index like 0,1,in case of range 2.
m=len(a[b])
print("This is a lenth of a[b]",m)
for c in range(m):
#print("This is inner for loop")
... |
20b6dc04b7839b15cbfe78e66990316d36d7e5ff | panditprogrammer/python3 | /Python Practice code/forloop.py | 242 | 3.5 | 4 | #for loop all concept
st="This is my pro."
for ch in st:
print(ch)
print("here rest of the code")
for i in range(7):
print(i)
n=len(st)
for i in range(n):
print(i ,"=",st[i])
print("then rest of the code") |
d975c4042fe5752750ad7eca891850d591fd0b8b | panditprogrammer/python3 | /Tkinter GUI/tk_python03.py | 389 | 3.890625 | 4 | #Entry in windows input field
from tkinter import *
#creating a object name root of Tk
root=Tk()
root.geometry("400x400")
root.resizable(0,0)
# creating a label and input prompt using Label() and Entry()
user_name_label=Label(root,text="Enter Your Name",font=("Arial ",16),fg="blue",bg="red").pack()
user_name =Entry(r... |
a50e75a6ff5d2c386f4f193ff3fede105b0619cf | panditprogrammer/python3 | /pycode14.py | 346 | 3.84375 | 4 | a=int(input("Enter number"))
b=int(input("Enter number"))
# c= sum((a,b))
# print(c)
def addi(a,b):
"""This is function for calculating average of two number"""
print(" This is function")
v=(a+b)/2
print("average",v)
# return v
s=addi(a,b)
print(addi.__doc__) # This is called doc string for gett... |
79345424ee4c13980c886ad3ec009c736b5c79ae | panditprogrammer/python3 | /pycode02.py | 340 | 3.9375 | 4 | # variables datatypes and typecasting
var1="Hello world"
var2= 4
var3= 78.3
print(var1,var2,var3)
print(type(var1),type(var2),type(var3))
# typecasting
# print(type(int(var3)))
# print(type(int(var2)))
# print("Enter number")
# n=int(input())
# print(n,type(n))
# print(n)
a=int(input("Enter a number"))
b=int(input("Ent... |
deeb8ae3e2a81116d0d9beec7683669e20885644 | panditprogrammer/python3 | /python157.py | 406 | 4.0625 | 4 | # This is called set comprehension
scom={ ((i-j),(i+j)) for i in range(20,34,3) for j in range(50,60,2)}
# print(scom)
# dictionary comprehension in python
dict0={}
for i in range(10):
dict0[i]=(10-i)
# print(dict0)
dict1={i:i+10 for i in range(0,100,12) } #this is called comprehension
print(dict1)
lit=[(10,"one"... |
9fdcf03a227850f99153d4948c26c3415ccb34f2 | panditprogrammer/python3 | /Tkinter GUI/tk_python01.py | 774 | 4.28125 | 4 | from tkinter import *
#creating a windows
root=Tk()
# geometry is used to create windows size
root.geometry("600x400")
# To creating a label or text you must use Label class
labelg=Label(root,text="This is windows",fg= "red", font=("Arial",20))
# fg for forground color and bg for background color to change font colo... |
08f1705a31cdc9b5a0199606bc3fe99abee6a6fa | panditprogrammer/python3 | /Python Practice code/arrayloop2.py | 153 | 3.8125 | 4 | #accessing array using for loop
from array import *
sturo=array('i',[101,102,103,104,105,106])
n=len(sturo)
i=0
while (i<n):
print(sturo[i])
i+=1 |
6813a75d35490defbf678287c5c13a06732aa90e | panditprogrammer/python3 | /python142.py | 283 | 3.875 | 4 | # Deleting Element in set using discard and Remove
# remove raise error if element does't exist descar not
a={10,29,"pp",80}
a.discard("pp")
print(a)
a.update("pandit","panditprogrammer")
print(a)
a.discard("pp")
# accessing element using for loop video185
for i in a:
print(i) |
ef1981a7b13dcbffc4406d2043e8feaac2c63e90 | panditprogrammer/python3 | /python138.py | 267 | 3.65625 | 4 | # passing a tuple in function in python
# returning a tuple from function video178
def fuc1(n):
print(n)
for i in n:
print(i)
print(type(n))
b=(12,87)
return n+b
a=(1,20,23,87)
s=fuc1(a)
print(s)
for i in s:
print(i)
print(type(s))
|
ffae30c198f5a7132713304fcb3d0a2a0d4962a6 | panditprogrammer/python3 | /python78.py | 860 | 4.46875 | 4 | # slicing array in multi dimensional array in python
#video 83\
from numpy import *
# a=array([[11,13,17],
# [11,12,13],
# [21,22,23] ])
# print("array after printing")
# print(a)
# print("1st row 2nd coloum")
# b=a[1,2 ]
# print(b)
# print("2nd coloum")
# c=a[0:1,0:1]
# print(c)
x=array ([
[1,2,3,4,5,]... |
c3ef397ae174f3df14c677d864abb0e89f103746 | panditprogrammer/python3 | /python160.py | 260 | 3.875 | 4 | # membership operator in python "in " and "not in"
ex=[10,20,30,40,7,83,23,15,41]
ex1=(10,20,30,40,7,83,23,15,41)
a={1:"python",2:'java',3:"c",4:"c++"}
print(83 in ex)
print(83 in ex1)
print(83 not in ex1)
print(83 not in ex1)
print(4 in a )
print(4 not in a ) |
cd7b38bf1f1a01ede8163ef0dc324fa06b503eda | panditprogrammer/python3 | /python45.py | 204 | 3.96875 | 4 | #Append method in python using while loop
from array import *
a=array("i",[11,12,13,14,15,16,17,18,19,20])
b=len(a)
c=0
while c<b:
print(c,"=",a[c])
c+=1
a.append(int(input("Enter number :")))
print(a) |
5e18536912ed061cb904f8105c6bcc4b15228d07 | panditprogrammer/python3 | /python68.py | 186 | 3.703125 | 4 | # input from user using numpy
from numpy import *
a=int(input("Enter number of students :"))
b=zeros(a,dtype=int)
e=len(b)
for c in range(e):
d=int(input("Enter "))
b[c]=d
print(b) |
49dc7eb12f5c8f0af173a95af416f70c8c775c31 | panditprogrammer/python3 | /python48.py | 162 | 3.65625 | 4 | #insert methon in python
from array import *
a= array('i',[])
b=int(input("Enter number :"))
c=0
while c<b:
a.append(int(input("Enter R :")))
c+=1
print(a)
|
795df29b700acf03d497a203a93fe4343ef6a1d5 | panditprogrammer/python3 | /python150.py | 252 | 3.546875 | 4 | # getting keys from dictionary
s={10:"rahul",11:"dinesh",12:"sharma"}
print(s.keys())
# getting value from dictionary video 202
print(s.values())
s.update({16:"ritu"})
print(s)
# popitem method in dictionary video 205
rs=s.popitem()
print(rs)
print(s) |
b582e00513dc06af97b9bb8b87e90feee03c6782 | detel/Project-Euler | /CountDivisors.py | 359 | 3.796875 | 4 | from math import sqrt
def count_divisors(num):
divisors = []
SQRT = sqrt(num)
for i in xrange(1,int(SQRT)+1):
if i == SQRT:
divisors.append(i)
elif num%i == 0:
divisors.extend([i,num/i])
return len(divisors)
n = 1
while True:
triangle_number = (n*(n+1))/2
if count_divisors(triangle_number) > 500:
... |
fadae9167f289ed36909a1ad16b093cf81346cc8 | detel/Project-Euler | /paths_dp.py | 354 | 3.515625 | 4 | def paths(num):
distance = [[0 for i in xrange(num+1)] for j in xrange(num+1)]
distance[0][0] = 0
for i in xrange(1,num+1):
distance[i][0] = 1
for j in xrange(1,num+1):
distance[0][j] = 1
for i in xrange(1,num+1):
for j in xrange(1,num+1):
distance[i][j] = distance[i-1][j] + distance[i][j-1]
return di... |
3521f7d84630164b393757e2e734d26f74756c0f | BarnabasK/maxmin_lab | /max_min.py | 236 | 3.96875 | 4 | def find_max_min(numbers):
min_num=min(numbers)
max_num=max(numbers)
if max_num != min_num:
return [min_num,max_num]
else:
return [len(numbers)]
print find_max_min([1,4,7,2,8])
print find_max_min([41,42]) |
6cb6f4bc8cc4036cf46368edf14ac70313a727c3 | verneyleaf/test | /regular.py | 362 | 3.671875 | 4 | # -*- coding:utf-8 -*-
import re
s = 'cats are smarter than dogs'
result = re.match(r'(.*) are (.*?) (.*)', s)
print (result)
print ('\n')
print (type(result.group()))
#if type(result.group()) == 'str':
print (len(result.group()))
print (result.group(0))
print (result.group(1))
print (result.group(2))
print (result.g... |
bd1273bc8ef932244d2d8e681a7c49df34f0e748 | guoy2019/guoya001 | /py-01/py-001/match-01.py | 272 | 3.75 | 4 | #print(1+1)
#print(2-1)
#print(3*2)
#print(6/3)
#print(2%3)
#a=20
#b=30
#print(a+b)
#print(a-b)
#print(a*b)
#算数平方
#print(2**5)
#字符串,元组,列表可用“+”拼接
a=[12,23,34,45]
b=[23,34,13,35]
print(a+b)
a="12233445"
b="23341335"
print(a+b)
|
71722104d6e8be3a73bbc6913cbd4d73990a9d52 | jmarietta1/pythonfiles | /exercise1.py | 150 | 3.859375 | 4 | def addition():
first=int(raw_input('what is your first number'))
second=int(raw_input('what is your second number'))
print(first+second)
|
ac2c99f6517d89d6ab16eeb51f149f123ccdcbe5 | KofujiBlank/test | /Python/learning.py | 4,632 | 3.875 | 4 | # coding: utf-8
print("#スコープ")
message = "paiza"
a = 10
b = 20
def sum(x, y):
a = 3
global message
message += "paiza"
print(message + " " + str(a))
return x + y
num = sum(a, b)
print(num)
print(message + " " + str(a))
print("#クラス内でメソッドを定義するときはselfを定義しないといけない")
class Player01:
# クラスからオブジェクトを作ると... |
26230d0e8b712a5ea37bb008e578768ed322b5c7 | jktheking/MLAI | /PythonForDataScience/ArrayBasics.py | 1,027 | 4.28125 | 4 | import numpy as np
array_1d = np.array([1, 2, 3, 4, 589, 76])
print(type(array_1d))
print(array_1d)
print("printing 1d array\n", array_1d)
array_2d = np.array([[1, 2, 3], [6, 7, 9], [11, 12, 13]])
print(type(array_2d))
print(array_2d)
print("printing 2d array\n", array_2d)
array_3d = np.array([[[1, 2, 3], [6, 7, 9]... |
5ed85898864a4d15e5e155fc315e6cebe435a900 | kwantaing/Python_OOP | /Party_oop_exercise/partyOOPwithguestObj.py | 868 | 3.65625 | 4 | class Party:
def __init__(self,cap):
self.capacity = cap
self.guests = []
# def introduceGuest(self,name,age,gender):
# newGuest = Guest(self,name,age,gender)
# self.welcomeguest(newGuest)
def welcomeguest(self,guest):
if(len(self.guests)<self.capacity):
s... |
c2f91e664973c9b3f33976a0306873ff0ff73206 | tommiu/GithubSpider | /github/oauthManager.py | 9,936 | 3.546875 | 4 | '''
Created on Jul 21, 2015
@author: Tommi Unruh
'''
import requests as r
import getpass
import json
import os
class OAuthManager(object):
"""
Manages creation and loading/parsing of authorization data for Github.com.
"""
KEY_OAUTH = "OAuth"
KEY_USER_AGENT = "user_agent"
def __init__(self, ... |
636216ea4ad221d0fe7fa64de742380c752c9664 | okazelnik/ML_hackathon | /decision_tree.py | 5,756 | 4.0625 | 4 | """
===================================================
Introduction to Machine Learning (67577)
===================================================
Skeleton for the decision tree classifier with real-values features.
Training algorithm: ID3
Author: Noga Zaslavsky
Date: April, 2016
"""
import numpy as np
import... |
91379d16025858cd4ef59ee00e9fdc3c4e8ccfb6 | themockingjester/leetcode-python- | /1381. Design a Stack With Increment Operation.py | 1,718 | 3.65625 | 4 | class Node():
def __init__(self):
self.val = 0
self.next = None
class CustomStack:
def __init__(self, maxSize: int):
self.height = 0
self.maxheight = maxSize
self.bottom = None
def push(self, x: int) -> None:
k = Node()
k.val = x
if sel... |
b9009ad4958b998ca86926467533b05a8f2a76bb | themockingjester/leetcode-python- | /151. Reverse Words in a String.py | 243 | 3.609375 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
s=s.strip()
lis = s.split(" ")
lis=lis[::-1]
print(lis)
temp = [i for i in lis if i!=""]
new=" ".join(temp)
return new
|
51f87b5158a4f7d29cd76bd9903793e5f264cc89 | themockingjester/leetcode-python- | /382. Linked List Random Node.py | 808 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def __init__(self, head: ListNode):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null,... |
7692a9c8fcf9a61b1290804ef660081f4541ade3 | themockingjester/leetcode-python- | /1832. Check if the Sentence Is Pangram.py | 349 | 3.578125 | 4 | class Solution:
def checkIfPangram(self, sentence: str) -> bool:
ele = 'a'
result = False
while True:
if ele in sentence:
result = True
if ele == 'z':
return True
else:
return False
ele = ... |
f8505b10e3719b5e08f5be8889a102c083ad4539 | themockingjester/leetcode-python- | /328. Odd Even Linked List.py | 707 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
ctr=1
even=[]
odd=[]
while head:
if ctr%2==0:
... |
e29b74c03669682f258c7dfe3334efbd75f4835a | themockingjester/leetcode-python- | /83. Remove Duplicates from Sorted List.py | 723 | 3.59375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
lis=[]
while head:
lis.append(head.val)
head... |
91c7bd12a3e8f99a9b2f125fc53162c6421d81fd | themockingjester/leetcode-python- | /654. Maximum Binary Tree.py | 1,447 | 3.703125 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildtree(self,lis,node,isleft):
maxi = max(lis)
maxindex = lis.index(maxi)
lef... |
7340b90845bda2b350d331de9a80bbc5167b9509 | themockingjester/leetcode-python- | /897. Increasing Order Search Tree.py | 835 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def check(self,root):
if root:
self.lis.append(root.val)
self.check(root.lef... |
b97fc5c39509ace74ce7f44b34dabb9d17e64ef9 | themockingjester/leetcode-python- | /23. Merge k Sorted Lists.py | 735 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
lis=[]
for i in lists:
head = i
while head:
... |
0b0cf7c3179553f93b9e5091959535bfc82ff64f | themockingjester/leetcode-python- | /257. Binary Tree Paths.py | 1,102 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def check(self,root,s):
if root:
if root.left==None and root.right==None:
... |
59228a1eebd5c0b2b1d4d5f9645492187e7b226c | themockingjester/leetcode-python- | /11. Container With Most Water.py | 1,512 | 3.515625 | 4 | # my approach but with recursion hence throughing TLE at test case 55 out of 60
# class Solution:
# def check(self,lower,upper):
# if lower < upper:
# base = len(self.lis[lower:upper])
# print(base)
# if self.lis[lower]>=self.lis[upper]:
# height = self.li... |
5a703a662c4cbbf760270708f2e1875f841c0f84 | themockingjester/leetcode-python- | /316. Remove Duplicate Letters.py | 404 | 3.5 | 4 | from collections import Counter
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
lis = []
count = Counter(s)
for i in s:
count[i]-=1
if i not in lis:
while len(lis)!=0 and lis[-1]>i and count[lis[-1]]!=0:
... |
fdf2ca50105b52927d7e1b0d90b989c45ebeb797 | BattleOfBrands/BattleField | /tests/integration/brand_impact/test_impact_generated.py | 1,340 | 3.5 | 4 | import unittest
from brand_impact.metric import BrandImpact
class MyTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.brand_impact = BrandImpact(h=1000, w=1000)
def test_full_impact(self):
# "brands": [
# {
# "name": "<brand_name>",
# ... |
97ad058655604e7069b5bee1eabf6f345990ea2c | haclark30/ctci | /chapter_1/1_7_rotate_matrix.py | 549 | 3.75 | 4 | def rotate_matrix(matrix):
n = len(matrix)
for layer in range(n//2):
start = layer
end = n-1-layer
for i in range(start, end):
offset = i - start
top = matrix[start][i]
matrix[start][i] = matrix[end-offset][start]
matrix[end-offset][star... |
71d4149c69b12b47e09177838770a9f722fa479a | Rashi0206/Assignment | /p8.py | 816 | 3.890625 | 4 | # -*- coding: utf-8 -*-
class Car():
def __init__
(self,make,model,color,price):
self.make = make
self.model = model
self.color = color
self.price = price
self.speed=0
def start(self):
self.speed=0
return self.speed
def move(self... |
cbba10ae857098b84ced29117e6e0cb85eec6ac1 | m-RezaFahlevi/Mathematica-Works | /Notebooks/Naive.py | 328 | 3.90625 | 4 | # %%
def Naive(N):
is_prime = True
if N <= 1 :
is_prime = False
else:
for i in range(2, N, 1):
if N % i == 0:
is_prime = False
return(is_prime)
def main():
N = 139
print(f"{N} prime ? : {Naive(N)}")
if __name__=="__main__":
main()... |
c32ee7a799f325db6bc34e70ff64c0ce6d303feb | m-RezaFahlevi/Mathematica-Works | /Notebooks/poisson.py | 754 | 3.65625 | 4 | """
Author : Muhammad Reza Fahlevi
Dated : January 12th, 2021
Affiliation : Departemen Ilmu Komputer,
Fakultas Ilmu Komputer - Teknologi Informasi,
Universitas Sumatera Utara, Medan, Indonesia
"""
import numpy as np
factorial = lambda n : 1 if n == 0 else n * factorial(n - 1)
poisson = lambda x, mura... |
e52c0b8fdf5a0518d71a2e3926df924ed1c0beb8 | m-RezaFahlevi/Mathematica-Works | /Heuristics/uniformcostsearch_kuliah.py | 5,069 | 4.28125 | 4 | """
Author : Muhammad Reza Fahlevi
Dated : March 13th, 2021
Affiliation : Departemen Ilmu Komputer,
Fakultas Ilmu Komputer - Teknologi Informasi,
Universitas Sumatera Utara, Indonesia
References : Benjamin Baka. Python Data Structures and Algorithms. 2017. Packt... |
d754c311a2550c11f87fa1416dd83ac192e8183d | 16602710209/webdriverTest | /Test/PythonTest/Test2/myMath.py | 1,286 | 3.734375 | 4 | # 创建一个类
class mymath():
def jia(self, a, b):
if isinstance(a, str) and isinstance(b, int):
b = str(b)
return a+b
elif isinstance(a, int) and isinstance(b, str):
a = str(a)
return a+b
else:
return a+b
def jian(self, a, b):
... |
ca61dcd177b393e04153b09873be709582412a83 | PacktPublishing/big-data-analytics | /Chapter 4/DataSourceJson.py | 662 | 3.515625 | 4 | # Copy input dataset(people.json) to HDFS and then get into PySpark Shell. To read json file, use format to specify the type of datasource.
df_json = spark.read.load("people.json", format="json")
df_json = spark.read.json("people.json")
df_json.printSchema()
df_json.show()
# To write data to another JSON fi... |
4f9338211ede4e6f4bcc7a21e6e6d64f1baa61cc | PacktPublishing/big-data-analytics | /Chapter 4/CreatingDataFrames.py | 1,595 | 3.5625 | 4 | # Get into PySpark shell and execute below commands.
mylist = [(50, "DataFrame"),(60, "pandas")]
myschema = ['col1', 'col2']
# Method1: Create a DataFrame with a list, schema and default data types.
df1 = spark.createDataFrame(mylist, myschema)
# Method2: Create a DataFrame by parallelizing list and convert ... |
3ad5e932525a158e0b564888e587b040ea424372 | PacktPublishing/big-data-analytics | /Chapter 4/DataSourceJDBC.py | 1,047 | 3.75 | 4 | # Get into PySpark shell. Create DataFrames using one of the two methods below and then work on them.
#Method1
df1 = spark.read.format('jdbc').options(url='jdbc:mysql://localhost:3306/retail_db?user=root&password=cloudera', dbtable='departments').load()
df1.show()
#Method2
df2 = spark.read.format('jdbc').opt... |
71924b5d22086a15c32c8e30cc39f449e7b608fa | duttaa19/model-in-keras-lynda | /model/train_model.py | 1,143 | 3.59375 | 4 | import pandas as pd
from keras.models import Sequential
from keras.layers import *
training_data_df = pd.read_csv("sales_data_training_scaled.csv")
X = training_data_df.drop('total_earnings', axis=1).values
Y = training_data_df[['total_earnings']].values
# Define the model
model = Sequential()
model.add(Dense(64, in... |
9486104e02023bf4eca72e27d81fa4708806f527 | fancy0815/Fan_Fount_hhkr101 | /4_set/3_add.py | 217 | 4.03125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
set_country = set()
for i in range(n):
country_name = str(input())
set_country.add(country_name)
print(len(set_country))
|
dc6a6f4a8d8be6e0cf3cc4aff0176961d7a8e611 | mashiranna/codereview | /mashyram/second/task3.py | 354 | 3.59375 | 4 | """
Вивести суму парних та суму непарних чисел
"""
print("Введіть числа")
S = input()
list = [S.split( )]
sumparne = 0
sumneparne = 0
for i in list:
if i%2 == 0
sumparne += i
else :
sumneparne += i
print("Сума парних" + sumparne + "Cума непарних" + sumneparne) |
0ac1de87464b103ebf21bb3da41b8d0b1eeeb2b6 | AtulRajput01/Data-Structures-And-Algorithms-1 | /algorithms/python/Convex_Hull.py | 1,985 | 3.984375 | 4 | class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def Left_index(points):
minn = 0
for i in range(1, len(points)):
if points[i].x < points[minn].x:
minn = i
elif points[i].x == points[minn].x:
if points[i].y > points[minn].y:
... |
bd48356cbcf6e50f44dd26a88b8b8e2178311ef0 | AtulRajput01/Data-Structures-And-Algorithms-1 | /sorting/python/heap-sort.py | 1,331 | 4.15625 | 4 | """
Heap Sort
Algorithm:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1.
Finally, heapify the root of the tree.
3. Repeat step 2 while the size of the heap is greater t... |
c2468fb06d3b52cc0181f5a7f0f1515db31cb977 | StarStudyStart/PythonBasicSpace | /unittest/test_survey.py | 953 | 3.5625 | 4 | import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
'''测试匿名调查类能否准确的输出属性'''
def setUp(self):
'''创建一次对象,在后续每个单元测试都可以使用'''
question = " What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.response... |
24274d568477236135a8b822e9a7d5caa25c50e0 | StarStudyStart/PythonBasicSpace | /week01/LoopTest.py | 105 | 3.609375 | 4 | #LoopTest.py
n= 0
while True:
n = n+1;
if n % 2 == 0:
continue
print(n)
print("END")
|
46a8a8ca487ba09a7ff5b0ab731029befc295c46 | christian-chen12/basic-shipping-calculator | /Shipping calc.py | 1,267 | 4.09375 | 4 | #User message and weight input
print('Hello, how much does your package weigh?')
weight = input()
#FIRST SHIPPING METHOD
premium_ground_shipping = 125.00
#SECOND SHIPPING METHOD
def ground_shipping(weight):
if weight > 10:
return (weight * 4.75) + (20.00)
elif weight > 6:
return (weight * 4.00) + (20.00... |
44461dce4b681518724ddcc01eed19a58126003d | carrep27/python-challenge | /PyBank/main.py | 3,861 | 3.796875 | 4 | import os
import csv
month = []#create empty list for month
revenue =[]#crete empty list for revenue
changeinrevenue =[]#create empty list for change in revenue
csvpath = os.path.join("budget_data_1.csv")#declare path to csv file
with open(csvpath, newline='', encoding='utf-8') as csvfile: #open and read csvfile
cs... |
7deb2d43fbf45c07b5e2186c320e77bdad927c18 | iAmAdamReid/Algorithms | /recipe_batches/recipe_batches.py | 1,487 | 4.125 | 4 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients, count=0):
# we need to globally track how many batches we've made, and pass recursively
# TODO: find how to do this w/o global variables
global batches
batches = count
can_cook = []
# if we do not have any necessary ingredient, return ... |
5423de6aa6e58f2fd0aafc5c085f26af059e4558 | nestor1991/bootcamp | /dia1.py | 3,385 | 4.1875 | 4 | print(2+2)
print(2+4)
print(3*6)
print(32+8)
print(76/3)
#la union de palabra mas numeros
print("hola mundo!") #usar comillas para palabras
print("hola"*55) #multiplica las palabras
print("hola"+"feliz dia") #unen (+) las palabras
a = "hola"#si la variable equivale a un texto debe ir entre comillas
b=10
print(a*... |
32cd09efb118604e0d5c2e521046e64e8ad1c33f | solcra/pythonEstudio | /cadenas.py | 524 | 4.15625 | 4 | texto = "Prueba dos dos"
print("Upper")
print(texto.upper())
print("Lower")
print(texto.lower())
print("Capitalize")
print(texto.capitalize())
print("Count")
#print(texto.count())
print("Fing")
#print(texto.fing())
print("Isdigit")
print(texto.isdigit())
print("Isalnum")
print(texto.isalnum ())
print("Isalpha")
print(t... |
e963ce521ee5e42e45e7814c46274439ac3ba2fd | solcra/pythonEstudio | /generadores.py | 1,015 | 3.84375 | 4 | #Funcion
def generaPares(limite):
num=1
miLista=[]
while num<limite:
miLista.append(num*2)
num +=1
return miLista
print(generaPares(10))
#Interador
def generaPares2(limite):
num=1
while num<limite:
yield num*2
num +=1
devuelvePares=generaPares2(10)
for i in devuelvePares:
print(i)
devuelv... |
426694e5bb7f8c92421113e61e981d81fea43046 | TaeHongGil/study | /tileornaments.py | 1,269 | 3.765625 | 4 | def solution(N):
a,b=2,4
for i in range(1,N):
a,b=b,a+b
return b
N=2
print(solution(N))
'''
타일 장식물
문제 설명
대구 달성공원에 놀러 온 지수는 최근에 새로 만든 타일 장식물을 보게 되었다. 타일 장식물은 정사각형 타일을 붙여 만든 형태였는데, 한 변이 1인 정사각형 타일부터 시작하여 마치 앵무조개의 나선 모양처럼 점점 큰 타일을 붙인 형태였다. 타일 장식물의 일부를 그리면 다음과 같다.
그림에서 타일에 적힌 수는 각 타일의 한 변의 길이를 나타낸다... |
4b51afcbf12f23310405f481f6acf9165407e058 | tushar-nitave/fake-new-classification | /code/dm.py | 977 | 3.6875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import statistics
data = pd.read_csv("agreed.csv", sep=",")
a = data['s1tos2'].mean()
b = data['s2tos1'].mean()
print(f'Mean for s1tos2: {a:.4f}')
print(f'Mean for s2tos1: {b:.4f}')
am = (a+b)/2
print(f'Overall Mean for Agreed: {am:.4f}')
s1tos2 = data['s1tos2'].t... |
558176338c1c64b47a348b4477a186521b1ecee4 | Valen0320/TutorialesPython | /ejercicio7.py | 332 | 3.53125 | 4 | v1=int(input("Ingrese el primer valor:"))
v2=int(input("Ingrese el segundo valor:"))
v3=int(input("Ingrese el tercer valor:"))
v4=int(input("Ingrese el cuarto valor:"))
suma=v1+v2+v3+v4
promedio=(v1+v2+v3+v4)/4
print("La suma de los cuatro valores es")
print(suma)
print("El promedio de los 4 valores es")
print... |
f473e65eb5c5f45f1f8a73344f6799246853ecac | Valen0320/TutorialesPython | /ejercicio21.py | 166 | 3.640625 | 4 | dia=int(input("Ingrese dia:"))
mes=int(input("Ingrese mes:"))
año=int(input("Ingrese año:"))
if dia=25 and mes=12:
print("La fecha correcponde a navidad")
|
2236aa4dd27088821338b1b89a70cf8ec527f7e3 | Valen0320/TutorialesPython | /ejercicio14.py | 276 | 3.828125 | 4 | n1=int(input("Ingrese primer nota"))
n2=int(input("Ingrese segunda nota"))
n3=int(input("Ingrese tercera nota"))
promedio=(n1+n2+n3)/3
if promedio>=7:
print("Promocionado")
else:
if promedio>=4:
print("Regular")
else:
print("Reprobado")
|
12c91265500f6d7720ebd479b2c953f69a5b5a94 | noahhenry/python_for_beginners | /challenges/refactor_max_number_into_module.py | 228 | 4.03125 | 4 | # numbers = [10, 3, 6, 2]
# max = numbers[0]
# for number in numbers:
# if number > max:
# max = number
# print(max)
import max_number_utils_module
result = max_number_utils_module.find_maximum([1,2,7,3,4])
print(result) |
9d6c5130c61b682b0de8397aee721303d56f4685 | noahhenry/python_for_beginners | /notes/built-in_module_random.py | 322 | 4.15625 | 4 | import random
for i in range(3):
print(random.random())
# what if you want to limit the range of random numbers returned?
# use random.randint() and pass in the range...
for i in range(3):
print(random.randint(10, 20))
members = ["John", "Marry", "Bob", "Mosh", "Noah"]
leader = random.choice(members)
print(leade... |
4dcc344376f1079536c52aa80b415ee1b32178a2 | freephys/algorithms_illuminated | /algorithms_illuminated/part_2/chapter_9/graph_dijkstra.py | 12,921 | 3.828125 | 4 | '''
This module implements a graph data structure and implementations of Dijkstra's
algorithm.
Implementations are based on the exposition and pseudo-code in Algorithms Illuminated Part 2.
'''
from collections import defaultdict
import timeit
import numpy as np
from test_cases import *
import sys
import os
sys.path.ap... |
b6dce212955c27cb46ed3dcc46b8906ba626e936 | ritzyag/Narmada-server | /extract_resource_covid.py | 1,944 | 3.6875 | 4 | text_org = input("Enter text, or press return for an example: ")
import location
import pudb
from nltk.tokenize import word_tokenize
if text_org == "":
text_org = "Oxygen producing unit at Princess Esra Hospital (Owaisi Group of Hospitals). #Oxygen #IndiaNeedsOxygen #IndiaFightsCOVID19 @aimim_national @imShaukatAl... |
ed624852c9fe9632b4fc29525590da6c2666a526 | mwk48/cs50_solutions | /pset6/cash.py | 319 | 3.609375 | 4 | from cs50 import get_float
s=get_float("Change owed: ")
temp=int(s*100)
count=0
while temp!=0:
while temp>=25:
count+=1
temp-=25
while temp>=10:
count+=1
temp-=10
while temp>=5:
count+=1
temp-=5
while temp>=1:
count+=1
temp-=1
print(count) |
efbbf73be5efdde60ab1fa843249a46193912f19 | rohaan-ahmed/Master-Repository | /Course Assignments/CP8318 - Machine Learning Assignments/CP8318 Assignment 2 - Rohaan Ahmed/spam/spam_rohaan.py | 11,176 | 3.96875 | 4 | import collections
import string
import numpy as np
import util
import svm
def get_words(message):
"""Get the normalized list of words from a message string.
This function should split a message into words, normalize them, and return
the resulting list. For splitting, you should split on spaces. For nor... |
1a8b7728bcf5e5ffc5d1c02219e68985deb5d60a | YorkShen/LeetCode | /python/week5/49.py | 801 | 3.546875 | 4 | from collections import Counter
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
ret = {}
for item in strs:
key = str(sorted(list(item)))
if key in ret:
ret[key].appe... |
98e9eafa4312103ee6c671ec1153f02423eb332c | YorkShen/LeetCode | /python/week9/290.py | 1,192 | 3.5 | 4 | class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if pattern and str:
words = str.split()
if len(words) == len(pattern):
pattern_indexes = {}
word... |
528ebeee48f824344429ee7d7548986592b5e6a5 | YorkShen/LeetCode | /python/week9/102.py | 900 | 3.84375 | 4 | from collections import deque
# Definition
# for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List... |
009d9bfe9506de4d31769f0d40349bd800c4e0a0 | YorkShen/LeetCode | /python/week7,8/88.py | 675 | 3.765625 | 4 | class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
p1 = m - 1
p2 = n - 1
tail ... |
d9fa47dd0efd01132cccebd78950d7f2abb82ed4 | YorkShen/LeetCode | /python/week11/224.py | 971 | 3.515625 | 4 | class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
result, num, sign = 0, 0, 1
for letter in s:
if letter.isdigit():
num = num * 10 + int(letter)
elif letter == '+':
... |
0e497963f4c9f3a15a7e02fb8342ce3e0a3395ee | YorkShen/LeetCode | /python/week10/124.py | 928 | 3.96875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.max_value = 0
def maxPathSum(self, root):
"""
:type root: TreeNode
:... |
9ac090b7edc58393712b147e9305ada1afad5af7 | YorkShen/LeetCode | /python/week5/61.py | 1,062 | 3.984375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head an... |
5c1b903f2784243384c20a3c730b86f33327d338 | YorkShen/LeetCode | /python/week4/44.py | 1,580 | 3.71875 | 4 | class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
s_length = len(s)
p_length = len(p)
s_pointer, p_pointer = 0, 0
s_match_index, p_match_index = -1, -1
while s_pointer < s_length:
... |
47bd7de8284016c46ff3f756171a9b87d64c160a | TUTElectromechanics/mm-codegen | /extras/hermite_element.py | 2,274 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Symbolic derivation of Hermite shape functions using SymPy.
Created on Thu Nov 2 13:38:34 2017
@author: Juha Jeronen <juha.jeronen@tut.fi>
"""
import sympy as sy
def construct(k):
"""Construct Hermite shape functions.
The result can be used for interpolati... |
c450238e7d7de9e2b82358d3be77bb3bc1f00159 | AshRaven521/BSUIR | /7 semestr/MZI/Lr3/main.py | 2,897 | 3.9375 | 4 | import random
def get_primes(start, stop):
print("start:", start, ", stop:", stop)
if start >= stop:
return []
primes = [2]
for n in range(3, stop + 1, 2):
for p in primes:
if n % p == 0:
break
else:
primes.append(n)
while primes an... |
1cdc6874a72c8fe8957efb70a9aea763a22b31ee | Elisha419/python-programs | /loop.py | 78 | 3.875 | 4 | z='0'
for i in range(5):
x=input("enter your number")
z=z+x
print(z)
|
4d7a61244380c6a51fbbed6db7e3bdd4848b66ff | dnlsyfq/vim | /animal_farm.py | 438 | 3.84375 | 4 | #!/usr/bin/python3
"""Our own little animal farm."""
import sys
def add_animal(farm,animal):
farm.add(animal)
return farm
def main(animals):
farm = set()
for animal in animals:
farm = add_animal(farm,animal)
print("We've got some animals on the farm:", ", ".join(farm) + ".")
if __name__=='__main... |
dc5ad16802a2c423b4bb5073f54a6d6860d69109 | aadilkhhan/File-in-python | /13_pr_09.py | 251 | 3.5625 | 4 | file1 = "this.txt"
file2 = "hiscore.txt"
# file2 = "copy.txt"
with open(file1) as f:
f1 = f.read()
with open (file2) as f:
f2 = f.read()
if f1 == f2:
print("Files are identical")
else:
print("Files are not identical") |
37e12673a8a0a71141846103b8830bec74a80866 | j6e/advent-of-code-2020 | /advent_of_code/02_password_philosophy/part_two/solution.py | 584 | 3.765625 | 4 | import re
from collections import Counter
regex = r"(\d+)-(\d+) (\w): (\w+)"
with open('advent_of_code/02_password_philosophy/input.txt', 'r') as f:
lines = ''.join(f.readlines())
matches = re.findall(regex, lines, re.MULTILINE)
correct = 0
for pos_one, pos_two, letter, password in matches:
pos_one, pos_two =... |
3833d7c4b1e25ee3047d932bee1fb05d8c3de78b | j6e/advent-of-code-2020 | /advent_of_code/04_passport_processing/two.py | 3,781 | 3.65625 | 4 | import re
from typing import List
"""
Expected fields
byr (Birth Year) - four digits; at least 1920 and at most 2002.
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
hgt (Height) - a number followed by either cm or in:... |
1f0d340225be278ee074362f280207a60be9ed63 | Ardra/Python-Practice-Solutions | /chapter3/pbm11.py | 332 | 4.125 | 4 | '''Problem 11: Write a python program zip.py to create a zip file. The program should take name of zip file as first argument and files to add as rest of the arguments.'''
import sys
import zipfile
directory = sys.argv[1]
z = zipfile.zipfile(directory,'w')
length = len(sys.argv)
for i in range(2,length):
z.write(s... |
09c3839dbbe5c8cfc50eff2e5bd07fa5851695c0 | Ardra/Python-Practice-Solutions | /chapter6/pbm1.py | 203 | 4.21875 | 4 | '''Problem 1: Implement a function product to multiply 2 numbers recursively using + and - operators only.'''
def mul(x,y):
if y==0:
return 0
elif y>0:
return x+mul(x,y-1)
|
c19f67d6f4a5d2448fb4af73f1e3f12d3786bd1c | Ardra/Python-Practice-Solutions | /chapter3/pbm2.py | 742 | 4.21875 | 4 | '''Problem 2: Write a program extcount.py to count number of files for each extension in the given directory. The program should take a directory name as argument and print count and extension for each available file extension.'''
def listfiles(dir_name):
import os
list = os.listdir(dir_name)
return list
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.