blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6d5b3571292c6749e489d3de7fbfcd1fcfe6d1f0 | DejaVuMan/data_visualization | /classwork+homework/03-13-2020 Intro2/Class/5_Break_Continue.py | 777 | 4.15625 | 4 | # Break and Continue are operations typically reserved for loops.
#
# Break: Forces the loop to halt and continues to code outside of the loop.
#
# Continue: Ends current part of loop and continues to the next part.
#
# EXAMPLE:
#
# User Provides a number
# Program looks through a predetermined list of ... |
c72ec0a275c29acd7bc516e11bf3ac17e828f411 | djanshuman/Coding | /Leetcode-Blind-75/ValidParentheses.py | 431 | 3.71875 | 4 | class Solution:
def isValid(self, s: str) -> bool:
pair = {']':'[','}':'{',')':'('}
curr = []
for i in s:
if i in pair:
if (len(curr) == 0 or curr.pop() != pair[i]):
return False
else:
curr.append(i)
if len(... |
d2ee0f639dd06ebfd830e3e06579c56cdcc64921 | SandboxCoding/DSACourse | /Test Stuff/If,else,elif test.py | 627 | 3.984375 | 4 | #First usage of if and else
a = int(3)
b = int(2)
ab = a*b
if ab == 6:
print("Success")
else:
print("Failure")
#Trying some random things
month = int(input("Enter a month in numeric form from 1-12: "))
if month in list(range(1, 4)):
print("It's the first quarter of the month.")
elif month in list(range(4... |
77a4bfeea96f2cd555904cfdbddc7e5eac9c4cdb | AnaRhisT94/Machine_Learning_Projects | /Data-Preprocessing/data-preprocessing.py | 2,659 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 06:48:55 2019
@author: Ilan Aizelman
@Summary: Pre-processing techniques of data
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing dataset
dataset = pd.read_csv("Data.csv")
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].val... |
8473e8311f7e99f95690555e61860c5c38a9d9fe | madinhos/PYTHON | /lekcja7/rectangles.py | 2,279 | 3.765625 | 4 | from points import Point
class Rectangle:
def __init__(self, x1=0, y1=0, x2=0, y2=0):
# Chcemy, aby x1 <= x2, y1 <= y2.
if x1 > x2 or y1 > y2:
raise ValueError("bledne dane inicjalizacyjne")
self.pt1 = Point(x1, y1)
self.pt2 = Point(x2, y2)
def __str__(self):
return "([%s, %s], [%... |
6184493e4015a3a5bfd2b660e7f7e9e37baa0c52 | madinhos/PYTHON | /lekcja4/43.py | 202 | 4 | 4 | def factorial(n):
result = 1
if(n>0):
for i in range(1, n+1):
result *= i;
return result
else:
return 1
l = int(raw_input("Podaj lizcbe:"))
print(factorial(l))
raw_input() |
73fa2e2e80f5b54387e65974ead8b67b578b6094 | madinhos/PYTHON | /lekcja4/45.py | 690 | 3.515625 | 4 | #iteracja
def odwracanie(L, left, right):
temp = int((right - left)/2)
if(left < right):
temp2 = L[left]
for i in range(temp):
L[left+i] = L[right-i]
L[right-i] = L[left+i]
L[right] = temp2
return L
else:
return None
#rekurencja
def odwracanie2(L, left, right):
if(left < rig... |
298b1b66f6062381446758dcad28fe0c28367216 | madinhos/PYTHON | /lekcja4/47.py | 319 | 3.578125 | 4 | def flatten(sequence):
lista = list()
l = len(sequence)
for i in range(l):
if isinstance(sequence[i], (list, tuple)):
lista.extend(flatten(sequence[i]))
else:
lista.append(sequence[i])
return lista
seq = [1,(2,3),[],[4,(5,6,7)],8,[9],10]
print(seq)
print(flatten(seq))
raw_input()
|
74cfbb24cb39054e1018c745fda25e19ee1e836e | madinhos/PYTHON | /lekcja11/z5.py | 934 | 3.890625 | 4 | #Heapsort - szybki i niepochlaniajacy wiele pamieci algorytm sortowania. Nie jest stabilny.
#na podstawie algorytmu ze strony codecodex.com
# Pesymistyczna zlozonosc: O(n log n)
# Optymistyczna zlozonosc: O(n log n)
# Srednia zlozonosc: O(n log n)
import z1
def heapSort(a):
count = len(a)
start = c... |
77045753fd9a3478447e7ffb7ea92a78d37f3017 | madinhos/PYTHON | /lekcja3/8.py | 360 | 3.703125 | 4 | A = [1, 2, 3, 4, 5]
B = [4, 5, 1, 6, 9]
C = A+B
resultA = []
resultB = []
for i in C:
if i not in resultA:
resultA.append(i)
else:
resultB.append(i)
print "lista A: ", A
print "lista B: ", B
print "lista elementow wystepujacych w obu sekwencjach: ", resultB
print "lista wszystkich elementow z ... |
2c7b6832dda480fd751f02c2136ec188216181eb | sudeep0901/pandas | /5.pandas.py | 666 | 3.515625 | 4 | import pandas as pd
import numpy as np
# convert tuple in Series
# tp = tuple(1, 2, 3)
# print(tp)
h = ('AA', '2012-02-01', 100, 10.2)
s = pd.Series(h)
# print(s)
data = {
'name':['AA', 'CC', 'BB'],
'date': pd.date_range('2019', periods=3),
'shares' : [100, 30, 90],
'price': [12.3, 10.3, 32.2]
}
d... |
65c39c11eb616a737943fe0d42fc8cf543e213d8 | sudeep0901/pandas | /12.value&counts.py | 455 | 3.5625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
index = pd.Index([3, 1, 2, 3, 4, np.nan])
print(index)
# nan values not counted
print(index.value_counts())
# With normalize set to True, returns the relative frequency by dividing all values by the sum of values.
index.value_counts(normalize=T... |
09e2ba49362ca8d48b936d3c7e3834412b3ceae6 | bajaj-aditya/Useful-Python-Projects | /Guess a Number!.py | 516 | 4.0625 | 4 | import random
number = random.randint(0,20)
GuessTaken = 0
print("Hi There! I am thinking of a number! You will only get 5 chances to think of it!")
for GuessTaken in range(5):
print("Guess!")
guess = int(input())
GuessTaken = GuessTaken + 1
if guess > number:
print ("Too High")
... |
0e05623840b8f9b208c8fdef477fe7ab35a80414 | FishOfPitt116/WTSummerBoatPassScript | /searchandsort.py | 595 | 4.0625 | 4 | def search(l, val):
start = 0
end = len(l) - 1
# print(len(l))
while (end - start) > 1:
"""
print('Start:', start)
print('End:', end)
"""
mid = ((end - start) // 2) + start
"""
print('Mid:', mid)
print('//////////////////')
"""
... |
341373a3b7241d85b47679e89752898d1a46f22d | colesamson16/BramptonCompWork | /CityTemps.py | 362 | 3.5625 | 4 | cities = ["London", "Paris", "New York", "Cape Town", "Toronto", "Nairobi", "Beijing", "Tokyo", "Miami", "Los Angeles"]
temps = ["14.2", "15.3", "15.8", "17.7", "11.1", "21.0", "28.9", "29.6", "27.2", "22.4"]
#Citytemps = [cities, temps]
for i in range(0, 9):
print(cities[i], temps[i], "C")
#print(Citytemps[... |
e3afba95018236045235bb44122e2df02df5b93f | colesamson16/BramptonCompWork | /NovAssesment.py | 681 | 3.609375 | 4 | #Cole Samson 9/11/17 As/Comp/a
counter = 0
teamname = "Zeus"
playerHits = 0
totalHits = 0
averageHits = 0.0
pointsEarned =
def getdetails():
global teamname, playerHits, totalHits, counter
teamname = input("Team Name: ")
for counter in range(0,6,):
playerHits = int(input("Enter Player Hits: "))
t... |
f494fe7ee3e2a0dd4db12378b8d126d38e5fc2bb | shubhamkanade/Niyander-Python | /print_odd.py | 110 | 3.8125 | 4 |
for iCnt in range(1,18+1):
if iCnt%2!=0:
print iCnt,"number is odd"
else:
print iCnt,"number is even"
|
98ae20e867984da563ce2b17c473cedaded62554 | shubhamkanade/Niyander-Python | /Assignment 2/1.py | 449 | 3.546875 | 4 | #import Arithematic
from Arithematic import *
ino1=input("Enter a 1st number")
ino2=input("Enter a 2nd number")
#ret=Arithematic.Add(int(ino1),int(ino2))
ret=Add(int(ino1),int(ino2))
print(ret)
#ret=Arithematic.Sub(int(ino1),int(ino2))
ret=Sub(int(ino1),int(ino2))
print(ret)
#ret=Arithematic.Mult(int(ino1),int(ino2... |
50e065bb5005a3eb68dd209057fd1b8d9b6022e5 | shubhamkanade/Niyander-Python | /Assignment 2/5.py | 312 | 4 | 4 | def ChkPrime(num):
for i in range(2,int(num/2)+1,1):
if(num%i==0):
break
if(i<int(num/2)):
return False
else:
return True
def main():
num=int(input("Enter a number"))
ret=ChkPrime(num)
if(ret==True):
print("It is prime")
else:
print("It is not prime")
if(__name__=="__main__"):
main()
|
a68192e95ea98e1fd1f6afba38074c17d2d922ea | shubhamkanade/Niyander-Python | /overriding.py | 169 | 3.59375 | 4 | class base:
def mymethod(self):
print "in base class"
class derived(base):
def mymethod(self):
print "in derived class"
b=base()
b=derived()
b.mymethod()
|
0771cf294e8b8a2c31b565dac5c69ed0d53f6eb6 | shubhamkanade/Niyander-Python | /string_Tuple_DT.py | 142 | 3.90625 | 4 | tuple=('abcd',786,2.23,'john',70.2)
tinytuple=("john",123)
print tuple
print tuple[0]
print tuple[2:]
print tuple+tinytuple
tuple[0]=5.60
|
95fe61b2f013c3921ab276fbe32642ae8ec89304 | shubhamkanade/Niyander-Python | /Assignment 3/MarvellousNum.py | 274 | 3.953125 | 4 | def Chkprime(ino):
no=ino
i=2
for i in range(2,int((no/2)+1),1):
if(no%i==0):
break
#print(i)
if(i<int(no/2)):
return False
else:
return True
i=int(input("Enter number"))
ret=Chkprime(i)
if(ret==True):
print("It is prime")
else:
print("It is not prime")
|
c7248c935bf55284e6cb72b05cc7c1220ec2a385 | shubhamkanade/Niyander-Python | /decorator.py | 195 | 3.53125 | 4 | def sub(no1,no2):
return no1 - no2
def Decorator(orignalfun):
def updator(a,b):
if(a < b):
a,b = b,a
return orignalfun(a,b)
return updator
newSub = Decorator(sub)
print(newSub(6,7))
|
3a106ff968c72b65cd89f70b0555a3cc3250f2cf | shubhamkanade/Niyander-Python | /Assignment 2/2.py | 160 | 4.125 | 4 | def Display(num):
for i in range(1,num+1,1):
for j in range(1,num+1,1):
print("*",end=' ')
print()
num=input("Enter a number")
Display(int(num))
|
f45557739889628235ae6991acd9954d94c84e0a | shubhamkanade/Niyander-Python | /funtion_parameter_variable.py | 107 | 3.546875 | 4 | def printinfo(i,*value):
for Value in value:
print Value
print i
printinfo(10)
printinfo(10,20,30,40)
|
9597da53e2c7be1ccd30f2c254fd401ca31a71cc | shubhamkanade/Niyander-Python | /class_mult.py | 342 | 3.921875 | 4 |
class Arithematic:
def __init__(self,no1,no2):
self.no1 = no1
self.no2 = no2
def mult(self):
return self.no1 * self.no2
def main():
no1 = int(input("Enter first number"))
no2 = int(input("Enter second number"))
obj = Arithematic(no1, no2)
print("Multiplication is %d" % obj.mult())
if __name__ =... |
73d3797160f42afcc0b1b851e73fa43bdd65b762 | shubhamkanade/Niyander-Python | /Array_sum_tuple.py | 128 | 3.53125 | 4 | def array_sum(tuple):
sum=0
for i in tuple:
sum=sum+i
return sum
tuple=(10,3,5,4)
sum=array_sum(tuple)
print sum
|
da7e15cecf24b2d27287f9026b27c4b44f843218 | shubhamkanade/Niyander-Python | /Assignment 3/3.py | 497 | 3.90625 | 4 | def AcceptList():
n=int(input("Enter n elements"))
arr=list() #crerates empty list
for i in range(0,n):
arr.append(int(input())) #w/o int it takes in string
return arr
def ListMin(arr):
min=arr[0]
for i in arr:
if(i<min):
... |
e98641092722f6dbd0daf965c4a237467613b699 | shubhamkanade/Niyander-Python | /Print_even.py | 102 | 3.96875 | 4 | def print_even(no):
for x in range(2,(no*2)+2,2):
print x
x=input("Enter a number")
print_even(x)
|
3f82d1484cc32b41da56acfb0ceea32689e368ad | shubhamkanade/Niyander-Python | /Assignment 4/4.py | 482 | 3.5625 | 4 | from functools import reduce
def AcceptData():
n = int(input("Enter N number"))
brr = list()
for i in range(0,n):
num = int(input())
brr.append(num)
return brr
def even(no):
return not no%2
def cals(no):
return no*no
def add(no1,no2):
return no1 + no2
def main():
ans = AcceptData()
print(ans)
fdat... |
a498c902b7eafa829b802cf57dc1ee814ad29558 | shubhamkanade/Niyander-Python | /Assignment 3/4.py | 495 | 3.953125 | 4 | def AcceptList():
n=int(input("Enter n elements"))
arr=list() #crerates empty list
for i in range(0,n):
arr.append(int(input())) #w/o int it takes in string
return arr
def Count(arr):
print("eNTER the number to search")
no=int(input())
icnt=0
for i in arr:
if(no... |
a912cc2a7b6948d72984d1319c73bddedff96909 | shubhamkanade/Niyander-Python | /addition_subtraction.py | 200 | 3.8125 | 4 | a=10
b=20
c=0;
d=0;
f=10;
c=a+b
print("addition is ",c)
c=a-b;
print("subtraction is",c)
c=a*b
print("multiplication is ",c)
d=17%4
print("mod is ",d)
e=2**3
print("power is ",e)
f+=a
print(f)
|
9c65b6a57b745b64a96cd6661b0300b40e27f315 | BornaIz/python-workshop | /basics/1-3-assignment.py | 348 | 3.6875 | 4 |
### Assignment ###
# interactive prompt automatically writes the result of expression
# print is not necessary
# integer
a = 12
print a
# changing the value
a = 5
print a
# string
A = "Random text"
print A
# float
b = -2.5
print b
# reference assignment
c = A
print c
a = c
print a
# assignments can chain
a... |
ae0344d8f0d66f64959efd8e51159da403f2290e | AlexJackson31/ML | /file.py | 403 | 3.578125 | 4 | from datetime import datetime
msg=input("Enter the message:")
ty=input("Enter the type of message:")
now=datetime.now()
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
with open("log.txt","a+") as file:
str="Message: "+msg+"\nType: "+ty+"\nCreated on: "+date_time+"\n"
file.write("\n"+str)
file.seek(0... |
dd9c0b0dfb76a3bb3e3dbd1c5aada211c077d3b0 | dudamalinski/Login_Senha_Hash | /loginesenhaMd5.py | 2,559 | 3.765625 | 4 | def login():
"""
modulo de cadastro e autenticação de usuario
seus dados serão criptografados e gravados em um .txt
:return: sem retorno
"""
from hashlib import md5
import sys
def linhas():
print('\033[1;90m==\033[m'*20)
while True: # início do programa
... |
5a5dbb0c9215d31cf23825eb8d2dc09367cfd017 | JonesCD/codingbat | /string-2/count_hi.py | 162 | 3.765625 | 4 | def count_hi(str):
count = 0
if 'hi' in str:
for i in range(len(str) - 1):
if str[i] == 'h' and str[i + 1] == 'i':
count += 1
return count |
a82f64276a3eee1c78387217b7fc189108e16c21 | romulusdias/python | /Fib.py | 148 | 3.703125 | 4 | def fib(n): # write Fibonacci series upto n
a, b = 1, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(78) |
6feb0d1f89d91f607da801a50f62de6c63c40938 | Kaminarusawa-sekai/Numerical-analysis | /testtest.py | 682 | 3.578125 | 4 | from sympy import *
def fFunc(x):
y=pow(x,2)-4*x+3
return y
def newtonDownhill(a):
x=symbols('x')
y=pow(x,2)-4*x+3
diffFunc=diff(y,x)
def downhillFactor(a,factor):
b=a-factor*fFunc(a)/diffFunc.subs('x',a)
if abs(b)>abs(a):
factor=factor/2
downhillFactor(... |
87ecbc0064a844e81f11f73ba630b9e73c4ca9a7 | GateNLP/gateapplication-hyperpartisanclassification | /Preprocessing/features.py | 1,165 | 3.875 | 4 | """
Constants and functions related to the features.
"""
FEATURES = [
]
def doc2features(doc, features):
"""
Extract the features from the document. Each feature is either just the name
or a tuple of (name,flag,type) where flag indicates if the feature should get
selected. This returns the features i... |
4586f8fedc3e8a2b8818680313d2ec885d8d973d | jakamrak/uvod-v-programiranje | /datoteke-s-predavanj/2015-16/05-seznami/financniki/for.py | 1,351 | 3.53125 | 4 | def najvecji_element(sez):
'''Vrne največji element seznama sez. če je prazen, vrne None.'''
if len(sez) == 0:
return
najvecji_do_zdaj = sez[0]
for x in sez:
if x > najvecji_do_zdaj:
najvecji_do_zdaj = x
return najvecji_do_zdaj
def najvecji_element(seznam):
'''Vr... |
42b90016b4954cf473c7858b0a49ed47f14c6752 | jakamrak/uvod-v-programiranje | /datoteke-s-predavanj/2018-19/02-rekurzija/fibonacci-a.py | 226 | 3.890625 | 4 | # F0 F1 F2 F3 F4 F5 F6 F7
# 0 1 1 2 3 5 8 13
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
fibonacci(7)
|
999e38da926b4954316b3b813503c85d1c6279d8 | jakamrak/uvod-v-programiranje | /datoteke-s-predavanj/2016-17/04-ucinki/stranski-ucinki-a.py | 623 | 3.78125 | 4 | def fibonacci(n):
print('Računam vrednost pri', n)
if n == 0 or n == 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def f(x):
return x + 2
return x + 3
return x + 4
def g(x):
print(x + 2)
print(x + 3)
return x + 4
def pozdrav(ime):
if ime == 'Mati... |
ec6bf324e0722938d13fe608f91fca87bde9f701 | jakamrak/uvod-v-programiranje | /datoteke-s-predavanj/2016-17/05-zanke/vsote-a.py | 959 | 3.796875 | 4 | matrika = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
seznam = [1, 10, 20, 40]
vsota = 0
for x in seznam:
print('začenjam obhod')
print(x, vsota)
vsota = vsota + x
print('končal sem obhod')
print(vsota)
def vsota_seznama(sez):
vsota = 0
for element in sez:
vsota += element
return vsota
def... |
1dbb684bf3ac30d24fd464c4243a718a51172c84 | jakamrak/uvod-v-programiranje | /datoteke-s-predavanj/2015-16/12-izjeme-in-iteratorji/financniki/kalkulator.py | 974 | 3.875 | 4 | print('Pozdravljen v fantastičnem kalkulatorju!')
while True:
try:
racun = input('Kaj bi rad izračunal? ')
print('Odpiram plin na pečici.')
x, op, y = racun.split()
if op == '+':
rezultat = int(x) + int(y)
elif op == '*':
rezultat = int(x) * int(y)
... |
acd7208964d129f95401f7c8d759ca572bddbfa8 | ZhangChengL/s14 | /zsq.py | 1,852 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
#
# def decorartor(func):
# def wrapper(n):
# print('starting')
# func(n)
# print('stopping')
#
# return wrapper
#
#
# def test(n):
# print('in the test arg is %s' % n)
#
# decorartor(test)('alex')
def decorartor(func):
... |
7addf934ce8a8de65784e4eb08099b69d8d0d50e | ZhangChengL/s14 | /ceshi3.py | 250 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
acc_mon = open('byacc','r+')
a = input('name')
for acc_mons in acc_mon:
(acc_use, acc_money) = acc_mons.strip().split()
print(acc_use)
a not acc_use:
print(acc_money) |
977f7a3036e58ca863106f012b4a774dadb5a877 | awillats/SkillsWorkshop2017 | /Week01/Problem05/Abhiraj_5.py | 472 | 3.796875 | 4 | #!/usr/local/bin/python3.6
prime = [19,17,13,11,7,5,3,2]# primes below 20
n = []
for i in range(1,21):
n.append(i)
lcm = 1
def checkprime(prime):
size = len(n)
flag = 0
count = 0
while(count < size):
if(n[count]%prime == 0):
n[count] = n[count]//prime
if (n[count] == 1):
n.pop(count)
count -=1
... |
fe5607dbefb80f85eb7f09fb059ae3d062a05698 | awillats/SkillsWorkshop2017 | /Week01/Problem01/Abhiraj_1.py | 168 | 4.15625 | 4 | #!/usr/local/bin/python3.6
sum = 0
for i in range(1,1000):
if (i%3 == 0) or (i%5 == 0):
sum += i
print("The sum of all multiples of 3 or 5 below 1000 = ",sum)
|
feb4a16efe9e7a5206f7ef5429d53ad843e76c44 | awillats/SkillsWorkshop2017 | /Week01/Problem01/klundquist_01.py | 201 | 3.875 | 4 |
limit = 1000
num = 3
total = 0
while num < limit:
total = total + num
num = num + 3
num = 5
while num < limit:
if num%3 != 0:
total = total + num
num = num + 5
print(total)
|
b0694c0a3f5f7ee780f3474c265c4c0c7c92666a | awillats/SkillsWorkshop2017 | /Week01/Problem01/qxu_01.py | 97 | 3.546875 | 4 | sum = 0
for ii in range(1,1000):
if ii % 3 == 0 or ii % 5 == 0:
sum += ii
print(sum)
# 233168
|
41c4a02b14bcf59e342788c0441462297ca0d198 | awillats/SkillsWorkshop2017 | /Week01/Problem04/awillats_04.py | 1,200 | 4.34375 | 4 | import math
#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def checkIfPal(num):
#in more robust program would check if the number is an integer he... |
7fce809d38a47cbccf7e1c65b5b09080d464e198 | awillats/SkillsWorkshop2017 | /Week01/Problem03/msoto_03.py | 194 | 3.59375 | 4 | #!/usr/bin/env python
##What is the largest prime factor of the number 600851475143?
i=2
number=600851475143
while i < number:
while number%i == 0:
number = number/i
i+=1
print(number)
|
7e41b08d0f7a24bce1d667627ad898a153967a65 | awillats/SkillsWorkshop2017 | /Week01/Problem05/opangarkar_05.py | 362 | 3.6875 | 4 | from __future__ import print_function
def max():
d = range(20, 10, -1) # only check multiple of 11 through 20
n = 20
while True:
for x in d:
if n % x != 0:
break
else: # no break happened, all multiples
return n
n += 20 # multiple of 20 shou... |
9cb693d3c405e94257d61465c208f6367c6bd0fd | gotoofar/effective_Python | /chapter2/18_19.py | 1,853 | 3.640625 | 4 | # -*- coding=utf-8 -*-
'''
18.用数量可变的位置参数减少视觉杂讯
'''
def log(message,*values):
if not values:
print(message)
else:
values_str=','.join(str(x) for x in values)
print('%s:%s'%(message,values_str))
log('My numbers are ',1,2)
log('Hi there') #不传入也不要紧
'''把已有的列表传给带有变长参数的函数,前面加个*'''
favorite... |
91fb6086eb0083edee5504941386e166f4d3eb06 | M7hesh/Python-Projects | /Codecademy-Python/3_pizza_slice.py | 441 | 4.15625 | 4 | toppings = ['pepperoni', 'pineapple','cheese','sausage','olives','anchovies','mushrooms']
prices = [2,6,1,3,2,7,2]
num_pizzas = len(toppings)
print("We sell",num_pizzas, "different kinds of pizza!")
pizzas = list(zip(prices, toppings))
print(pizzas)
pizzas.sort()
cheapest_pizza = pizzas[0]
priciest_pizza = pizzas[-1]... |
569aad00f624b6096d495c6d18d2ea43b495ab52 | gargemilika/ozon-book | /cap.py | 172 | 3.671875 | 4 | def capitalize(data):
if data == "":
return ""
# head, *other = data
# return head.upper() + "".join(other)
return data[:1].upper() + data[1:]
|
92a5f1599ff7cc4e72a30bbb965ab8c67b14ebd6 | YuriiKhomych/ITEA_AC | /Serhii_Hidenko/l_3_oop/hw/decorators.py | 725 | 3.5625 | 4 | import functools
import time
def execution_time_and_result_decorator(
func=None, *, filename="functions_executions.txt"
):
"""Decorator for writing to file functions execution time and results"""
def outer_wrapper(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
ti... |
010257800d589cdad3c8a8eeaee288897d97530a | YuriiKhomych/ITEA_AC | /Yurii_Khomych/l_6_files/file_read_write_examples_1.py | 2,525 | 3.78125 | 4 | # f = open("text_file_name_1.txt", "w")
#
# f.write("Good")
# f.close()
# with open("text_file_name.txt", "r+") as file:
# print(file.read())
# print(file.read())
# print()
# file.read()
# try:
# f = open("text_file_name_1.txt", "w")
# f.write("Good")
#
# except , :
#
# finally:
# f.close()
# with ... |
d1d2e1197cc71485a32ca78067bc2aae320afe9a | YuriiKhomych/ITEA_AC | /Yurii_Khomych/l_4_iterators_generators/class_static_2.py | 972 | 3.796875 | 4 | # from abc import ABCMeta, abstractclassmethod
#
# class BasePizza:
# @abstractclassmethod
# def margherita(cls):
# pass
#
import math
class Pizza:
def __init__(self, ingredients, radius):
self.ingredients = ingredients
self.radius = radius
def __repr__(self):
return f... |
edf88a824ed1a3ba979110225f1d70d77a251f85 | YuriiKhomych/ITEA_AC | /Yurii_Khomych/l_4_iterators_generators/ex_14_series_iterator.py | 792 | 3.5 | 4 | class Series:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
... |
afe14f896c8b8cc3c451ddc41ed8a8176e2e1cf7 | YuriiKhomych/ITEA_AC | /Yurii_Khomych/l_7_packages/collections_examples/default_dict.py | 354 | 3.859375 | 4 | from collections import defaultdict
dd = defaultdict(list)
# Accessing a missing key creates it and initializes it
# using the default factory, i.e. list() in this example:
dd["dogs"].append("Rufus")
dd["dogs"].append("Kathrin")
dd["dogs"].append("Mr Sniffles")
dd["dogs"]
my_dict = dict()
my_dict["dogs"].append("Ru... |
e66c3b80a337e4845ed65febf53d61b72e662b6b | mehmeetereen/COMU-Prog_Lab | /06.03.20.py | 1,503 | 3.75 | 4 | FiniteSet || Symbol
x=5 'x'
a=100 'a'
z=(x+y)**3-2xy
FiniteSet(1,2,3)
intersect
union
**
t=Finiteset(1,2,3)
t==s
t.union(s)
t.intersect(s)
t**2
def probability(space,event):
return len(event)/len(space) #Olay/Tüm Olaylar
def checkprime(number):
if number!=1:
for factor in... |
307791673b4a3d7ce65e42a3ce26e4e677986df1 | mehmeetereen/COMU-Prog_Lab | /17blm202programlama_lab_odev_2/170401068_hw_2.py | 1,580 | 3.875 | 4 | import os
import sys
def hist(document):
histogram = []
data = []
for i in document:
check = False
data.append(int(i.split(";")[3].split("-")[1]))
for k in range(len(histogram)):
if int(i.split(";")[3].split("-")[1]) == histogram[k][0]:
histogram[k][1] += ... |
f18e87a0e45f4d509590a6f089e84e66c1e46c62 | drkvogel/python | /misc/misc.py | 1,012 | 4.40625 | 4 | """
Learn python3 in Y Minutes (https://learnxinyminutes.com/docs/python3/)
"""
# given_name = input("What's your name? ")
print("Hello, {name}".format(name=given_name))
for i in range(3):
print("an ting ", end="")
print("aye...")
for animal in ["cat", "dog", "rabbit"]:
print("{} is a mammal".format(animal))
fo... |
ac68bddefeab52bcedc4d1f306f561bd07edc21c | drkvogel/python | /misc/fib.py | 291 | 4.1875 | 4 |
def fib(n):
a, b = 0, 1
while b < n:
# print(b)
yield a
a, b = b, a + b
# >>> print([i for i in fib(30)])
# [0, 1, 1, 2, 3, 5, 8, 13]
# [python - What does the "yield" keyword do?](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do)
|
8087bc423fa1fcd83b1eaa3db94d1c1b07f720c0 | abaransy/Tough-Problems-Elegant-Solutions | /problems/daily_temperatures.py | 1,136 | 3.90625 | 4 | # Given a list of daily temperatures T, return a list such that, for each day in the input,
# tells you how many days you would have to wait until a warmer temperature. If there is no
# future day for which this is possible, put 0 instead.
# For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, ... |
f56eb6b919aeceb307b0ee789e16a4e2af5ebdd0 | temir-org/temir-org.github.io | /teaching/information-retrieval-ss22/preprocessing.py | 2,901 | 3.5625 | 4 | import re
class Preprocessor:
def __init__(self, stopword_file="../data/stopwords.txt"):
self.stopwords = self._get_stopwords_(stopword_file)
@staticmethod
def _get_stopwords_(path):
"""
Reads a list of stopwords from the specified file
:param path: path to the stopwords fi... |
2c26c1d0537a7c978c1593dd424646aba3cc04e9 | tanmoy1999/eleko_assistant | /versions/eleko.py | 2,249 | 3.703125 | 4 | import speech_recognition as sr
import wikipedia as wiki
import pyttsx3
r = sr.Recognizer()
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice','voices[0].id')
def speak(text):
engine.say(text)
engine.runAndWait()
def eleko_wiki(text):
k = tex... |
14175d4b625f58bbf39a00b4ff07d40954e02c4e | MohdFazalm99/My-100DaysOfPython | /Day6/Defining_&_Calling_functions.py | 444 | 3.921875 | 4 | # FUNCTIONS in Python
"""
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result."""
# Creating a Function
# In Python a function is defined using the def keyword:
# Example
def my_function():
print("Hello "... |
04682ef37eb8ee7e1590757fda409ec02bd0b6dd | MohdFazalm99/My-100DaysOfPython | /Day2/Number_manipulation_F-strings.py | 623 | 4.15625 | 4 | # Rounding Number
print(round(8/3))
print(round(8/3,2))
print(round(2.6666666666,3))
# FLOOR-DIVISION =Python uses // as the floor division operator and % as the modulo operator.
# If the numerator is N and the denominator D, then this equation N = D * ( N // D) + (N % D) is always satisfied. Use floor division ope... |
ce203d1f13c9ff455b7c581f9a756c5e070b2e6d | MohdFazalm99/My-100DaysOfPython | /Day10/functions_with _output.py | 326 | 4.09375 | 4 | # Function with output
# Now here we will use titile() which is used for Making every first letter of a word captial_case
def format_name(f_name,l_name):
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f"{formated_f_name} {formated_l_name}"
print(format_name("fazal", "MAHM... |
ca27552b1b9484f5bc109f22533109e5b0ed3890 | MohdFazalm99/My-100DaysOfPython | /Day13/indent_error.py | 279 | 4.03125 | 4 | #Use a Debugger
def mutate(a_list):
b_list = []
for item in a_list:
new_item = item * 2
# Here is the error we indent the b_list inside the for loop otherwise it will only give us one output that is 26 .
b_list.append(new_item)
print(b_list)
mutate([1,2,3,5,8,13]) |
3f9a264c4e20ddf93ba78e9b8b1190c0c6cb6733 | MohdFazalm99/My-100DaysOfPython | /Day2/tip_calculator.py | 423 | 4.0625 | 4 | print("Welcome to the tip calculaotr. ")
total_bill = input("What was the total bill? ")
percent_tip = input("What percentage tip would you like to give? ")
people = input("How many people to split the bill? ")
total_bill_int = int(total_bill)
percent_tip_int = int(percent_tip)
people_int = int(people)
bill_pay = (t... |
43764ebbd857789ed70fa5adf4b071db874f197e | KhalidGit/Project_euler_solutions | /Python/Problem-5.py | 938 | 3.609375 | 4 | #!/usr/bin/env python3
# Problem 3
# https://github.com/KhalidGit/Project-Euler-solutions
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# ---------------i... |
4f37f3b2471d7f2c9d65e4cd3e84ce85586a4980 | vrussillo/dadlibs | /stories.py | 4,402 | 4 | 4 | class Story:
def __init__(self, code, title, words, text):
"""Create story with words and template text."""
self.code = code
self.title = title
self.prompts = words
self.template = text
def generate(self, answers):
"""Substitute answers into text."""
t... |
3916ae1547876578d9241d8ccfe6aa958b9e0e65 | dnewbie25/Python-Quick-Reference | /Example Exercises/Excepciones_Explicación_1.py | 1,343 | 4.25 | 4 | '''Exception Handling'''
def sum(num1, num2):
return num1 + num2
def substract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
'''def divide(num1, num2):''' # Si el denominador es cero esto va a causar un crash
'''return num1 / num2'''
# Para evitar eso usamos un try - except
de... |
89de58c06d25e888166831f288245d444d9cdfd9 | dnewbie25/Python-Quick-Reference | /Automate The Boring Stuff Projects/7 Pattern Matching with Regular Expression/Project_Strong_Password_Detection.py | 1,293 | 4.40625 | 4 | """Function to test a strong password. It must have at least:
8 characters long
Contains upper and lower case characters
1 digit minimum
"""
import re
password_to_test = input("Enter a password to test: ")
def regexStrong(password):
lowercaseRegex = re.compile(r'[a-z]') # any lower case letter
uppercaseRegex =... |
65dbf57dc94d9c7a808d22c89ebb5e570bf3d794 | dnewbie25/Python-Quick-Reference | /Automate The Boring Stuff Projects/C2_Guess_The_Number.py | 893 | 4.125 | 4 | import random, sys
# Let the computer guess a number
def computer_guess():
choice = random.randint(0,100)
return choice
# Let the user choose a number
def player_guess():
player = input("Enter a number to play or 'q' to exit: ")
if player == 'q' or player == 'Q':
sys.exit()
else:
player = int(playe... |
00e4f47858aa4c91359ef2f61e26a1c0df5ec0c2 | dnewbie25/Python-Quick-Reference | /Automate The Boring Stuff Projects/7 Pattern Matching with Regular Expression/Project_Regex_Strip_Method.py | 1,539 | 4.25 | 4 | """Write a function that does the same as the strip( ) method
The strip method removes whitespaces at the start and end of a string
"""
import re
text_to_strip = input("Enter your text here:\n")
def myOwnStrip(text, character = ''):
if character == '':
replace = ''
startWhitespaceRegex = re.compile(r'^\s... |
4bbabe00da6c3d39487134cc4915a9009f74febf | dnewbie25/Python-Quick-Reference | /Example Exercises/Basic Exercises/9_Lists_Methods_Recap.py | 646 | 4.21875 | 4 | # Each list methods should be used at leat once
my_list = ['Car', 'Trophies', 'Motorcycles', 'Airplanes', 'Ships', 'Toys']
print(my_list)
# Change an item
my_list[0] = 'Glasses'
print(my_list)
# Appends
my_list.append('Cellphones')
print(my_list)
# Insert
my_list.insert(1, 'Medals')
print(my_list)
# Del
del my... |
969b07ba31182afa1def78f0f6d175f35dda98b5 | dnewbie25/Python-Quick-Reference | /Example Exercises/Basic Exercises/29_Writing_to_a_File_Exercises.py | 1,698 | 4.21875 | 4 | from datetime import date, timedelta # In order to use the current day and add days to it
from random import randint # To add a random number to current date
today = date.today()
# Guests
filename = 'Files Samples/guest.txt'
def ask_name(): # Create a function that asks for the name of the guest
name = input("Wha... |
b4782f1cd7e927c8c42bc3972917b0faebe521cb | dnewbie25/Python-Quick-Reference | /Python Crash Course Projects/Data Visualization/random_walk_visualization.py | 489 | 3.65625 | 4 | import matplotlib.pyplot as plt
from random_walk import RandomWalk
# Make a RandomWalk instance in variable rw
rw = RandomWalk()
# Call RandomWalk fill_walk( ) method
rw.fill_walk()
# Plot the points in the walk
plt.style.use('classic') # classic style
fig, ax = plt.subplots() # creates a figure contaiing a si... |
9430973e715a15351c3cf59dfad958c846206b60 | dnewbie25/Python-Quick-Reference | /Example Exercises/Basic Exercises/test_language_survey_35.py | 2,171 | 4.1875 | 4 | import unittest
from language_survey_35 import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""Test for the class AnonymousSurvey"""
def setUp(self):
"""Create a survey and a set of reponses for use in all test methods"""
# This method setUp( ) creates an instance that can be used in the ... |
9eb8e96647a735e6507f0fe1f255a8abd3d2bece | dnewbie25/Python-Quick-Reference | /Example Exercises/Basic Exercises/16_Dictionary_Polling.py | 763 | 4.40625 | 4 | # Create a dictionary with the favorite programming languages of certain people
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
# Create alist of people missing for saying their favorite language
people_missing = ['max', 'tim', 'sarah', 'rachel', 'thomas', 'phil', 'p... |
d0c3418de77b7f01d5bbb5c5261547e4a558935a | dnewbie25/Python-Quick-Reference | /Python Crash Course Projects/Data Visualization/random_walk.py | 1,358 | 4.46875 | 4 | from random import choice
class RandomWalk:
"""A class that generates random walks"""
def __init__(self, num_points=5000):
"""Initialize the attributes of a walk"""
self.num_points = num_points # the numbers of points in the walk, it can be as many as you want
# All walks start at (0, 0)
self.x_... |
192ed66c48bed24181f2dfe7645b259f6a360509 | MoDo-coer/GIT | /exercise01_server.py | 1,852 | 3.765625 | 4 | """
练习2: 基于dict数据库中的words表完成
从客户端输入单词,发送给服务端,得到单词的
解释,并打印出来
接收单词 --》 查询单词解释 --》 发送单词解释
"""
from socket import *
import pymysql
# 数据库处理
class Dict:
def __init__(self):
self.kwargs = {
"user": "root",
"password": "123456",
"database": "dict",
"charset": "utf8... |
336ff7714deeca5740ab78d55370b6993c2d60ab | ellis-madagan/word_fun | /word_fun.py | 175 | 3.75 | 4 | import string
def palindrome(s):
translator = str.maketrans('', '', string.punctuation)
s = s.replace(' ', '').lower().translate(translator)
return s[::-1] == s
|
731d835ba700f6aa91b4d4baeb375489fcdd0ceb | raydouglass/python_sql | /python_sql/b_tree.py | 10,075 | 3.890625 | 4 | from collections import MutableMapping
from functools import total_ordering
def set_siblings_pair(left, right):
left.next_sibling = right
right.prev_sibling = left
def set_siblings(children):
for i in range(1, len(children)):
set_siblings_pair(children[i - 1], children[i])
# https://www.cs.usf... |
48941b2be53e2e8b43086ac854e0eb742c2d9392 | ngcogan/2021_R7_Microbit | /20210223_scissorspaperstone.py | 624 | 3.796875 | 4 | # 20210223 - Scissors Paper Stone
# This code has a minor change. Rather than using ARROW_W as the "Scissors" image, I have defined a variable called scissors, and in the variable it shows an image which looks more like a scissors.
from microbit import *
import random
scissors = Image("99099:99099:00900:09090:90009")... |
036aa7b417ef368cd10787c2b916f62a97b71463 | HuichuanLI/alogritme-interview | /考试/深幸福.py | 424 | 3.828125 | 4 | # 有排成一行的n个方格,用红(Red)、粉(Pink)、绿(Green)三色涂每个格子,每格涂一色,
# 要求任何相邻的方格不能同色,且首尾两格也不同色
# .求全部的满足要求的涂法.
# RPG 难题
def result(n):
res = [0] * (n + 1)
res[1] = 3
res[2] = 6
for i in range(3, n + 1):
res[i] = res[i - 1] + 2 * res[i - 2]
return res[-1]
print(result(10))
|
d7ebfb48b06676422eb079a3c24c73f5d02d85e0 | HuichuanLI/alogritme-interview | /Chapter11_每日一题/rejection_sampling/lc470.py | 622 | 3.78125 | 4 | # The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution:
def rand10(self):
"""
:rtype: int
"""
while True:
nums = (rand7() - 1) * 7 + rand7()
if nums <= 40:
return nums % 10 + ... |
4967699822f542afc769a3e40012ce74dd15eae3 | HuichuanLI/alogritme-interview | /Chapter17String/lc288.py | 691 | 3.5 | 4 | from collections import defaultdict
class ValidWordAbbr:
def __init__(self, dictionary: List[str]):
self.mp = defaultdict(set)
for s in dictionary:
abbr = self.getAbbr(s)
self.mp[abbr].add(s)
def isUnique(self, word: str) -> bool:
abbr = self.getAbbr(word)
... |
e6ab2f9f1f99192929e6729cee41592b9fcef48a | HuichuanLI/alogritme-interview | /Chapter11_每日一题/lc1451.py | 406 | 3.546875 | 4 | from collections import defaultdict
class Solution:
def arrangeWords(self, text: str) -> str:
count = defaultdict(list)
for elem in text.split():
count[len(elem)].append(elem)
res = []
for elem in sorted(count.keys(), reverse=False):
for items in count[elem]... |
4b5b99ec9a1d020438e8c86a97d5a5f3b84d8e13 | HuichuanLI/alogritme-interview | /Chapter02_Search/leetcode290.py | 1,097 | 3.671875 | 4 | class Solution:
# - 时间复杂度: O(N ^ 2) - 空间复杂度: O(N)
def wordPattern(self, pattern, str):
str_array = str.split(" ")
if len(pattern) != len(str_array):
return False
dict1 = {}
for p_ele, str_ele in zip(pattern, str_array):
if not dict1.get(p_ele, None):
... |
12880c4111d0d77de4a356f871f7c857dd66cf64 | HuichuanLI/alogritme-interview | /Chapter05_Tree&Recurison/lc257.py | 1,560 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Travales
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if root is None:
return []
result = []
... |
3b1994294a3d0c624dfe49543330fe2e70a64447 | HuichuanLI/alogritme-interview | /Chapter07_dynamicProgramming/leetcode198.py | 2,369 | 3.53125 | 4 | class Solution:
def rob(self, nums):
if not nums:
return 0
res = []
self.combination(nums, 0, 0, res)
return res[0]
def combination(self, nums, index, sum, res):
if index >= len(nums):
res.append(sum)
return
for i in range(inde... |
24ba2ebdd40635251913da5c2061e698ef209b1d | HuichuanLI/alogritme-interview | /考试/dianxing3.py | 401 | 3.515625 | 4 | import sys
def max_value(nums) -> int:
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
res = [0] * (n + 1)
res[0] = 0
res[1] = nums[0]
for i in range(2, n + 1):
res[i] = max(res[i - 1], res[i - 2] + nums[i - 1])
return res[-1]
line = sys.stdin.read... |
22eeb9b2325a04c839e3f201b4ea50ea08d3b62c | HuichuanLI/alogritme-interview | /Chapter13Trie/lc208.py | 1,651 | 3.984375 | 4 | class Node:
def __init__(self):
# is_word表示这个结点是否为一个单词的结尾
# next[]表示这个结点的下一个26个字母结点
self.is_word = False
self.next = [None] * 26
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def insert(self... |
967c54ebd9e3e7a1f17010694bebc3026a024991 | HuichuanLI/alogritme-interview | /Chapter01_ArrayProblem/lc796.py | 372 | 3.671875 | 4 | class Solution:
def rotateString(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
if A == B:
return True
for index, a in enumerate(A):
if a != B[0]:
continue
else:
if A[index:] + A[:index] == B:
... |
919cd56c52f098b5114823e7c0541811cb5ba971 | pra-kri/ProjectEuler | /ProjectEulerProblem010_PK.py | 740 | 3.921875 | 4 |
print(total_sum)
def find_if_prime(z):
is_prime = True
for i in range(2, z):
if z%i == 0:
is_prime = False
break
return is_prime
for k in range(2,20000):
if find_if_prime(k) is True:
total_sum += k
print(total_sum)
"""
worst possib... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.