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 |
|---|---|---|---|---|---|---|
62eb81ecdd1e11a168c906324cfb9375ac708eba | joseramirez270/pfl | /Assignment4/tokenizedwords.py | 395 | 3.96875 | 4 |
def get_tokenizedwords(filename):
"""taking a filename as input, returns a list of tokenized words"""
import nltk
file = open(filename)
text = file.read()
tokens = nltk.tokenize.word_tokenize(text)
return tokens
tokens = get_tokenizedwords('C://Users//owner//desktop//clma//fall2015//pfl//assignmen... |
bb8749c3abda670d006b2184f7b620449bb54f07 | joseramirez270/pfl | /Assignment4/generate_model.py | 1,180 | 4.1875 | 4 | """modify this by generating the most likely next word based on two previous words rather than one. Demonstrate how it works with a corresponding conditional frequency distribution"""
import nltk
"""essentially, this function takes a conditional frequency distribution of bigrams and a word and makes a sentence.
... |
c232b417ebbeaa4a299969cdd7f4bc9290260ac5 | jyoung2119/Class | /Class/demo_labs/PythonStuff/LoopStuff/treadmill.py | 171 | 3.625 | 4 | #Loop Practice
def main():
calBurn = 3.9
for i in range(2,7):
i = i*5
print("Calories burned after", i, "minutes = ", i*calBurn)
main()
|
5c0cc6efb5f8c01d93791d1df6b14d3727e0fb8f | jyoung2119/Class | /Class/demo_labs/PythonStuff/5_4_19Projects/carLoan.py | 631 | 4 | 4 | # Determine the monthly payment for a car loan.
def main():
loanAmount = float(input("Enter amount of loan: "))
intRate = float(input("Enter interest rate (%): "))
ratePer = (intRate / 12) / 100
years = int(input("Enter number of years: "))
numPayments = years * 12
#monPayment = float(l... |
b723b31f1c4f88e7ee14964492b9c320f689be87 | jyoung2119/Class | /Class/demo_labs/PythonStuff/5_6_19Projects/halfStuff.py | 214 | 3.984375 | 4 | #Function Practice
def main():
userInput = float(input("Enter a number to cut in half: "))
result = half(userInput)
print("Result = ", result)
def half(number):
return number / 2
main() |
a65754f85f70e2b11b8c4e2d3008b5ba7c51eee8 | jyoung2119/Class | /Class/demo_labs/PythonStuff/5_14_19Projects/FileAnalysis/fAnalysis.py | 1,146 | 3.703125 | 4 | #File Analysis
def main():
song1File = open("textFile1.txt", 'r')
song2File = open("textFile2.txt", 'r')
sharedWords = []
uniqueSong1 = []
uniqueSong2 = []
i = 0
x = 0
song1Text = song1File.read()
song1Words = song1Text.split()
song2Text = song2File.read()
son... |
1d118fe45f06cd5e2bf5c24b3cfd8d2a5b764a48 | jyoung2119/Class | /Class/demo_labs/PythonStuff/LoopStuff/softwareDiscount.py | 668 | 3.890625 | 4 | #Software Discount
def main():
cost = 99
packageNum = int(input("Enter Number of Packages Purchased: "))
if packageNum >= 10 and packageNum <= 19:
discount = (packageNum * cost) * 0.20
elif packageNum >= 20 and packageNum <= 49:
discount = (packageNum * cost) * 0.30
elif pa... |
0a93e0ded92ef09809aa22bd801667587171f6ed | jyoung2119/Class | /Class/demo_labs/PythonStuff/5_10_19Projects/dateClass.py | 1,918 | 4.15625 | 4 | #Class practice
class Date:
def __init__(self, m, d):
self.__month = m
self.__day = d
#Returns the date's day
def get_day(self):
return self.__day
#Returns the date's month
def get_month(self):
return self.__month
#Returns number of days in ... |
ac1971b1544ccb491d9ed862258cc4bf3dbccae2 | inbsarda/Ccoder | /Python_codes/linked_list.py | 2,030 | 4.1875 | 4 | ###################################################
#
# Linked List
#
###################################################
class node:
def __init__(self, data):
self.data = data
self.next = None
def insertAtBegining(head,data):
'''
Insert node at begining
'''
newnode = node(data)
... |
a4c58d8162dbb4317ec0cfced87e8e3c71860f74 | inbsarda/Ccoder | /Python_codes/reverse_list.py | 1,161 | 4.3125 | 4 | ##################################################################
#
# Reverse the linked list
#
##################################################################
class node:
def __init__(self, data):
self.data = data
self.next = None
class linkedlist:
def __init__(self):
self.head =... |
1ec70a6b07b2946aa9cd5e305c5b9cc306fcf373 | daddykeba/Project-Edacy-DataScience | /project-edacy-datascience.py | 2,891 | 3.90625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 17:29:20 2019
@author: daddy
"""
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
"""Extraire et créer un fichier EXCEL contenant les liste des élèves ayant la moyenne"""
# Lecture de notre jeu de données
df = pd.rea... |
a1593b01f3f3c09d1c392c63612e81506d90243a | doritger/she-codes-git-course-1 | /ex2.py | 1,049 | 4.28125 | 4 | from datetime import datetime
# imports current date and time
def details():
first_name = input("Please enter your first name: ")
surname = input("Please enter your surname: ")
birth_year = input("Please enter the year of your birth: ")
# asks the user to enter name, surname and year of birth
print... |
765d447467c46c72f18ada8535f4c69aad36f7b7 | smoper0916/IFind | /service/test_methods.py | 2,928 | 3.65625 | 4 | '''
이 모듈은 테스트용 메소드 모음 모듈입니다.
'''
from flask import Flask
app = Flask(__name__)
@app.route('/hello')
def hello_world():
# make a collection , make a document
# it also has updating function
# start = time.time()
# doc_ref = db.collection(u'users').document(u'u2')
# doc_ref.set({
# u'fi... |
0e003caf017c7c9a667aacfdbf70c4dc3472e29f | dengtianxiang/python-learn | /com/xyg/python/py_07_exceptions.py | 406 | 3.515625 | 4 | #--coding:utf-8--
try:
float('abc')
except Exception,e:
print e
try:
float(1.0)
except Exception,e:
print e
finally:
print 'Do not forget to close database.'
try:
assert 1==0
except AssertionError, args:
print 'One does equal zero silly',args
try:
raise... |
e0e4bc9e80c3efd8af0cb4e0f66f8822a220eac0 | Raiane-nepomuceno/Python | /Parte 1/Ativividades do moodle/string/teste-ano.py | 355 | 3.71875 | 4 | b = str(input('Digite a segunda string[aa/aa/aaaa]:'))
if (int(b[0:2])>31 or int(b[0:2])< 0) and (int(b[4:5])>12 or int(b[4:5])<0) or (int(b[6:10])<1900 or int(b[6:110])>2020):
print('A data: {} está inválida.'.format(b))
#else:
# print('A data: {} está correta'.format(b))
print(int(b[0:2]))
print(in... |
54f0c2ccbcc0e19c82d3107e72eba87188e5ded8 | Raiane-nepomuceno/Python | /Parte 1/Lista 01/004.py | 356 | 3.8125 | 4 | #prova 70% trabalho = 30%
n1 = float(input('Digite a nota da prova:'))
n2 = float(input('Digite a nota do trabalho:'))
f = int(input('Digite a frequência do aluno:'))
m = (n1 * 7 + n2 * 3) /(7+3)
#print(m)
if m >= 6 and f >= 75:
print('Aprovado')
elif m >= 4 and m < 6 and f >= 75:
print('Recuperação')
else:
... |
a2536912436cee66852e285dbfac107ee2a6af42 | Raiane-nepomuceno/Python | /Parte 2/EXERCÍCIOS DE LISTAS/002.py | 413 | 3.890625 | 4 | op = 1
lista = []
maior = 0
while op == 1:
op = int(input('Deseja continuar [1]sim,[2]não:'))
if op == 1:
lista.append(float(input('Digite a altura:')))
for i in lista:
if i > maior:
maior = i
else:
print('A lista das alturas',lista)
... |
e99f4188c26f504edd8c36c30f9a5e92e626205e | Raiane-nepomuceno/Python | /Parte 2/MÓDULOS-RECURSÃO/003 - div inteira.py | 218 | 4 | 4 | #quociente
def div(x,y):#a = 8 b = 4
if x == y:
return 1
else:
return div(x,y+1)
x = int(input('Digite o dividendo:'))
y = int(input('Digite o divisor:'))
print('Quociente:',div(x,y))
|
8784038a66fd9ae741cb74ce7f903c314d4de19d | Raiane-nepomuceno/Python | /Testes/Operações básicas/Operadores Aritméticos[007].py | 170 | 3.78125 | 4 | n1=float(input('Digite a primeira nota do aluno(a):'))
n2=float(input('Digite a segunda nota do aluno(a):'))
m = (n1+n2)/2
print('A média do aluno(a) é {}.'.format(m))
|
2f46b74e3c11c481b45f5ec4f5b8ba46ab161fbf | Raiane-nepomuceno/Python | /Parte 1/Lista 03/002.py | 256 | 3.5 | 4 | prox = 0
count = 0
total = 9
vetor =[]
for i in range(total):
vetor.append(int(input('Digite o valor:')))
for i in range(total):
for x in range(total):
ant = vetor[i]
prox = vetor[x]
if ant!=prox:
count+=1
print(count)
|
45da0f3838cc9ad4dfd49c4b0a1e70355f3a6cea | Raiane-nepomuceno/Python | /Parte 1/Desafios/Desafio 02.py | 301 | 4.0625 | 4 | from random import randint
num = int(input('Digite um valor inteiro entre 1 e 10:'))
soma = 0
numero_sorteado = randint(1,10)
print(numero_sorteado)
while num != numero_sorteado:
soma = soma + numero_sorteado
numero_sorteado = randint(1,10)
print(numero_sorteado)
print('A soma é',soma)
|
c419b71308e0438158bd7d87b9084ea9f0be0885 | Raiane-nepomuceno/Python | /Parte 2/MÓDULOS-RECURSÃO/teste de soma com while.py | 350 | 3.71875 | 4 | #i = 10
#num = 100
#cont = 0
#soma = 0
def soma(num,i):
cont = 0
s =0
if soma<=num:
return soma(num(s+i))
else:
return cont+1
#while soma<=num:
# soma = soma + i
# cont = cont+1
#print(cont-1)
num = int(input('Digite a base:'))
i = int(input('Digite o expoente:'))
pr... |
d8bc6ebc86b2a42fa670df49d06330138889ab19 | Raiane-nepomuceno/Python | /Parte 1/Lista 01/002(2.1).py | 216 | 3.890625 | 4 | #Quantos são maiores que 10
cont = 0
for i in range(0,5):
valor = float(input('Digite o número:'))
if valor > 10:
cont = cont + 1
print('Há {} números maiores que 10'.format(cont))
|
5ccac32ec6db7ceeeb4c6daeb7ba08524124159d | Raiane-nepomuceno/Python | /Parte 1/Lista 01/003.py | 496 | 3.78125 | 4 | for i in range(0,1):
l = float(input('Digite a quantidade de lados do terreno:'))
c = float(input('Digite o comprimento do terreno:'))
cid = str(input('Digite a cidade que está localizada o lote [SP/Curitiba]:')).upper()
m = l*c
if cid == 'SP':
sp = 500*m
print('Em São Paulo custa R$... |
57044de69024d956548f000f130d1afe3b48e66a | Raiane-nepomuceno/Python | /Parte 1/Lista 01/011.py | 501 | 4.25 | 4 | n= int(input('Digite o número:'))
if n%2== 0 and n%5 == 0 and n%10 == 0:
print('O número {} é divisível por:2,5,10'.format(n))
elif n%2!= 0 and n%5 == 0 and n%10 == 0:
print('O número {} é divisível por 5 e 10'.format(n))
elif n%2!= 0 and n%5 == 0 and n%10 != 0:
print('O número {} é divisível apenas por 5'.... |
307749d59efe27650f9a95f1a8394b34648df56c | Raiane-nepomuceno/Python | /Parte 1/Lista 01/Resolução antes da prova/014.py | 186 | 3.859375 | 4 | i = int(input('Idade:'))
if i < 16:
print('Não eleitor')
elif i>=18 and i<65:
print('Obrigatório')
else:
if i>=16 and i<18 or i>65:
print('Facultativo')
|
7d315d98c3d2b268a600eee898b046512c0a42df | Raiane-nepomuceno/Python | /Parte 2/EXERCÍCIOS DE LISTAS/004.py | 600 | 4.15625 | 4 | #Crie um programa que leia
#Inicialmente uma sequencia de
#N números inteiros
#e mostre ao final 2 listas: uma sem repetição e outra dos elementos repetidos
op = 1
lista_rep = []
lista3 = []
while op == 1:
op = int(input('Deseja adicionar o elemento [1-sim/2-não]:'))
if op == 1:
n = int(input('Num:'... |
815779d7556eb00369532e1aab04f3f224e63dd4 | yaswanth12365/python-problems | /Count occurrences of an element in a list.py | 208 | 3.890625 | 4 | # Python code to count the number of occurrences
def countX(lst, x):
return lst.count(x)
# Driver Code
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x, countX(lst, x)))
|
5c7bf6be88f0c9ecb263a7ffc97cd245ea5b70fb | ouuzannn/BelajarPandas | /pandastutor02/pandas06.py | 284 | 3.828125 | 4 | import pandas as pd
import numpy as np
row = 5
col = 5
cols = tuple('ABCDE')
df = pd.DataFrame(np.random.randint(1, 10, size=(row,col)),columns=cols)
print(df)
#cara mengubah nama kolom
df = df.rename(columns={'C':'Hobi','A':'contoh'})
print(f'hasil perubahan nama kolom :\n{df}') |
651803d43bd068b338e81c86cf7d1e92423a7e46 | SamuelSchmidgall/ProjectEulerProblems | /completed/pe46.py | 649 | 3.5 | 4 | from tools import isPrime
primes = [i for i in range(2,10000) if isPrime(i)]
non_primes = [i for i in range(2,10000) if not isPrime(i)]
def find():
for np in non_primes:
hit = False
for p in primes:
if hit:
break
if p > np:
if np%2 == 1:
... |
afc39f57d68bf8c04086f1baf4acedc04344b5b6 | PatrikMosko/simple-projects | /minimize_automata/fsm.py | 23,449 | 3.5 | 4 | import re
from args import print_exit
class Rule:
def __init__(self, s1, c, s2):
self.s1 = s1
self.c = c
self.s2 = s2
class Token:
def __init__(self, name, type):
self.name = name
self.type = type
class State:
def __init__(self, name):
self.... |
f348416d9a81e1fcf71a4592e946b3d5eca5c29a | JWRickyWan/CS61A | /Projects/Disc03/Disc03.py | 196 | 4.0625 | 4 | """Discussion 3: Feb 12, 2020
-----------------Recursion---------------
"""
def product_nums(m,n):
if m ==0 or n==0:
return 0
else:
return m + product_nums(m,n-1)
|
59c1517b2ad8cfac4d186e417859ae5dbd190575 | pythoncoder999/Python | /AutomateTheBoringStuff/myPets.py | 272 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 27 01:06:29 2019
@author: Gunardi Saputra
"""
myPets = ["One", "Two", "Three"]
print("Enter a pet name: ")
name = input()
if name not in myPets:
print("I do not have a pet named " + name)
else:
print(name + " is my pet.")
|
fcf32576108205535d8df4add56deead88f71cf3 | pythoncoder999/Python | /AutomateTheBoringStuff/characterCount.py | 275 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 27 14:02:01 2019
@author: Gunardi Saputra
"""
message = "I like you. I miss you. You are my Python now and forever."
count = {}
for character in message:
count.setdefault(character, 0)
count[character] += 1
print(count)
|
32060afb09adbc8ddf2d3e019106cecf1c4f61b0 | drkvogel/perspectum-test | /scratch.py | 5,819 | 3.796875 | 4 | #!/usr/bin/python
#!/usr/bin/env python
'''
Scratch file for development
'''
# print "Hello, World!"
import sys # for sys.stdout.write
import analyse_lists
import StringIO
def analyse_lists_local(*lists):
# count = 0
# more_than_once = 0
# more_than_once = []
all_strings = []
list_unique = {}
... |
072121328b619ba4b25e4f65dfe503feb9b51020 | apaparun/training | /product_discount_tax.py | 587 | 3.90625 | 4 | '''Let us say that we want to update our code such that:
if the mobile brand is Apple then the discount is 10% else the discount is 5%
all shoes have 2% tax and no discount'''
def purchase_product(product_type,price,mobile_brand=None):
if product_type =="Mobile":
if mobile_brand == "Apple":
discount = 10
... |
fa0bbe971646fb2c5d15a7cec5d12b974273f427 | defeall/HackerRank | /Python/collection.deque().py | 370 | 3.609375 | 4 | from collections import deque
N=int(input())
d=deque()
for i in range(N):
o=input().split()
if(o[0]=='append'):
a=int(o[1])
d.append(a)
elif(o[0]=='appendleft'):
a=int(o[1])
d.appendleft(a)
elif(o[0]=='pop'):
d.pop()
elif(o[0]=='popleft'):
... |
b76c33101e6364b9803775d0f45302d4bfac39de | Randy17/DataScienceFromScratch | /ChapterOne/ChapterTwo.py | 3,631 | 3.640625 | 4 | l = lambda x, y : x / y
print(l(5, 2))
#lists
my_list_1 = list(range(10))
my_list_2 = [10,11,12]
print(1 in my_list_1 and 1 in my_list_2)
#tuples
my_tuple = (1, 2)
try:
my_tuple[0] = 3
except TypeError:
print('Unable to change tuple')
#dictionaries
my_dict = {'Joel' : 80, 'Tim' : 95 }
print(my_dict['Joel'])... |
5bc6e70e808cc6cf726bdd988ba0e0455221bdce | franktea/acm | /uva.onlinejudge.org/uva 537 - Artificial Intelligence?/537.py | 916 | 3.515625 | 4 |
import re
# 可能会出现负数
r = re.compile(r'(?P<name>([UPI]))=(?P<value>[\-]?[0-9\.]+)(?P<suffix>[mkM]?)')
suffix_values = {None: 1, 'm': 0.001, 'k': 1000, 'M': 1000000}
class Solver:
def __init__(self):
self.P, self.U, self.I = None, None, None
def Calc(self):
if self.P is None:
p... |
6a079fe56b745a6860eebc00d5d25909c172cb31 | franktea/acm | /uva.onlinejudge.org/uva 644 - Immediate Decodability/644.py | 897 | 3.5 | 4 |
def solve(lines):
lines.sort()
for i in range(len(lines)-1):
for j in range(i+1, len(lines)):
if lines[j].startswith(lines[i]):
return False
return True
if __name__ == '__main__':
try:
case_count = 0
while True:
lines = []
cas... |
40c4085f0b21fa3499ee8e5c21e5f314ecba12d4 | peixingtao01/dataanalysis | /第四天pands/02df属性.py | 883 | 3.890625 | 4 | import pandas as pd
# 创建一个df,这个不叫数组,这个叫表
#
df = pd.DataFrame({
'col1':[0,1,2],
'col2':['zs','ls','ww'],
'col3':[3.14,2.71,1.72]
},
index=['一','二','三']
)
# 用dataframe生成的东西不是数组,是增加了很多零碎的表
print(df)
# 查看dataframe 属性
print("df 的values:\n",df.values) # 获取df的数组
print("df 的values的类型:\n",type(df.value... |
fe5f4390ffbdef6fc5e4b66d62055f8fcdd8b35c | MingkaiMa/Algorithm-Programming | /Eight_Queens_All_Solu.py | 986 | 3.5 | 4 | N = 8
k = 1
def printSolution(board):
global k
print(k)
k += 1
for i in range(N):
for j in range(N):
print(board[i][j], end= ', ')
print()
def isSafe(board, row, col):
for i in range(col):
if(board[row][i]):
return False
i = row
... |
bdde72019a02d69961fefa000c89abd13fb7c8ac | gilbertoalexsantos/judgesolutions | /Solved/CodeF/@CodeF 501 - A. Contest/501 - A. Contest.py | 368 | 3.625 | 4 | #Author: Gilberto A. dos Santos
#Website: http://codeforces.com/contest/501/problem/A
def getTime(points, time):
p1 = (3 * points) / 10
p2 = points - (points / 250) * time
return max(p1, p2)
a, b, c, d = map(int, raw_input("").split(" "))
misha = getTime(a, c)
vasya = getTime(b, d)
if misha == vasya: pr... |
61aa7d3f733a4b42a20697cb224a8a8d5807b961 | adrianalejandro/teamMonitoring | /MemberModule.py | 1,546 | 3.5625 | 4 | import datetime
class Member:
def __init__(self):
self.memberId = ""
self.firstName = ""
self.surname = ""
self.birthday = ""
self.age = 0
self.presentAddress = ""
self.permanentAddress = ""
self.mobileNumber_1 = ""
self.mobileNumber_2 = ""
self.facebookAddress = ""
self.cellLeader = ""
self.i... |
c416ed17fadc79676e12ac10cfc4023c5f2e611e | Nirkan/Computer-Vision-Python | /OpenCV-T2/chap4.py | 610 | 3.65625 | 4 | import cv2
import numpy as np
img = np.zeros((512, 512, 3), np.uint8)
print(img.shape)
# coloring the parts of image
img[:] = 255, 0, 0
img[100:200, 150:250] = 100,20,0
# Drawing a line
# In openCV height and width have different positons
cv2.line(img, (0,0), (img.shape[1],img.shape[0]), (0,200,0), 5)
# Drawin... |
eb233c02094577e704560663814fdb8be75788c6 | sfidahussain/aliceIsGone | /aliceIsGone.py | 2,293 | 3.828125 | 4 | import sqlite3
con = sqlite3.connect('pcfb.sqlite')
## Creating the tables
##con.execute("create table people (id integer primary key, name varchar, position varchar, phone varchar, office varchar);")
##con.execute("create table experiment ( id integer primary key, name varchar, researcher integer, description text, ... |
2467f02012ea84dbaf72ba0566aedb992326aeb9 | SamuelEllertson/StatsCourseBot | /datastore.py | 10,710 | 3.578125 | 4 |
import json
import pymysql.cursors
import pymysql.connections
import warnings
from typing import Set, List
'''Provides high level access methods to data stored in the database
All SQL queries should be aggregated here, abstracting that logic away from other parts of the code.
creates a connection to the database ba... |
4f0352b687f57afb0a27c8dfcc1f1718add2ca92 | Havacore/adventOfCode2016 | /day4/solution2.py | 726 | 3.65625 | 4 | from solution import split_room
file = open('input.txt', 'r')
input = file.read()
rooms = input.split('\n')
test_input = """qzmt-zixmtkozy-ivhz-343[abcdef]"""
rooms = input.split('\n')
def decrypt(room_number, sector):
decrypted_string = ""
for letter in room_number:
if letter == "-":
decrypted_string += " "... |
03d6eed1a3ca5ddef2648a5a769879785489ebf8 | felipolis/SortingHat | /lib/questions.py | 20,042 | 4.0625 | 4 | from random import randint
def question(choices):
while True:
choice = str(input(">>>>> ")).strip().upper()[0]
if choice in choices:
return choice
print("[WARNING] You should chose a defined option!!!")
def first_question():
num = randint(1, 3)
if num == 1:
... |
ea028f047807736b8e6bed1a6e437a9d37edb194 | transelvania/repo-github | /lesson_03/3.2.py | 445 | 3.84375 | 4 | def user_info():
name = (input("Введите имя"))
surname = (input("Введите фамилию"))
birth_year = int(input("Введите год рождения"))
city = (input("Введите город проживания"))
email = (input("Введите email"))
phone = (input("Введите номер телефона"))
return [name, surname, birth_year, city, e... |
438d524b0753f52092842c6cddb326d95c19a47e | rahulpatil5202/python_practice | /files_3_append.py | 242 | 3.578125 | 4 | f = open("D:\\test1.txt","a") # a signifies that file is opened for appending
f.write("This line is being appended to exsting content")
f.write("\nthis will be added to new line")
f.close()
f = open("D:\\test1.txt","r")
f.seek(0,0)
f.read() |
1ee917afad6d090089cb5b12f8647443aa6d5ab7 | rahulpatil5202/python_practice | /files_1_read_file.py | 581 | 3.71875 | 4 | file1 = open("D:\\test1.txt","r")
## "r" signifies that file is opened in read only mode
file1.read()
## Now let's try reading it again
file1.read()
# above command return empty string because our earlier read() function scaned file and moved cursor to end of file
# and hence getting blank result
# we can reset cursor ... |
4b1da823a8e13b252edbab94c3b27df70c129d18 | yagomotti/algoritmosordenacao | /insertionSort.py | 696 | 3.78125 | 4 | import random #importa lib de misturar vetor
import time #importa lib do tempo
def sort (array):#funcao de ordenacao
for p in range(0, len(array)):
current_element = array[p] #guarda o elemento atual do array
while p > 0 and array[p-1] > current_element: # enquanto o elemento for de tras fo... |
297078e611af245376e5888ccf5132fb7f8ecab4 | llwf/python-project | /pillow_test.py | 563 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PIL import Image, ImageFilter
# 打开一个png图像文件,注意是当前路径:
im = Image.open('file/mat_depth.png')
# 获得图像尺寸:
w, h = im.size
print('Original image size: %sx%s' % (w, h))
# 缩放到50%:
im.thumbnail((w/2, h/2))
print('Resize image to: %sx%s' % (w/2, h/2))
# 把缩放后的图像用png格式保存:
im.sav... |
765031220538a7121db61f8afacefaa28ae94d18 | llwf/python-project | /closure_test.py | 577 | 3.828125 | 4 | #!/usr/bin/env pyhont3
# -*- coding: utf-8 -*-
def createCounter():
count = 0
def counter():
nonlocal count
count = count + 1
return count
return counter
# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), ... |
5fe884067f7af8df12f114e84a40953cab414d6e | abby-does-code/youtube_practice_intmd | /dictionaries!!.py | 2,766 | 4.3125 | 4 | # START
## Keep chugging away bb!
# Dictionary: data type that is unordered and mutable
##Consists of key:value pairs; maps value to associated pair
# Create a dictionary(30:00)
mydict = {"name": "Max", "age": 28, "city": "New York"}
print(mydict)
# Dict method for creation
# mydict2 = dict(name = "Mary", age = 27, ... |
f94dc01f4eff4eabf56cd3d05dfa8fd3b1c179fd | Bryson14/Numerical_Methods | /src/assn6/problem4.py | 2,111 | 3.8125 | 4 | import numpy as np
import matplotlib.pyplot as plt
'''
y_x+1 = y_x + h * f(t_x, y_x)
'''
def euler(var1, var2, step):
current = var2
variables_1 = [current]
times = [0]
variables_2 = [var1]
index = 0
while current > 0: # hasn't hit the ground yet
if index % (1/step) == 0:
p... |
2382d11e2afae970ac1203727bb7f58823301c7e | Bryson14/Numerical_Methods | /src/assn6/problem5.py | 3,299 | 3.96875 | 4 | import numpy as np
import matplotlib.pyplot as plt
'''
y_x+1 = y_x + h * f(t_x, y_x)
'''
def euler(initial_v, initial_y, step, end):
curr_y = initial_y
positions = [curr_y]
times = np.arange(0, end + step, step)
velocities = [initial_v]
for index in range(len(times)):
velocities.append(velo... |
2b15a210cb553b80453612c2e8f019384c6c0477 | cmestradap/Asesorias | /busqsecuencial.py | 977 | 3.921875 | 4 | #BUSQUEDA SECUENCIAL
def busqueda_lineal(lista, elementobuscado):
""" Búsqueda lineal.
Si x está en lista devuelve su posición en lista, de lo
contrario devuelve -1.
"""
# Estrategia: se recorren uno a uno los elementos de la lista
# y se los compara con el valor x buscado.
i=0 ... |
7895d71a12dca25e0817c9504cfbb433a725d3f6 | prasobh606/pythonNew | /some_games/just_pong.py | 2,808 | 3.8125 | 4 | """import turtle as t
window = t.Screen();
window.bgcolor("green")
window.setup(width=800,height=600)
window.tracer(825)
window.mainloop()"""
from turtle import *
import turtle as t
window = t.Screen()
window.bgcolor("green")
window.setup(width=800, height=600)
window.tracer(0)
left_border = -390
right_border = 390
t... |
9f6428346651b58e0cf9dff340b78d03fcc35371 | BrunaAdmComp/alguns-exercicios-python | /Produto_Multiplicação.py | 121 | 3.6875 | 4 | n = int(input('Digite um valor: '))
print('O dobro é: {}'.format(n*2))
print('A raiz quadrada é:{}'.format(n**(1/2))) |
a6e6b869f5de7d169dc668b4967332bea5498ae1 | shanbumin/py-hundred | /Day01-15/Day12/demo01/main.py | 1,103 | 4.4375 | 4 | # 字符串常用操作
print('My brother\'s name is \'007\'') # 转义字符
print(r'My brother\'s name is \'007\'') # 原始字符串
# -------------------------------------------------------
str = 'hello123world'
print('he' in str) #True
print('her' in str) #False
print(str.isalpha()) # 字符串是否只包含字母 False
print(str.isalnum()) # 字符串是否只包含字母和数字 True... |
18f75cc839f336f3a2f815a578eb5871ad2a7f5c | pranabsg/python-dsa | /get_fibonacci.py | 381 | 4.28125 | 4 | """Implement a function recursively to get the desired
Fibonacci sequence value.
"""
def get_fib(position: int) -> int:
if position == 0 or position == 1:
return position
return get_fib(position - 1) + get_fib(position - 2)
def main():
# Test cases
print(get_fib(2))
print(get_fib(11))
... |
df11ec5f0d6e371df3c128f8ba0304f5de2414d3 | brfarlow/advent_of_code_2017 | /day9/day9-part2.py | 529 | 3.703125 | 4 | input = open('input.txt').read()
score = 0
garbage = 0
depth = 0
in_garbage = False
skip = False
for char in input:
if in_garbage:
if skip:
skip = False
elif char == "!":
skip = True
elif char == ">":
in_garbage = False
else:
garbage +... |
dd3903d3658309b6b056deda9db6f3b54885a27d | brfarlow/advent_of_code_2017 | /day3/day3-part1.py | 1,031 | 3.59375 | 4 | # Calculate the nearest odd perfect square n2 from your input
# and you have a number that is n-1 Manhattan distance away
# from the center (the bottom right corner).
# Then count the distance from your input.
puzzle_input = 277678
closest_square_root = int(puzzle_input ** 0.5)
if closest_square_root % 2 == 0:
siz... |
f2d630cc30977519e5ee7b098c120e2623a52d9a | hossam692/PyPro | /tictoe.py | 2,025 | 4.0625 | 4 |
def display_board(board):
print(" | | ")
print(f" {board[7]} | {board[8]} | {board[9]} ")
print(" | | ")
print("-----------------")
print(" | | ")
print(f" {board[4]} | {board[5]} | {board[6]} ")
print(" | | ")
print("-----------------")
pri... |
2c1f05500f1eadaed3a3333da1bafe166e3ea265 | DSchana/Misc | /PyTorch/tutorial/vector-jacobian.py | 388 | 3.6875 | 4 | import torch
x = torch.randn(3, requires_grad=True)
y = x * 2
while y.data.norm() < 1000:
y *= 2
print(y)
# NOTE: y is not a scalar; torch.autograd could not computer the full jacobian directly. If we we just want the vector-jacobian product, simply pass the vector to .backward as an argument
v = torch.tensor(... |
888d24aaca64f8d3b18c8acf5248c512285f8656 | tianer2820/Subtitles-for-Images | /src/generate_text_file.py | 3,668 | 3.703125 | 4 | """
根据文件夹内的图片自动生成台词文件的分页符
"""
import typing
from typing import List, Tuple
import os
import re
def is_split_page(line: str) -> bool:
line = line.strip('\n ')
if line.startswith('---') and line.endswith('---'):
return True
return False
if __name__ == "__main__":
from settings_loader import lo... |
f78a79c275e90a90394269b230cdef39dbc4d979 | danecashion/python_example_programs | /first_largest.py | 284 | 4.5625 | 5 | """
Python program to find the largest element and its location.
"""
def largest_element(a):
""" Return the largest element of a sequence a.
"""
return None
if __name__ == "__main__":
a = [1,2,3,2,1]
print("Largest element is {:}".format(largest_element(a)))
|
554642e3a17ce8e689c4a12ac85311d6fb497cce | Dhanunjaya2000/DSP | /operations on numbers.py | 1,176 | 3.8125 | 4 | ##program to perform some arithemetic operations on numbers##
import numpy as np
a=5
b=10
c=5.6
d=-9
e=0.45
print("the predefined numbers are",a,b,c,d,e)
print("1.addition=",a+b)
print("2.substraction=",a-b)
print("3.multiplication=",a*b)
print("4.division=",b/a)
print("5.modulus or integer remainder=",b%a)
print("6.po... |
97b70220c4852e252ab4a51429e1c839a2d2a101 | bfurner27/CS306AlgorithmsCollaboration | /merge.py | 501 | 3.578125 | 4 | import sys;
import time;
items = []
from heapq import merge
def merge_sort(m):
if len(m) <= 1:
return m
middle = len(m) // 2
left = m[:middle]
right = m[middle:]
left = merge_sort(left)
right = merge_sort(right)
return list(merge(left, right))
with open(sys.argv[1], 'r') as f... |
9ee5a2273a14483a1ecef223fa63ff63b0a7aadc | m-yuhas/pysigdig | /test/test_pysigdig.py | 16,693 | 3.640625 | 4 | """Unit test cases for the _pysigdig module."""
import unittest
import pysigdig
class TestConstructor(unittest.TestCase):
"""Test the constructor for Number class."""
def test_integer(self) -> None:
"""Test constructor when an integer is provided as value."""
number = pysigdig.Number(1)
... |
470f625827b09d0fbfca68d27d28fe574759591c | Jackson-Le/290I-IMP | /folder/tree.py | 1,385 | 3.765625 | 4 | #Printing the nodal tree for problem 2:
class tree:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def get_level(self):
level = 0
p = self.parent
while p:
level += 1
p = p.parent
return level
... |
1323f15d87befa1e03f457d413d33f8cf38f5253 | saishibu/Smartgrids | /Algo/voltagecheck.py | 1,111 | 3.859375 | 4 | #Algorithm for Voltage error check
#Code by Nikhitha
#voltage error considered as 'low priority' error. LED gives warning in case of any errors
#This program also gives alarm in case of critical condition
#this algorithm can be implemented in both Load meter and Grid meter main programs
#voltage error checked in the pr... |
e7c7c3df91a427918cb4007708c33e0588a262f9 | ykzzyk/Networking | /P1/MultithreadServer/Class/tcp.py | 2,539 | 3.75 | 4 | from socket import *
class TCP():
def __init__(self, ip, port, bfsz):
self.ip = ip
self.port = port
self.bfsz = bfsz
def tcp_server(self):
# Prepare a server socket
serverSocket = socket(AF_INET, SOCK_STREAM)
# Bind IP address and port
serverSoc... |
9c519052b0517ab15c895b4243d9fe68b1e3a2ce | ykzzyk/Networking | /P1/MultithreadServer/Method_1/server.py | 2,108 | 3.59375 | 4 | from socket import *
import threading
def tcp_server(TCP_IP, TCP_PORT, BUFFER_SIZE):
# Prepare a server socket
serverSocket = socket(AF_INET, SOCK_STREAM)
try:
# Bind TCP_IP address and TCP_PORT
serverSocket.bind((TCP_IP, TCP_PORT))
except Exception:
print("\n")
threa... |
ba9c31ebc3df8d7c0379d0face66c3e4dfecd9e1 | deepdc19/Practice_Problems | /piToNth_chudnovsky.py | 1,006 | 4.1875 | 4 | from decimal import Decimal
from decimal import getcontext
def factorial(n):
'''
Factorial function to find the factorial of the functions
https://en.wikipedia.org/wiki/Factorial
'''
if n < 1:
return 1
else:
return n * factorial(n-1)
def piToNth(num):
'''
chudnovs... |
6641254f4f84f29c38a744c85d9ab16c35c87bf8 | AchintyaX/Twitter_Data_Retrieval | /tweet_retrieve.py | 3,239 | 3.71875 | 4 | # importing tweepy used to connect twitter with python
import tweepy
import sys # to take arguments from the terminal
# setting up the api keys for the twitter api
consumer_key = ''
consumer_secret = ''
access_token = ''
access_secret = ''
# handling the authentication process of the twitter api
auth = tweepy.O... |
9e281e072c7da292fc16de4928efa8362c5e7b6e | JiaoZexin/PyDemo | /kaike/first/3Demo1.py | 789 | 3.6875 | 4 | height = 0;
while height < 170:
height = int(input('继续输入身高:'))
print('已经找到人去搬水了~')
print('''课外题一:for 循环能确定循环次数while 不能确定循环次数 需要有跳出while循环的条件 break等''')
print('课外题二')
sum1 = 0;
for i in range(1, 101):
sum1 += i;
print('使用for循环打印1-100之间的和:', sum1)
sum2 = 0;
i = 1;
while i < 101:
sum2 += i;
i+=1;
print(... |
2db9b430724ef4ab6bb423dc19807d319fab8a96 | JiaoZexin/PyDemo | /kaike/three/15/Demo1.py | 1,220 | 3.5 | 4 | import pandas as pd
data = pd.read_csv('../../data/analyse_spider.csv',encoding='GBK')
data.head()
# 删除businessZones列数据
data.drop(['businessZones'],axis=1, inplace=True)
data.dropna(inplace=True)
# 计算重复的数据数
print(len(data.duplicated()[data.duplicated()==True]))
# 删除重复数据
data.drop_duplicates(inplace=True)
data.info()
... |
31a54a5a10a3e4e7ffb601efc8468335ef03cbcd | JiaoZexin/PyDemo | /kaike/first/7/Demo1.py | 1,034 | 3.96875 | 4 | # 题目要求
# 现在KFC餐厅的奖金激励政策变了,变成如下:
# 1.工作时间<1年的,发放1000元
# 2.工作年限≥1年但<3年的,发放奖金3000*年数(年数四舍五入,输入时只输入整数)如1年半为 3000*2 = 6000
# 3.工作年限≥3年的,发放奖金5000*年数(年数四舍五入,输入时只输入整数) 如3年为 5000*3 = 15000
# 题目讲解
# 定义两个函数第一个函数功能为根据工作年数返回奖金额,第二个函数功能为打印出'XX员工来了X年,获得奖金XXX元'。
# 比如输入姓名 ‘老王’,年限‘3’;就会打印出“老王来了3年,获得奖金15000元”。
name = input('请输入姓名:')
yea... |
1069fd6ef89aef3702c092711f206f6d42276077 | JiaoZexin/PyDemo | /python/Student.py | 772 | 3.78125 | 4 | class Student(object):
telname="学生名称";
def __init__(self,name,age):
self.name=name
self.age=age
def print_score(self):
print('%s: %s' % (self.name, self.age))
def get_grade(self):
if self.age >= 90:
return 'A'
elif self.age >= 60:
retur... |
5e510e2496a4f086835e6967bb73a8bb594d8c44 | JiaoZexin/PyDemo | /kaike/first/9/Demo1.py | 169 | 4.03125 | 4 | #请你找出一下代码的错误 并修改使其正常运行
age=int(input('请输入数字'));
if age==10:
print('小明今年%d岁了'%age)
print('程序结束') |
5117af620e663d26d31f62fe742718e6ba486706 | JiaoZexin/PyDemo | /kaike/three/1/Demo2.py | 1,488 | 3.78125 | 4 | from pandas import Series,DataFrame
import pandas as pd
# 使用字典创建
dic={
'姓名': ['小罗伯特·唐尼', '克里斯·埃文斯', '斯嘉丽·约翰逊', '克里斯·海姆斯沃斯'],
'饰演': ['钢铁侠', '美国队长', '黑寡妇', '雷神'],
'武器': ['钢铁战衣', '盾牌', '寡妇蜇', '雷神之锤'],
'语录': ['和平,我热爱和平','最好的选择就是重新开始 ','嘿,大兄弟,太阳下山了','要用知识来打败无知']}
df=DataFrame(dic)
print(df)
from pandas impo... |
0c961a963a420b30fc1c0a19b559e6066c0ef92f | JiaoZexin/PyDemo | /kaike/three/6/Demo2.py | 400 | 3.875 | 4 | import pandas as pd
df = pd.read_excel('../../data/forbes_2018.xlsx')
print()
groups = df.groupby('gender')
for group_name,group_df in groups:
print(group_name,group_df.shape)
f_mean = group_df['age'].mean()
f_max = group_df['age'].max()
f_min = group_df['age'].min()
print('{}组的最大年龄是{},最小年龄是{},平均年龄是... |
a28440750a6cec888db51507a7143f57514438ca | JiaoZexin/PyDemo | /kaike/first/8/Demo4.py | 524 | 3.5625 | 4 | #2:已知某运输公司规定运输价格 5KG一下20元,5KG以上每运输1KG货物另收2元(不足一公斤按一公斤计算) 设计一个函数 实现输入货物重量 计算出运送这批货物的需要的价格
import math
def calculate(kg):
sum=0;
if kg<=5:
sum=20;
else:
kg=math.ceil((kg-5))
sum=math.ceil(kg*2+20);
print('运送这批货物的需要的价格为:%d元'%sum)
while True:
kg = math.ceil(float(input('实现输入货物重量:... |
4086c632e62c92e0fd86a19a0ae25350a8769846 | JiaoZexin/PyDemo | /kaike/first/14/Demo2.py | 493 | 3.59375 | 4 | # 题目要求
# 使用Python中的csv模块, 在csv文件中写九宫格
# 题目讲解
# 回顾总结本节课csv的使用方法, 然后通过Python在test.csv文件中写入如下九宫格, 补全practice_csv.py中的代码:
# 书写代码
import csv
#from kkb_tools import open_file
with open("mytest.csv",'a') as r:
writer=csv.writer(r)
writer.writerow([41,42,43])
writer.writerow([51,52,53])
writer.writerow([61,62... |
07fdf4ea8aafe8d19afe9c032ceb7c3dcb969020 | JiaoZexin/PyDemo | /kaike/first/14Demo1.py | 884 | 3.8125 | 4 | import time; # 引入time模块
ticks = time.time() # 时间戳 每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。
print("当前时间戳为:", ticks)
localtime = time.localtime(time.time()) # 本地时间 从返回浮点数的时间戳方式向时间元组转换,只要将浮点数传递给如localtime之类的函数。
print("本地时间为 :", localtime)
localtime = time.asctime(time.localtime(time.time())) # 根据需求选取时间格式
print("本地时间为... |
35ce561305c24c2bbfc6ec4d7319f0717220508e | alex2835/stuff | /dataBase/lib/dbController.py | 5,939 | 3.671875 | 4 | class DataBase:
def __init__(self, connection):
self.connection = connection
self.cursor = connection.cursor()
def create_tables(self):
# create book table
self.cursor.execute(
"CREATE TABLE IF NOT EXISTS books("
"id INTEGER PRIMARY KEY AUTOINCREMENT NOT... |
457810c6f6da46a66f2e1c3c97c350c13b2ff4ce | altynbek01/Labs | /InputOutput/B.py | 162 | 3.84375 | 4 | a=int(input())
b='The next number for the number {} is {}.'
c='The previous number for the number {} is {}.'
print(b.format(a, a+1))
print(c.format(a, a-1)) |
c28a5d57768c455789b63cdc63bf6cd0de225d98 | altynbek01/Labs | /functions/D.py | 256 | 3.5 | 4 | def election( x,y,z):
a=[]
a.append(x)
a.append(y)
a.append(z)
zero= a.count(0)
one=a.count(1)
if zero>one:
return 0
else:
return 1
print(election(int(input()), int(input()), int(input()))) |
5b2a16675a829ac6344fffe32cf0121238da9348 | AlecFaye/Coding-Practice | /August 2020/August 5/TheGrandAdventure.py | 775 | 3.6875 | 4 | cases = int(input())
encounter = {
"b": "$",
"j": "*",
"t": "|"
}
objects = ["$", "*", "|"]
for test in range(cases):
backpack = []
complete_adventure = True
adventure = input()
for event in adventure:
if event in objects:
backpack.append(event)
elif event in... |
303ac31c9701007de6e1d0a5b2dec42c9518853b | AlecFaye/Coding-Practice | /August 2020/August 10/PolygonArea.py | 1,631 | 3.515625 | 4 | def calculate_order(_vertices):
clockwise_count = 0
counterclockwise_count = 0
for i in range(len(_vertices)):
a_index = i
b_index = (i + 1) % len(_vertices)
c_index = (i + 2) % len(_vertices)
a_point = _vertices[a_index]
b_point = _vertices[b_index]
c_point... |
7d78cf93685ee70fa889adf36b747806c11e6d29 | AlecFaye/Coding-Practice | /December 2020/December 07/Homework.py | 188 | 3.53125 | 4 | questions = input().split(";")
total = 0
for x in questions:
x = x.split("-")
if len(x) > 1:
total += int(x[1]) - int(x[0]) + 1
else:
total += 1
print(total)
|
d186838db4a31d24c6aec874ca648dba49a8bd1d | AlecFaye/Coding-Practice | /August 2020/August 6/Cetvrta.py | 565 | 3.796875 | 4 | x_coordinates = {}
y_coordinates = {}
for count in range(3):
point = input().split()
if point[0] not in x_coordinates:
x_coordinates[point[0]] = 1
else:
x_coordinates[point[0]] += 1
if point[1] not in y_coordinates:
y_coordinates[point[1]] = 1
else:
y_coordinates[p... |
184aeb20e16399de484a1ee9447f2d4f9d2cc12b | AlecFaye/Coding-Practice | /August 2020/August 26/AlphabetSpam.py | 475 | 4.09375 | 4 | phrase = input()
phrase = [char for char in phrase]
whitespace = 0
lowercase = 0
uppercase = 0
symbols = 0
for letter in phrase:
if 65 <= ord(letter) <= 90:
uppercase += 1
elif 97 <= ord(letter) <= 122:
lowercase += 1
elif letter == "_":
whitespace += 1
else:
symbols +=... |
0a821d4f96ed4083f8c245e930d167f015e61f8e | AlecFaye/Coding-Practice | /August 2020/August 7/Ladder.py | 178 | 3.703125 | 4 | import math
height_angle = input().split()
height = int(height_angle[0])
angle = int(height_angle[1])
angle = angle * math.pi / 180
print(math.ceil(height / math.sin(angle)))
|
94b19df7e82ed7e806202fa6b67724cb7f8cd4d6 | AlecFaye/Coding-Practice | /August 2020/August 3/Modulo.py | 211 | 3.5625 | 4 | modulo_count = []
for case in range(10):
number = int(input())
remainder = divmod(number, 42)[1]
if remainder not in modulo_count:
modulo_count.append(remainder)
print(len(modulo_count))
|
33e67b13dcc68f698b78633f0f7cf06492ee28c3 | AlecFaye/Coding-Practice | /August 2020/August 3/Spavanac.py | 386 | 3.828125 | 4 | time = input()
time_hour = int(time.split()[0])
time_minute = int(time.split()[1])
alarm_hour = 0
alarm_minute = 0
if time_minute < 45:
if time_hour > 0:
alarm_hour = time_hour - 1
else:
alarm_hour = 23
alarm_minute = time_minute + 15
else:
alarm_hour = time_hour
alarm_minute = t... |
b85655b4fcfe6be3b1abe93b6ec9601b4aeea6f1 | AlecFaye/Coding-Practice | /August 2020/August 3/Autori.py | 114 | 4 | 4 | name = input()
autori = ""
for letter in name:
if letter.isupper():
autori += letter
print(autori)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.