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 |
|---|---|---|---|---|---|---|
e047b0eeda1e934eebcef822d70a9403f30f7eec | ngchrbn/DS-Roadmap | /DS Code/1. Programming/Python/Projects/banking_system.py | 1,217 | 4.28125 | 4 | """
Banking System using OOP:
==> Holds details about a user
==> Has a function to show user details
==> Child class : Bank
==> Stores details about the account balance
==> Stores details about the amount
==> Allows for deposits, withdrawals, and view balance
"""
class User:
def __init__(self, name, age, gender... |
8ca8ab2ea56e7b67c3780a27e7fb8f05f6968dfe | shubhu-88/Python_Webscrapping | /project.py | 6,355 | 3.59375 | 4 | import requests
import os
import csv
from bs4 import BeautifulSoup
def selectregion(college):
data={'Amravati':'1','Aurangabad':'2','Mumbai':'3','Nagpur':'4','Nashik':'5','Pune':'6'}
url='http://www.dtemaharashtra.gov.in/frmInstituteList.aspx?RegionID='+data[college]+'&RegionName='+college
head... |
8196eaf12826e03e463f4d737eae63534b6f6765 | jamtot/CodingBatPython | /Warmup-2/last2.py | 752 | 3.859375 | 4 | # Given a string, return the count of
# the number of times that a substring
# length 2 appears in the string and
# also as the last 2 chars of the
# string, so "hixxxhi" yields 1 (we
# won't count the end substring).
from test import Tester
def last2(str):
count = 0
substr = str[-2:]
for i in range(len(... |
52d6b023a3d76cf6d512833f3cb9aa86617b1488 | jamtot/CodingBatPython | /Logic-1/near_ten.py | 822 | 3.984375 | 4 | # Given a non-negative number "num",
# return True if num is within 2 of
# a multiple of 10. Note: (a % b)
# is the remainder of dividing a by
# b, so (7 % 5) is 2.
def near_ten(num):
return (num % 10) not in range (3,8)
def tester(actual, expected):
if actual == expected:
print "OK."
else:
... |
866e912cc80c6cc295a682987f1f90fae27e73b9 | jamtot/CodingBatPython | /List-1/sum2.py | 553 | 3.90625 | 4 | """
Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0.
"""
from test import Tester
def sum2(nums):
length = len(nums)
if length < 1: return 0
elif length < 2: return num... |
9d299caef0eb2d51dc614c15c249dd4f95d5ecd4 | jamtot/CodingBatPython | /Warmup-2/string_splosion.py | 686 | 3.703125 | 4 | # Given a non-empty string like "Code" return a string like "CCoCodCode".
from test import Tester
def string_splosion(str):
result = ''
for i in range(len(str)):
result += str[:i+1]
return result
Tester(string_splosion('Code'), 'CCoCodCode')
Tester(string_splosion('abc'), 'aababc')
Tester(s... |
68f53dee1396a164b23b3d64e501a198d8d8db21 | jamtot/CodingBatPython | /List-2/centered_average.py | 1,685 | 4.09375 | 4 | """
Return the "centered" average of an array of ints, which we'll say is
the mean average of the values, except ignoring the largest and smallest
values in the array. If there are multiple copies of the smallest
value, ignore just one copy, and likewise for the largest value. Use int
division to produce the final a... |
6b34c72ea2462903129e6417c0476db28172ac8b | jamtot/CodingBatPython | /Warmup-2/string_match.py | 921 | 4.03125 | 4 | # Given 2 strings, a and b, return
# the number of the positions where
# they contain the same length 2
# substring. So "xxcaazz" and
# "xxbaaz" yields 3, since the
# "xx", "aa", and "az" substrings
# appear in the same place in both
# strings.
from test import Tester
def string_match(a, b):
count = 0
#previ... |
a3e02d997bcd5119b866de7f2e557fa7320952cb | osirisbash/Wiener-Attack | /Wiener.py | 2,597 | 3.890625 | 4 | import ContinueFractions
import Arithmetic
def Wiener(N : int, e : int) -> int :
"""
Wiener Attack
return the private key if it's vulnerable
if not, return 0
"""
#1 - initialize the list of partial quotients
quot = ContinueFractions.cont_frac(e,N)
print(quot)
... |
b86d4e8e6754a5de9d3c8dbc7f99b74f2f73924e | RaadUH/RBARNETTCIS2348 | /7_26.py | 1,506 | 3.640625 | 4 | def exact_change(user_total):
if(user_total==0):
print('no change')
else:
num_dollars = num_quarters = num_dimes = num_nickels = num_pennies = 0
if(user_total//100!=0):
a = user_total//100
user_total -= a*100
num_dollars += a
if(nu... |
f970c225e3e0ac68970cf9d27900b7637bc8e76c | RaadUH/RBARNETTCIS2348 | /1_20.py | 427 | 3.90625 | 4 | # Raad Barnett 1231583
user_num = int(input('Enter integer:\n'))
# Type your code here
print("You entered:",user_num)
print("{0} squared is {1}".format(user_num,user_num**2))
print("And {0} cubed is {1} !!".format(user_num,user_num**3))
user_num2 = int(input("Enter another integer:\n"))
print("{0} + {1} is {2}".format... |
99b2328f91fc4677b052733546c480604cbcf4c2 | RaadUH/RBARNETTCIS2348 | /homework_1.py | 752 | 4.125 | 4 | #Raad Barnett 1231583
current_date = input("Enter the current date in (mm/dd/yyyy)")
date_of_birth = input("Enter the date of birth in (mm/dd/yyyy)")
cur_month = int(current_date.split("/")[0])
cur_day = int(current_date.split("/")[1])
cur_year = int(current_date.split("/")[2])
birth_month = int(date_of_birth.split("... |
61404a321613adf0583661fd1aba503472e9088a | phvargas/TwitterClassifier | /SeparateAccounts.py | 1,651 | 3.609375 | 4 | import re
import requests
from twitter_apps.Keys import get_password
from requests.auth import HTTPBasicAuth
"""
This Python program
1. From a list of given Twitter accounts finds which are accounts are deleted, protected, or suspended
"""
__author__ = 'Plinio H. Vargas'
__date__ = 'Fri, Jan 31, 2018 at 15:41:23'
_... |
8804bf269294558375aa9c391e6941c0c4d422b7 | AlexanderStarr/iTunesExportFormatter | /formatExport.py | 923 | 3.5 | 4 | # iTunes Export Formatter
# Keeps only the columns of the iTunes export that you want to keep
import csv
def pickColumns(column_names):
for i in range(len(column_names)):
print str(i) + "\t| " + column_names[i]
print "\nPlease enter the numbers of the columns you want to keep, separated by spaces."
... |
7676b955fcaae0634f9a4c8f228d8921a8091b7a | nocoli/DailyProgrammer | /Easy - 296.py | 845 | 3.59375 | 4 | print(type(3+7))
print(2-1)
print("this is a chunk of text")
a = 20
c = a * 2
if (c<50):
print(c)
print("c is less than 50")
else:
print(c)
print("c is greater than or = to 50")
print('hello')
### easy DPC
a = ["first", "second", "third", "fourth", "fith", "sixth", "seventh",
"eighth", "ninth"... |
fdca7cd08fd6dcea8473e58c736994b4d808ebe5 | davidevanks/Python | /contactos.py | 3,875 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import csv
class Contact:
def __init__(self,name,phone,email):
self.name=name
self.phone=phone
self.email=email
class ContactBook:
def _save(self):
with open('contacts.csv','w') as f:
writer = csv.writer(f)
... |
b9bc7f3ad7bfe8acdaad5128b3c891121236d12b | aadilkhhan/Variables-and-Datatypes | /04_inputfunction.py | 97 | 3.828125 | 4 | a = input("Enter your name : ")
a = int(a) #Convert a to an Integer(if possible)
print(type(a)) |
87b37fd4c3aec1a36238476db062404cecb5a8a9 | rmboot/python-algorithm | /Search/sequential_search.py | 266 | 3.875 | 4 | # 最基础的遍历无序列表的查找算法
# 时间复杂度O(n)
def sequential_search(li,key):
length = len(li)
for i in range(length):
if li[i] == key:
return i
return None
li=[8,7,6,5,4,3,2,1,0]
print(sequential_search(li,8))
|
8949145f8a97a4e223b17863701bc6e94d85bc49 | Muchdor/Primbon | /Primbon.py | 1,569 | 3.625 | 4 | import random
a = 100
b = 200
print("==֍==SELAMAT DATANG DI ABAL-ABAL METER==֍==")
c = input("1. Lanjut \n2. Keluar \n")
if c == '1':
print("Mantap")
print("=================")
loop = True
while loop:
cowok = input("Masukkan nama cowok : ")
while a <= 0 or a >= 32:
a = i... |
a894a4f38357a5e18a9b9d50a8b7d4809d31f806 | ShubbhRMewada/30DayOfPython | /Day-28/Day-28_Yukta.py | 441 | 4.09375 | 4 | m = int(input("Enter number of rows: "))
n = int(input("Enter number of columns: "))
matrix = []
print("Enter the elements row-wise-")
b = False
for i in range (0, m):
a = []
for j in range (0, n):
a.append(int(input()))
matrix.append(a)
target = int(input("Enter element to be searched: "))
for i... |
24ec8edd13c7bcf926e5729c243d7c02767727e5 | ShubbhRMewada/30DayOfPython | /Day-27/Day27_Shahazada(ST).py | 830 | 4.0625 | 4 | def checkBalance(string):
stack=[]
openpbb=['(','{','[']
for pbb in string:
if pbb in openpbb:
stack.append(pbb)
else:
if not stack:
return False
currPbb=stack.pop()
if currPbb == '(' and pbb !... |
c492c944fe2e4462c2ab454bd16b9e6117817aa1 | ShubbhRMewada/30DayOfPython | /Day-29/Day_29_Freya.py | 519 | 3.921875 | 4 | # common prefix of given array of words.
a=[]
def longestCommonPrefix(a):
size = len(a)
if (size == 0):
return ""
if (size == 1):
return a[0]
a.sort()
end = min(len(a[0]), len(a[size - 1]))
i = 0
while (i < end and a[0][i] == a[size - 1][i]):
i += 1
pre = a[0]... |
7bf819a91fc2dd814434a44b001cabeedb6dc1a8 | armandouv/practicas-eda2 | /Práctica 4/binarySearch.py | 452 | 3.84375 | 4 | def binarySearch(arr, toSearch):
return binarySearchAux(arr, 0, len(arr), toSearch)
def binarySearchAux(arr, start, end, toSearch):
if start > end:
return -1
halfIndex = (start + end) // 2
if arr[halfIndex] == toSearch:
return halfIndex
elif arr[halfIndex] > toSearch:
retu... |
b8f1334144bc46120d7f78597cce925dfb0a1ccf | armandouv/practicas-eda2 | /Práctica 8/BinaryTree.py | 8,150 | 3.890625 | 4 | from queue import Queue
from typing import Optional
from Node import TreeNode
class BinaryTree:
def __init__(self):
self.root: Optional[TreeNode] = None
def getRoot(self):
return self.root
def search(self, key: int):
return self.__searchAux(self.root, key)
def __searchAux(s... |
cb217a8a547a07eb1c02e065e9a0db8416ffd117 | shaniajain/hello-world | /ShaniaJainLab3.py | 2,792 | 4.15625 | 4 | ###############################################################################
# CS 21A Python Programming: Lab #3
# Name: Shania Jain
# Description: Password Verification Program
# Filename: ShaniaJainLab3.py
# Date: 07/25/17
###############################################################################
def main()... |
0de259898dda42e95a48f48b67851a828218a638 | barpasc/python_tuto_400_oop | /main_oop.py | 6,872 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk #GUI package
from tkinter import messagebox as msg
from classdb_oop import Database
# Instanciate databse object
db = Database('courses.db')
class Application(tk.Frame):
"""docstring for ."""
def __init__(self, parent):
super(Applic... |
0f504d31e78ec4dd3ed8bd52d3fe690a9475fbc0 | fg885436fg/python | /main/1/ifelse.py | 344 | 4.25 | 4 | height = float(input('please enter your height: '));
weight = float(input('please enter your weight: '));
bmi = weight / (height * height);
if bmi < 18.5:
print("过轻")
elif 18.5 <= bmi <= 25:
print("正常")
elif 25 <= bmi <= 28:
print("过重")
elif 28 <= bmi <= 32:
print("肥胖")
elif bmi > 32:
print("严重肥胖") |
dc0a9318c8e98718d4cb5b51e3da47c1f864b8eb | Abrahams11/practica-11 | /ejercicio2.py | 522 | 3.5625 | 4 | # Algoritmo greedy
def cambio(cantidad, monedas):
resulatdo = []
while cantidad > 0:
if cantidad >= monedas[0]:
num = cantidad//monedas[0]
cantidad = cantidad - (num*monedas[0])
resulatdo.append([monedas[0], num])
monedas = monedas[1:]
return resu... |
588d2e95a4d0c6e62aa37141fad665441bba798a | kimha1030/holbertonschool-web_back_end | /0x00-python_variable_annotations/3-to_str.py | 381 | 4.09375 | 4 | #!/usr/bin/env python3
"""Type-annotated function to_str"""
def to_str(n: float) -> str:
"""[Function that takes a float n as argument and returns
the string representation of the float]
Args:
n (float): [number used in operation]
Returns:
float: [it's the string ... |
76fd605b7f6c282a9b3b7fa3744883c71e4b76fb | JokerTongTong/Numpy_learn | /2.2获取单个数组值-数组切片.py | 239 | 3.921875 | 4 | from numpy import *
a = array([[1,2,3],[4,5,6],[7,8,9]])
print(a)
print("a[0,1]={} , a[2,1]={}".format(a[0,1],a[2,1]))
# 切片
print(a[0:2,1:2])
"""
a[0:2,1:2]
第一部分为行切片|第二部分为列切片|中间用逗号隔开
""" |
a9f7be24f85cda3510be72c60ca0268ab2dd3a25 | choococo/MoMLearning | /2.opencvLearning/stage04/8. bound_detect.py | 1,301 | 3.734375 | 4 | import cv2
import numpy
"边界检测: 边界矩形、最小(面积)矩形、最小外接圆以及椭圆拟合、直线拟合"
import cv2
import numpy as np
# img = cv2.imread('../images/23.jpg')
img = cv2.imread('../images/1.jpg')
imggray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# ret, thresh = cv2.threshold(imggray, 127, 255, 0)
ret, thresh = cv2.threshold(imggray, 0, 255, cv2.T... |
5300e9c2f8742a7565ce7b5f69d918b99d247d6a | choococo/MoMLearning | /8.others/01.pandas2use/test01.py | 1,232 | 3.65625 | 4 | import pandas as pd
import numpy as np
'pandas 是numpy的一个升级,对数据处理的更加的高效,比numpy更强大更高效'
'类似于一维的数组'
s = pd.Series([1, 2, 3, 4, np.nan, 6, 8]) # np.nan 非数字
print(s)
'DataFrame 数据结构'
dates = pd.date_range('20200101', periods=6) # 生成 随机的日期, periods=6个
print(dates)
'生成数据帧 二维... |
d58c06f7ef0734849ce119a9b6defa849976f216 | davizucon/ChatterBot | /tests/test_comparisons.py | 2,487 | 3.5 | 4 | """
Test ChatterBot's statement comparison algorithms.
"""
from unittest import TestCase, SkipTest
from chatterbot.conversation import Statement
from chatterbot import comparisons
class LevenshteinDistanceTestCase(TestCase):
def test_levenshtein_distance_statement_false(self):
"""
Falsy values s... |
439c7a5693bd9fde7ce49d45bb83b0c581911cb6 | Mark-Guan/Anagram-Generator | /anagram_generator.py | 4,234 | 4.15625 | 4 | """
This program represents is an anagram generator. A user is asked for an input file
and then the program prints all the possible anagrams containing a number of words
<= the specified max.
Mark Guan
2/17/17
"""
from letter_inventory import LetterInventory
import os.path
"""
Class AnagramSolver allows one to gener... |
5985d37813b38286068a78c14bc788a9540d9802 | anishvarsha/LeetCodeQuestions | /src/group-anagrams.py | 237 | 3.53125 | 4 | a = list(raw_input().split(" "))
print a
b = list()
count = 0
for i in range(len(a)):
k = sorted(list(a[i]))
if k not in b:
b.append(k)
n = len(b)
x = [[] for i in range(n)]
for i in range(len(a)):
if sorted(list(a[i])) in b: |
11d37a0c61c139565a8ea8da3894e404fd55c21a | anishvarsha/LeetCodeQuestions | /src/fizz-buzz.py | 219 | 4 | 4 | n = int(raw_input())
arr = list()
for i in range(1,n+1):
if i%3 == 0 and i%5 ==0:
arr.append("FizzBuzz")
elif i%3 == 0:
arr.append("Fizz")
elif i%5 == 0:
arr.append("Buzz")
else:
arr.append(str(i))
print arr |
1681923bc649db94bea11d519fc45490e502eb22 | JackShang94/BasicStudy | /DeepDiveIntoPython/Day02/ChecksumLetter.py | 653 | 3.65625 | 4 | plate = input("What is the number plate:")
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
last_char = 'AZYXUTSRPMLKJHGEDCB'
length = len(plate)
plateLetter = []
if plate[2].isalpha():
plateLetter.append(plate[1:])
elif plate[1].isalpha():
if length == 5:
plateLetter.append(plate)
firstLetter = (letters.find(p... |
7c34470fae12f974b2cc8bba75a32cf28a2f8f02 | JackShang94/BasicStudy | /DeepDiveIntoPython/Day04/ForLoop.py | 516 | 3.90625 | 4 | range(9) # 0~8
range(2,9) # 2~8
range(2,10,2) # 2,4,6,8
range(-2,-10,-2) # -2,-4,-6,-8
# Activity 1
measurement = [20.1]
total = 0
## way1
for item in measurement:
total = total + item
## way 2
for i in range(0,len(measurement)):
total += measurement[i]
average = total/len(measurement)
# Activity 2
for item ... |
15312026ea5140058f5d609559994b23a4bfaaaa | JackShang94/BasicStudy | /DeepDiveIntoPython/Day02/Strings.py | 1,578 | 4.34375 | 4 | # string formatting
## method 1
text = 'Hello'
text2 = 'World'
print('%s' % text)
print('...%s...%s' % (text,text2))
## method 2
text = 'Hello'
print(f'...{text}...')
## method 3
text = 'Hello'
print('...{:s}...'.format(text))
print('{}'.format(text))
print('{},{}'.format('one','two','three')) ## different paramet... |
1044f8b5e39c020d22e5001b604560f421c86001 | JackShang94/BasicStudy | /DeepDiveIntoPython/Day03/Exercise1.py | 854 | 3.8125 | 4 | # 1)
def calculate_average_marks(markList):
firstCourse = markList[1].split(';')
secondCourse = markList[2].split(';')
firstMark = float(firstCourse[0])*(float(firstCourse[1])/100)
secondMark = float(secondCourse[0])*(float(secondCourse[1])/100)
finalMark = firstMark + secondMark
return finalMar... |
f859d377fd94716eb7a41985d2ef8b62cda75631 | thesrikarpaida/ProjectEuler | /p2.py | 305 | 4.0625 | 4 | def fib(n):
if n == 1 or n == 0:
return n
return fib(n-1) + fib(n-2)
n = int(input("Enter an upper limit for the Fibonacci terms:"))
s = 0
i = 1
x = fib(i)
while x <= n:
if x%2 == 0:
s = s + x
i = i + 1
x = fib(i)
print("Sum of Even Fibonacci terms upto ",n," is ",s)
|
e8a6a4cc7054bf49070425bd50978a3b0643e56c | whgaara/TensorFlowTrain | /CNN&LSTM/lesson2-2.py | 1,091 | 3.609375 | 4 | import tensorflow as tf
x = tf.Variable([1, 2])
a = tf.constant([3, 3])
# 定义一个减法op
sub = tf.subtract(x, a)
# 定义一个加法op
add = tf.add(x, sub)
# tf中只要出现变量,就要定义全局变量初始化op
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sub)
print(add)
print(sess.run(sub))
prin... |
7a20db6d0aa73255347ceaa0295ba15336aac9a4 | d2fzero/hw4 | /exercises 7+8.py | 168 | 3.734375 | 4 | #7
def sum_to(n):
total=0
for i in range(n+1):
total += i
print(total)
return
#8
def area_of_circle(r):
area = 3.14*r*r
|
b527e0dc149e1c769f394ceaa9f9ae332c0fecfa | phaustin/ocgy-dataviewer | /station.py | 473 | 3.53125 | 4 | class Station:
def __init__(self, type, lat, lon, name, colour):
self.type = type
self.lat = lat
self.lon = lon
self.name = name
self.colour = colour
def in_list(lat, lon, list):
for s in list:
if (s.lat == lat) & (s.lon == lon):
return True
retu... |
f0e83e8c534cf74d7445fa0e2d089d3a942a47bf | fouad18-meet/meet201617YL1cs-mod4 | /square.py | 1,031 | 4.09375 | 4 |
from rectangle import Rectangle
class Square(Rectangle):
def __init__(self, length):
super().__init__(length , length)
def set_length(self,new_length):
"""
Change the length of the rectangle.
:param new_length: length (horizontal dimension) of rectangle. Must be >= 0.... |
98a67c1f9dc705376c7589889375c89a3408b088 | Tlemos-Daitan/Python-Beginning | /cadastro.py | 188 | 3.6875 | 4 | nomes = []
nome = input()
nomes.append(nome)
nomes
def cadastrar(nomes):
print ('Digite o nome:')
nome = input()
nomes.append(nome)
print (nomes)
nomes = []
cadastrar(nomes) |
c5f84fbbcd7f88cb28cee4640cf5ed67bef281a0 | psprakashkkdi/VideoSearch | /src/timeConvert.py | 694 | 3.53125 | 4 | """
timeConvert.py
Created by Mitchell Katz
Converts a timestamp of the form H:M:S to the total number of seconds and
vice versa thanks to stackoverflow post
http://stackoverflow.com/questions/10663720/converting-a-time-string-to-seconds-in-python
and user Burhan Kahlid for this code
"""
import datetime
import time
d... |
065a9caecae22ad5490d3fd8599834dcc9f6295e | jackson541/algoritmos | /ordenacao.py | 3,367 | 3.875 | 4 | import time
import random
def selecao_direta(lista):
"""
Percorre uma lista verificando para cada índice qual o menor elemento da lista a partir dele
para poder tomar a posição desse índice.
Ex:
[1, 5, 9, 0, 8, 10, 6] -> inicio
[0, 5, 9, 1, 8, 10, 6] -> 0 menor
[0, 1, 9, 5, 8, 10, 6] -... |
06a57df0cd2b82ea2643ec5517e133009009d435 | ProgrammerOfLife/Library-Project | /lib.py | 1,872 | 4.0625 | 4 | class NewUser(object):
def __init__(self, Name):
Number_of_Users = 0
Number_of_Users =+1
self.Name = Name
self.Serial_Number = Number_of_Users
self.Library_Id = "ZionLib" + str(Number_of_Users)
def Details(self):
return "Welcome " + self.Name + " This is ... |
8559753660c08c97fde2209f55441799435c8923 | singhaldivya1/Tic-Tac-Toe_with_AI | /Test_suite/test_board.py | 2,535 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 1 01:12:46 2018
@author: singh
"""
import io
import sys
import unittest
import unittest.mock
from Board import Board
class TestTicTacToeBoard(unittest.TestCase):
def test_BoardClass(self):
game_board = Board()
self.assertIsInstance(game_board,Boa... |
6391ee84a2e3b396c42894f4e82803d80d9c0770 | ingelres/sixtakes | /tools/__init__.py | 280 | 3.5 | 4 | import sys
def progressbar(done, total, length):
""" Draw a progress bar showing the current progress (done / total) over length+2 characters """
done = done * length / total
sys.stdout.write('\r[' + '=' * done + ' ' * (length - done) + ']')
sys.stdout.flush()
|
ce0198d5caa2eb033fb1b4c40198232063d0de38 | asiftandel96/Python-Implementation | /LambdaFunctions.py | 2,580 | 4.40625 | 4 | """ Python Lambda Functions/Anonymous Functions.Anonymous function are those function which are without name."""
# Defining a Normal functions.
def addition_num(a, b):
c = a * b
print(c)
addition_num(2, 42)
# Using A Lambda
# Syntax lambda arguments:expression
# Note-(Lambda Function can take si... |
7ceec30bba544788cd5915d1c102a8438a3a8a47 | aaguiarneto/CusoDev_Infinity | /TestePrecoCarro.py | 209 | 3.625 | 4 | precofabrica = float(input("Informe o preço de Fabrica: "))
precovenda = (precofabrica + (precofabrica * 28/100) + (precofabrica * 45/100))
print("O preço para o consumidor é: {:.2f}".format(precovenda))
|
1a8791e310d231db783e4b50b9fbad5244e69f93 | DarcyZuzetLonaCruz/LyA1 | /correo1.py | 275 | 3.578125 | 4 | def correo():
import email
correo='nombre@dominio.ext'
if email.match('^[(a-z)]+@[(a-z]',correo.lower()):
print "Correo correcto"
else:
print "Correo incorrecto"
rom time import time
start =time()
correo1()
end=time()-start
print(end) |
26d9cb4a7842a2a37016da4af82edf674f5b2997 | leuthier/UFRPE | /victor_leuthier_E4.py | 1,248 | 3.71875 | 4 | def bolha(lista):
troca = True
while troca:
troca = False
for x in range(len(lista)-1):
if lista[x] > lista[x+1]:
chave = lista[x]
lista[x] = lista[x+1]
lista[x+1] = chave
troca = True
return lista
import ... |
c639a2febab5d70fa2d4665667c98071efcb7309 | mubaraqwahab/algorithms | /os/page-replacement/fifo.py | 1,057 | 4 | 4 | def FIFO(references: list, page_frames: list):
"""Perform page replacement using the first-in first-out algorithm.
Inputs:
* references - a list (queue) of page references
* page_frames - a list representing the page frames.
Output: the number of page faults.
"""
# Create a copy of the or... |
060c84427e307b104548c5f5a4032e2f605ced20 | mubaraqwahab/algorithms | /misc/commonelems.py | 870 | 3.859375 | 4 | def common_elements(p, q):
"""Return a list of all elements common to sorted lists p and q."""
i = j = 0
elems = []
while i < len(p) and j < len(q):
if p[i] < q[j]: i += 1
elif p[i] > q[j]: j += 1
else:
elems.append(q[j])
j += 1
i += 1
return elems
# Test drive
if __name__ =... |
dbb65046ac5bdd32016b144e2c254504a470cff8 | eulermoraes/PythonStudies | /MilestoneProject2/app.py | 798 | 3.8125 | 4 | from utils import database
USER_MENU = """
Enter:
- [1] Add new book
- [2] List books
- [3] Mark book as read
- [4] Delete book
- [q] Quit
What's your choice:
"""
def menu():
user_input = ""
while user_input != 'q':
user_input = input(USER_MENU)
if user_input == '1':
add()
... |
ec9f5ace4c8a0910be937836577710585ecb87c8 | dave5801/CodingChallenges | /leetcode/arrayIntersect.py | 941 | 3.78125 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
inters = []
nums1 = list(set(nums1))
nums2 = list(set(nums2))
seen = {}
longer, shorter = [],... |
0e0c852d2ef9c236b308121527699f2a0ffee248 | dave5801/CodingChallenges | /leetcode/cardFlip.py | 620 | 3.5625 | 4 | import sys
class Solution:
def flipgame(self, fronts, backs):
"""
:type fronts: List[int]
:type backs: List[int]
:rtype: int
"""
sameFrontAndBack = set()
for card in range(len(fronts)):
if fronts[card] == backs[card]:
sameFrontAnd... |
f3f380591f403b1b9d50d27c0eafac6423786f79 | dave5801/CodingChallenges | /leetcode/longestSubstringNoRepeats.py | 682 | 3.53125 | 4 | class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
if length < 1:
return length
longest = 1
seenSubstrings = [s[0]]
for i in range(len(s)):
current = s[i]
... |
54df688eab059286f2b2da7765da96ea804bac0a | Shivvrat/Collaborative-Filtering | /import_data.py | 1,090 | 3.796875 | 4 | import os
def import_train_data(data_set_name):
"""
This function is used to import the train data
:param data_set_name: Please provide the name of dataset in string format
:return: the string containing all train dataset
"""
path = os.path.join(os.getcwd(), data_set_name)
path = o... |
a508113c8a9e02eeb9e120df12a92e3d03514388 | hritikjain1707/HacktoberFest2021 | /Python/Tasks/binary_numbers.py | 1,007 | 3.96875 | 4 | """
Write a program which accepts a sequence of comma separated 4 digit binary numbers
as its input and then check whether they are divisible by 5 or not.
The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example:
0100,0011,1010,1001
Then the output should be:
1010
"""
def binary_to... |
994b1de7447a33bbc8c8f7432633cafc9f9bf94e | iopedare/ML_Methods | /2. Numpy.py | 5,085 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
# In[3]:
my_list1 = [1, 2, 3, 4]
my_array1 = np.array(my_list1)
# In[4]:
my_array1
# In[5]:
my_list2 = [5,6,7,8]
# In[6]:
my_array = np.array([my_list1, my_list2])
my_array
# In[7]:
# Usage of shape function
my_array.shape
# 2 rows... |
203d73454df55ff66c94552a8cadaf7b27a86d36 | iopedare/ML_Methods | /DecisionTree-Assignment.py | 985 | 3.5 | 4 | # Decision Tree
# Import libraries
import numpy as np
import pandas as pd
# Import dataset
dataset = pd.read_csv('Iris.csv')
#mapping the dependent variable
dataset['Species'] = dataset['Species'].map({'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2})
#Selecting the independent and dependent variables
X ... |
c67c5f150f64b12ecee8ee51967bf52a420edd40 | DyeffersonAz/calculo-de-paginas | /livros.py | 747 | 4 | 4 | from math import ceil
#input do usuario
paginas = int(input("Quantas páginas/capítulos tem o livro? "))
dias = int(input("Em quantos dias quer lê-lo? "))
paginasDiarias = ceil(paginas/dias)
#apos calcular o quanto de páginas o usuario deverá ler por dia o programa arrendonda pra cima e mostra o resultado
prin... |
e05b2b62f3899b581dba094612e4ccbc57f79532 | 18F/snap-api-prototype | /snap_financial_factors/program_data_api/fetch_min_allotments.py | 1,374 | 3.6875 | 4 | class FetchMinAllotments:
'''
Uses a state or territory and a household size to fetch the min allotment,
returning None if the household is not eligible for a minimum allotment.
In 2020, only one- and two- person households are eligible for a minimum
allotment amount.
'''
def __init__(self... |
ec7abe4969c5bbf1e5dbde4b05541d361aa169ff | KarthikMgk/Puzzles--Problems | /PuzzlesfromCodingBat.com/in1to10 | 198 | 3.578125 | 4 | def in1to10(n, outside_mode):
while outside_mode is True:
if (n<=1) or (n>=10):
return True
return False
else:
if n in range(1,11):
return True
return False
|
3e06e6cf723442d979b32d985df927e975715371 | rp927/05-Python-Programming | /question_7.py | 218 | 4 | 4 | '''MPG'''
'''User input'''
user_miles = float(input("Enter the number of miles driven:"))
user_gallons = float(input("Enter the number gallons used:"))
'''Output'''
print(F"Your MPG is {user_miles/user_gallons:.2f}") |
2c0cc54ba6987d8e5b56d18da63b744524b7c3f9 | rp927/05-Python-Programming | /Class/Car_Class.py | 664 | 3.640625 | 4 | class Car:
def __init__(self,year,make,speed=0):
self.__year = year
self.__make = make
self.__speed = speed
def set_year(self,year):
self.__year = year
def set_make(self,make):
self.__make = make
def set_speed(self,speed):
self.__speed = speed
def ... |
b2b8e0d4fdf58e5da673a45d4ce894de37e3aec0 | rp927/05-Python-Programming | /question_9.py | 221 | 4.34375 | 4 | '''Celsius to Fahrenheit'''
'''User input'''
celsius = int(input("Enter a temperature to convert to fahrenheit:"))
'''Output'''
print(F"{celsius} degrees celsius is equal to {(9/5)*celsius + 32:.2f} degrees fahrenheit") |
ff5bf24fcc71af90583931b78d88143dc95e2fc9 | kalyangoud77/practice | /commn2.py | 138 | 3.734375 | 4 | a = [1,2,3]
b = [1,4,3,4]
for i in range(len(a)):
for j in range(len(b)):
if (a[i]==b[j]):
print(a[i],b[j]) |
5e01f9f2fb80d62b5d8a0874eabe8fbf3eec03bb | kalyangoud77/practice | /stdnt_avg.py | 226 | 3.609375 | 4 | class Student():
def __init__(self,m1,m2,m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
def avg(self):
return((self.m1+self.m2+self.m3)/3)
s1 = Student(40,60,95)
print(s1.avg())
|
6d3a97e11af7376cc5833ccb14e45f53cafef17a | kalyangoud77/practice | /tmatrix3.py | 670 | 3.859375 | 4 | l=[[0,1,2,3],[1,2,3,4],[2,3,4,5],[3,4,5,6]]
l1=[]
for i in range(len(l)-2):
for j in range(len(l)-2):
value = 0
for k in range(i,i+3):
for m in range(j,j+3):
if i == k:
print(l[k][m],end=" ")
value +=l[k][m]
... |
4c0092547567d5212b615d81e65236dcedde6bd8 | kalyangoud77/practice | /common_num_in_two_lists.py | 210 | 3.859375 | 4 | a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 7]
def common_member(a, b):
x = set(a)
y = set(b)
if (x & y):
print(x & y)
else:
print("No common elements")
common_member(a, b)
|
49a3eec58f65f86d1778ba4cba9b56a3143c504b | jcpenuela/Pruebas | /Pruebas/passthrough.py | 1,470 | 3.78125 | 4 | '''
Cómo aplicamos un passthrough a un objeto para aplicar una búsqueda
'''
import clases.persona
def carga_datos():
d = dict()
d[1] = clases.persona.Persona('Uno','Sevilla',18)
d[2] = clases.persona.Persona('H27','Huelva',27)
d[3] = clases.persona.Persona('M15','Madrid',15)
d[4] = clases.persona.... |
65af4722539fe0d738209facc4540c512f085502 | DerekMarshall855/Assignment-1 | /node.py | 2,010 | 4.0625 | 4 | """
Class Node
Each Node represents a point on a graph, tree or list.
---------------------------------
self.state - state of puzzle node (3x3)
self.parent - points to the current nodes parent node
self.g - distance to starting node, used for heuristics
self.h - distance to goal node, used for heuristics
self.f - total... |
e87893f965a979c0ff40c6d4b6a646ec7e77528d | mrmoonlv/Advent-of-Code | /2020/day2/part2.py | 550 | 3.640625 | 4 | #!/usr/bin/env python3
import sys
f = open("data.txt", "r")
lines = f.read().splitlines()
valid_passwords = 0
for line in lines:
parts = line.split(" ")
ranges = parts[0].split('-')
first_index = int(ranges[0])
second_index = int(ranges[1])
need = parts[1].replace(':', '')
password = parts[... |
53338cd792cdd50346204c85f29dfb3336cf1880 | mrmoonlv/Advent-of-Code | /2020/day6/part1.py | 315 | 3.5 | 4 | #!/usr/bin/env python3
count: int = 0
for group in open("data.txt", "r").read().split("\n\n"):
questions = list(set(group.replace('\n', ' ').replace(' ', '')))
for question in questions:
if question in 'abcdefghijklmnopqrstuvwxyz':
count += +1
print("The sum of those counts:", count)
|
acc93d7c6a15a315f8404d34b7da05e3641177a5 | hameji/create_sns_account | /model/data/data_manager.py | 464 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
if os.name == "nt": #Windows
NEW_LINE_CODE = "\r\n"
elif os.name == "posix": #Mac
NEW_LINE_CODE = "\n"
class DataManager(object):
def str_to_list(self, input: str):
result = []
if "," in input:
result = input.split(",")
... |
ac3420ed1d71fbab98b8155a84e77c68262290af | amarinas/algo | /chapter_1_fundamentals/final_countdown.py | 396 | 3.796875 | 4 | # given 4 params
# print the multiples of param 1 starting at param 2 and extending to param 3
# if a multiple is equal to param 4 then skip
#given( 3,5,17,9) expected (6,12,15)
def final_count(param1,param2,param3,param4):
count = param3
while count > param2:
if count % param1 == 0 and count != param4... |
413f32f1367a8cbf5183add9771d598e630f9534 | amarinas/algo | /chapter_1_fundamentals/leapyear.py | 484 | 4.21875 | 4 | # write a function that determines whether a given year is a leap year
# if the year is divisible by four, its a leap year
# unless its divisible by 100
# if it is divisible by 400 than it is
def leapyear(year):
if year % 4 == 0:
print "it is a leap year"
elif year % 100 ==0:
print "not a leap... |
12e421c9a2aec754aa2746f3c20c0226df2a1a0d | amarinas/algo | /chapter_1_fundamentals/whoa.py | 203 | 3.59375 | 4 | def whoa():
#add odd intergers from -3000 to 3000 and console log sum
sum = 0
for i in range(-300000, 300000):
if i % 2 == 1:
sum = sum + i
return sum
print(whoa())
|
27d5d87b93ee017bef9a760d091b7c80d95a147e | amarinas/algo | /chapter_1_fundamentals/print_return.py | 239 | 3.703125 | 4 | #function will receive an array with two numbers
#print the first value
#return the second
def print_return(val1, val2):
print "this is print ", val1
return "this is return", val2
print_return(12, 22)
print(print_return(33,12))
|
ef06ee1de6b838599b98c1bab5883c595086f514 | amarinas/algo | /Hack_rank_algo/writefunction.py | 304 | 4.1875 | 4 | #Determine if a year is a leap yesar
def is_leap(year):
leap = False
#condition for a leap year
if year % 4 == 0 and year % 400 == 0 or year % 100 != 0:
return True
#return leap if the above condition is false
return leap
year = int(raw_input())
print is_leap(year)
|
9554a30f82c858f0aacab04102ba43a7f7057f02 | amarinas/algo | /random_algo_exercise/strings_integers.py | 208 | 4.15625 | 4 | # Read a string,S , and print its integer value; if S cannot be converted to an integer, print Bad String
import sys
S = raw_input().strip()
try:
print(int(S))
except ValueError:
print("Bad String")
|
5ca75fc6ea0ae05da9905aae7ee3cb2a7b1c8e19 | amarinas/algo | /chapter_1_fundamentals/flexible.py | 297 | 3.796875 | 4 | # based on countdown by four
# given lowNum, highNum, mult
# print mult from highNum down to lowNum using For loop
def flexible(lowNum,highNum, mult):
count = highNum
while count > 0:
if count % mult == 0:
print count
count = count - 1
print(flexible(2,9,3))
|
096abdbc6c7a049bbfbc7c8afc516bad0ec5d022 | amarinas/algo | /PlatformAlgo/reversing.py | 474 | 4.65625 | 5 | #Given an array X of multiple values (e.g. [-3,5,1,3,2,10]), write a program that reverses the values in the array. Once your program is done X should be in the reserved order. Do this without creating a temporary array. Also, do NOT use the reverse method but find a way to reverse the values in the array (HINT: swa... |
f9bd0cca25a8e163eb84c490e44fc305f3e1dc85 | amarinas/algo | /PlatformAlgo/square_value.py | 477 | 4.21875 | 4 | #Given an array x (e.g. [1,5, 10, -2]), create an algorithm (sets of instructions) that squares each value in the array. When the program is done x should have values that have been squared (e.g. [1, 25, 100, 4]). You're not to use any of the pre-built function in Javascript. You could for example square the value b... |
7f90da219ab5807749f17964bdd7b1ff78b3c1eb | amarinas/algo | /random_algo_exercise/arrays_day7.py | 302 | 4.125 | 4 | # Given an array, A, of N integers, print A's elements in reverse order as a single line of space-separated numbers.
from __future__ import print_function
import sys
n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
arr.reverse()
for num in arr:
print(num + " ", end='')
|
113abd3f4d90aa0b95d135b2b7928b6400738fa1 | amarinas/algo | /PlatformAlgo/iterate_array.py | 394 | 4.3125 | 4 | #Given an array X say [1,3,5,7,9,13], write a program that would iterate through each member of the array and print each value on the screen. Being able to loop through each member of the array is extremely important. Do this over and over (under 2 minutes) before moving on to the next algorithm challenge.
def Itera... |
3fc0a340f488963f1958cfdff8a5c67edeea64e8 | flohlen/University | /Informatik/EidI/Blatt4/aufgabe_2.py | 992 | 3.625 | 4 | # Gruppe 74
# 35408150 Reinbold, Jonas Florian
# 35395821 Hasert, Yannis
def infix(x):
if type(x) == int:
return str(x)
if type(x) == tuple and (str(x[1]) == "+" or str(x[1]) == "-" or str(x[1]) == "/" or str(x[1]) == "*"):
return ("(" + str(infix(x[0])) + str(x[1]) + str(infix(x[2])) + ")")
def prefix(x):
i... |
a3e13d1be692a749bdf8d7ef3507787691cdfbc0 | viveks-mdu/eight_puzzle_solver | /ai_rbfs.py | 10,992 | 3.578125 | 4 | __author__ = 'vivek'
import math, random, sys, time, bisect, string, functools, collections
states_hash = {}
def print_state(state):
for i in range(3):
for j in range(3):
print(state[i][j], end=" "),
print()
def track_empty_block(state):
row_index = -1
column_index = -1
... |
294807051595aa9f2c9b65a878ed883562113954 | 0xEitan/CryptoPals | /set1/ex4-single-char-xor/utils.py | 1,160 | 3.671875 | 4 | def score_english_sentence(s):
# not the best way to score a sentencte
# repeated 'E' will score the highest...
# http://pi.math.cornell.edu/~mec/2003-2004/cryptography/subs/frequencies.html
FREQUENCY = {
'E': 12.02,
'T': 9.10,
'A': 8.12,
'O': 7.68,
'I': 7.31,
... |
155b0534ff15efff0e239d6ce2a9e8a55b16664d | murageB/alx-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,248 | 4.09375 | 4 | #!/usr/bin/python3
"""
Matrix Division module
"""
def matrix_divided(matrix, div):
"""
Divides all elements of a matrix
Args:
matrix (list): matrix to be divided
div (int/float): number to divide matrix
Raises:
TypeError: if matrix is not a list of integers/floats
... |
6b2d1f41cb92431def9cc0ecc7de86898183efb5 | murageB/alx-higher_level_programming | /0x04-python-more_data_structures/9-multiply_by_2.py | 198 | 3.84375 | 4 | #!/usr/bin/python3
def multiply_by_2(a_dictionary):
new_dict = []
for x in range(len(a_dictionary)):
new_dict.append(list(map((lambda x: x * 2), a_dictionary)))
return(new_dict)
|
5a387029c3bf5b95fbde72c6391b18c70b14ebed | murageB/alx-higher_level_programming | /0x0B-python-input_output/6-load_from_json_file.py | 223 | 3.5 | 4 | #!/usr/bin/python3
"""
Load from json file module
"""
import json
def load_from_json_file(filename):
"""
creates an python object from json file
"""
with open(filename) as f:
return json.load(f)
|
744f223605b4ae7a8238dfcb9a0e97bcd3b72bf3 | hiniwo/python_base | /string.py | 545 | 3.78125 | 4 | #coding=utf-8
var1 = 'Hello World!'
var2 = "Python Runoob"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
print "更新字符串 :- ", var1[:6] + 'Runoob!' \
+ 'wwm' + '\n' + 'jinini'
print '更新字符串: 2', var2[:1] + 'wwm'
print 'H' in var1
print 'H' not in var1
var3 = var1[3:]
print var3
# 格式化字符串
print "My... |
635622c6d57ec22c524221b9dcdf17f573ddcbfb | samarpitchauhan/Python-Basic-Programs-Conditional-Loops- | /Table of a Number.py | 129 | 4.09375 | 4 | #Program to Print Table of a Number
n1 = int(input())
for i in range(1,11):
n = n1 * i
print(n) |
7de3b8bcdde2df9d9f04720886498e4926ee3e9a | chyidl/chyidlTutorial | /root/os/DSAA/DataStructuresAndAlgorithms/python/linked_list_merge_two_sorted_implement.py | 5,141 | 4.3125 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# linked_list_merge_two_sorted_implement.py
# python
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.