blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2c3cfe40d5c428e356576f0622ee1f332fa43489 | roque-brito/ICC-USP-Coursera | /icc_pt2/week2/exercicio_1.py | 3,114 | 4.25 | 4 | # Escreva uma função que recebe um array de strings como parâmetro e devolve o primeiro string na ordem lexicográfica, ignorando-se
# letras maiúsculas e minúsculas.
# *** lexicografia compara código Unicode
# ==============================================================================================================... |
c19d4de995359bbdc5c2edba24e2c32de5ecf032 | roque-brito/ICC-USP-Coursera | /icc_pt1/desafios/problem_coh_piah/testes_por_partes.py | 2,056 | 3.671875 | 4 | import re
texto = 'Então resolveu ir brincar com a Máquina pra ser também imperador dos filhos da mandioca. Mas as três cunhas deram muitas risadas e falaram que isso de deuses era gorda mentira antiga, que não tinha deus não e que com a máquina ninguém não brinca porque ela mata. A máquina não era deus não, nem possu... |
ab72ef4d4c906574acca083ef868c9f19b00dd54 | roque-brito/ICC-USP-Coursera | /icc_pt1/Arrays/gerador_numeros_primos.py | 415 | 3.765625 | 4 | # -------------------------
# GERADOR DE NÚMEROS PRIMOS
# -------------------------
def éPrimo(x):
fat = 2
if x == 2:
return True
while ((x % fat != 0) and (fat <= x/2)):
fat += 1
if x % fat == 0:
return False
else:
return True
lim = int(input('Limite... |
b6914b6ca79865f5eff7883b82a762515c4cb7a4 | roque-brito/ICC-USP-Coursera | /icc_pt2/week3/poo/exemplo_aplicado_metodo_init.py | 1,033 | 3.75 | 4 | def main():
carro1 = Carro('brasília', 1969, 'amarela', 80)
carro2 = Carro('fuscão', 1981, 'preto', 95)
carro1.acelere(40)
carro2.acelere(50)
carro1.acelere(80)
carro1.pare()
carro2.acelere(110)
class Carro:
def __init__(self, m, a, c, vm):
self.modelo = m
self.ano =... |
5761bfe0a7a77d6f9aa0c92827b7baa247ef862d | davyjang1/python-practice | /web/cgi-bin/friendsA.py | 433 | 3.5625 | 4 | #!/usr/bin/env python3
import cgi
import os
reshtml = '''Content-Type: text/html\n
<HTML><HEAD><TITLE>
Friends CGI demo (dynamic screen)
</TITLE></HEAD>
<BODY><H3>Friends list for: <I>%s</I></H3>
Your name is: <B>%s</B><P>
you have <B>%s</B> friends.
</BODY></HTML>'''
form = cgi.FieldStorage()
who = form['person'].va... |
3670f5f58e8b0d213300617fa2871df16d78c851 | lorderikstark0/leetcode | /p507.py | 553 | 3.53125 | 4 | '''perfect number is a +ve number
that is equal to the sum of all its +ve divisors except itself
'''
'''this will give tle --> writing the main solution in cpp
'''
def getDivisors(num):
i=1
li1=[]
while i<num:
if(num%i==0):
li1.append(i)
i=i+1
return li1
def checkPerfect(num:int)->bool:
if(num<0):
retu... |
9597bb4772c13a0c854ce382e460f505e7f443aa | lorderikstark0/leetcode | /p1295.py | 345 | 3.59375 | 4 | def findNumber(nums):
count_list=0
for i in nums:
count=0
while(nums[i] >0):
i=i//10
count+=1
if(count%2==0):
count_list+=1
return count_list
n=int(input('>'))
list_1=[]
while(n>0):
for i in range(n):
list_1.append(i)
n=n-1
print(... |
ab22acf0cea24bf419ee9b2bc03602f4ce2e8971 | lorderikstark0/leetcode | /p35.py | 672 | 4.03125 | 4 | class Solution:
def searchInsert(self,nums:List[int], target:int ) ->int:
for i in range(len(nums)):
if(nums[i]==target): ## the target is found
return i
else:
if(i==0 and target<nums[i]):##when element has to be inserted at index 0
... |
26aa29d1ee36e19b8138f03e0a5b4e4df5ddfa40 | Mehedi-Hasan-NSL/Python | /extra_long_factorial.py | 1,130 | 3.9375 | 4 | #!/bin/python3
import sys
#
# Complete the 'extraLongFactorials' function below.
#
# The function accepts INTEGER n as parameter.
#
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 8 18:02:50 2021
@author: DELL
"""
def factorial( n) :
res = [0]*1000
res[0] = 1
res_size = 1
... |
d9be0d047ffd5a0664d47e49e8fe96f0d6c20823 | Mehedi-Hasan-NSL/Python | /fibonacci_hr.py | 977 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 8 17:06:09 2021
@author: DELL
"""
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'fibonacciModified' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parame... |
c5fd12eb5bf94daedbcda6a17a34c4a56ff4d64e | Mehedi-Hasan-NSL/Python | /compress string.py | 334 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 28 16:32:27 2021
@author: DELL
"""
a = [1, 2, 3, 4, 5]
print(a)
print(x for x in a)
from itertools import groupby
ans = []
for k,c in groupby(input()):
ans.append((len(list(c)), int(k)))
#print(*[(len(list(c)), int(k)) for k, c in groupby(input())])
... |
b5be38f4f05385fee271b140763fec077dba9891 | Mehedi-Hasan-NSL/Python | /magic_square.py | 1,277 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 8 19:09:40 2021
@author: DELL
"""
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'formingMagicSquare' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_AR... |
d706608eb4690eeb96bf9aa2a71b247a392362f0 | Mehedi-Hasan-NSL/Python | /triangle_quest2.py | 283 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 24 17:11:04 2021
@author: DELL
"""
for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also
print (((10**(i-1)+(10**(i-1)//9))**2)) |
1b6b7a309cd3f6ba947f2586152c8297237d11f4 | Mehedi-Hasan-NSL/Python | /triangle_quest.py | 243 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 21 12:03:41 2021
@author: DELL
"""
for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also
print(i*(10**(i-1)) + (i*(10**(i-1)))//9)
|
c987715cb3ec64897b4c5779cb2ec4eeb9ca9055 | natanascimento/LaboratorioProgramacao | /LabProg/ME_1UN/me_lab.py | 3,696 | 3.578125 | 4 | import pickle
dados_funcionario = "funcionario.pickle"
dados_setor = "setor.pickle"
dados_salario = "salario.pickle"
def cadastro_funcionario():
matricula = int(input('Matricula do funcionário: '))
nome = str(input('Nome do funcionário: '))
email = str(input('Email do funcionário: '))
telefone = int(input('Te... |
51fe7b41819c567a3814c24263a5b6e47131d5e8 | AlexandrKhabarov/csc_python | /5 lection/tuple.py | 658 | 4.21875 | 4 | person = ('George', "Carlin", "May", 12, 1937)
LAST_NAME = 1
BIRTHDAY = slice(2, None)
print(f"Last name: {person[LAST_NAME]}")
print(f"Birthday: {person[BIRTHDAY]}")
# Part 2
from collections import namedtuple
Person = namedtuple('Person', ['first_name', 'last_name', 'age'])
p = Person('Terrence', 'Gilliam', 7... |
ae01867480854336d3cb2b1029cf1891cbf31c62 | ikostia/glyphs | /reader.py | 599 | 3.640625 | 4 | """
Authors: Nastia Merlits, Kostia Balitsky
"""
import itertools
import structures
class ImpoperInputFormat(Exception):
pass
def from_tripples(input, orientation):
glyph = structures.Glyph(orientation)
nums = [long(item) for item in input.split()]
tripples = [ nums[i:i+3]
for i i... |
5e67f8652c19d0aecb915bbc4d5e2b7980c1e142 | luise7932/hyuk | /CS/test7.py | 138 | 3.84375 | 4 | test_list = ['one','two','three']
for i in test_list:
print(i)
a = [(1,2),(3,4),(5,6)]
for (first,last) in a:
print(first+last)
|
c8b7f213acde7b42ee6a2e85b66dffe3a393b929 | luise7932/hyuk | /CS/Question/Q6.py | 96 | 3.703125 | 4 | number = [1, 2, 3, 4, 5]
result = []
result = [n*2 for n in number if n % 2 == 1]
print(result)
|
5f6f9dc277bf0ab9e62cafec1fdd10211ca49cb3 | luise7932/hyuk | /data type/Question/Q10.py | 146 | 3.578125 | 4 | a = {'A':90, 'B':80, 'C':70}
print(list(a.keys()).pop(1)) #키 목록을 리스트로 뽑아낸 다음 pop함수로 2번째 키인 B를 꺼낸다. |
f844bf8cfba67876daa32943edb759ee2f515fa2 | luise7932/hyuk | /Class/test2.py | 362 | 3.703125 | 4 | class Cal: # class Cal 선언.
def __init__(self):
self.result = 0
def add(self, num):
self.result += num
return self.result
def sub(self, num):
self.result -= num
return self.result
cal1 = Cal()
cal2 = Cal()
print(cal1.add(3))
print(cal1.add(4))
... |
edc9fe1f0311b2c7c89d756e7ae8baa91de5d9c1 | luise7932/hyuk | /Class/Library/test.py | 431 | 3.765625 | 4 | """ pickle은 객체의 형태를 그대로 유지하면서 파일에 저장하고 불러올 수 있게하는 모듈이다.
다음은 pickle 모듈의 dump 함수를 사용하여 딕셔너리 객체인 data를 그대로 파일에 저장하는 방법이다. """
import pickle
f = open("test.txt",'wb')
data = {1: 'python',2: 'you need'}
pickle.dump(data,f)
f.close()
f = open("test.txt",'rb')
data = pickle.load(f)
print(data)
|
58a96988ee925d1c65148817e500a3dee2e0216d | kylastyles/Python1000-Practice-Activities | /PR1000_03/PR03_HexReaderWriter.py | 970 | 4.40625 | 4 | #!usr/bin/env python3
# Problem Domain: Integral Conversion
# Mission Summary: Convert String / Integral Formats
user_string = input("Please enter a string to encode in hexadecimal notation: ")
def hex_writer(user_string):
hex_string = ""
if user_string == "":
return None
for char in user_stri... |
855b116b56809de2380624426a2b0efa84cbc328 | ju000n/90AngleSteganography | /Ceria.py | 5,314 | 3.515625 | 4 | from cv2 import cv2
import sys
txt = input("txt = ")
key = input("key = ")
# convert string to binary
bint = [bin(ord(x))[2:].zfill(8) for x in txt]
bins = [bin(ord(x))[2:].zfill(8) for x in key]
# fungsi xor
def prosesXor(texts, knci):
isi = []
for text, kunci in zip(texts, knci):
isi.... |
84ce7ead8f46662a9034b44862db7ded5aecf771 | Ai-kob/Hello-Python | /Titles2.py | 6,528 | 3.640625 | 4 | # Titlesをより良くなるようにやってみる
import os, re
import phonenumbers
import Fileope2
file_open = Fileope2.FileOperation("")
file_open2 = Fileope2.FileOperation2("","")
file_open4 = Fileope2.FileOperation4()
filename = './number_list4.txt'
patternz = '0\d{1,4}-\d{1,4}-\d{3,4}'
#名前と電話番号入力の土台を作成
class NameNum(obj... |
2e8fb160337f084912b9ed384f11891ab01fe63e | AwjTay/Python-book-practice | /ex4.py | 1,207 | 4.25 | 4 | # define the variable cars
cars = 100
# define the variable space_in_a_car
space_in_a_car = 4.0
# define the variable drivers
drivers = 30
# define the variable passengers
passengers = 90
# define the variable cars_not_driven
cars_not_driven = cars - drivers
# define the variable cars_driven as equal to drivers
ca... |
673eda9af0f3803e0b633e665ed9d0317fe7562f | NateSpace/children-s-python | /main.py | 1,237 | 3.71875 | 4 | import turtle, math
s = turtle.Screen()
s.bgcolor("black")
t = turtle.Turtle()
t.shape("turtle")
t.color("#bada55") # can put in web color name, or hex value, or RGB value for color
t.speed(0) # 0 is the fastest speed (no animation), 1-10 are animated speeds with 1 being the slowest and 10 being the fastest
t.pensize(... |
0d44cb8374a584f7a8ffa81dc945be48c523328d | VIGNESH-1346/MyCaptainSubmission | /radius.py | 141 | 4.4375 | 4 | radius=float(input("Input the radius of the circle :"))
print("The area of the circle with radius", radius, "is:", 3.14159*radius*radius)
|
ed5d168d9263f4719534dc8e462e606da196acbd | menghaoshen/python | /03-进制转换,数据类型详解、类型转换、预算符/03.数据类型的转换.py | 594 | 3.96875 | 4 | # 进制转换 将int 类型以不同的形式表现出来
#类型转换 将一个类型的数据转换为其他类型的数据
# int ===》 str str===》 int bool ===》 int int====float
age = input('请输入您的年龄:')
#input 接收的用户输入都是str字符串类型
# python里面字符串和数字做加法运算,会直接报错
# 可以把字符串的变量age 转换成数字类型的age
print(type(age)) #str 字符串
#使用int 内置类可以将其他数据类型转换成整数
new_age = int(age)
print(type(new_age)) #int 数字
print("您... |
c65c2e2db8f5f9ba35dc212f0383f6ef8cda6bef | menghaoshen/python | /09.函数/20.reduce的使用.py | 753 | 3.515625 | 4 | from functools import reduce # 导入模块的语法
# reduce 以前是个个内置的函数
# 内置函数和内置的类都在builtins.py 文件里面,求加法的运算
score = [100, 89, 76, 87]
print(reduce(lambda ele1, ele2: ele1 + ele2, score))
students = [
{'name':'zhansan','age':18,'score':98,'height':180},
{'name':'lisi','age':19,'score':95,'height':185},
{'name':'wan... |
df42005a5b729f1a015c419e314edebbc1f31ff1 | menghaoshen/python | /08.集合的使用/03.集合的练习.py | 89 | 3.625 | 4 | # 去重和排序
nums = [5, 8, 7, 6, 4, 1, 3, 5, 1, 8, 4]
x = list(set(nums))
print(x)
|
d066a6237c19bd258482a1f4233f2da936c41d86 | menghaoshen/python | /09.函数/06.全局变量和局部变量.py | 966 | 4.03125 | 4 | a = 100 # 是全局变量,在py文件里面可以全局访问
world = 'hello'
def test():
x = 'hello' # 这个变量是函数内部定义的变量,它是局部变量,只能在函数内部使用
print('x = {}'.format(x))
# 如果局部变量的名和全部变量同名,函数内部又定义了一个新的局部变量
# 而不是修改全局变量
a = 10
print('函数内部的a = {}'.format(a))
# 函数内部修改全局变量
# 使用global对变量进行声明,可以通过函数修改全局变量的值
global world
... |
aa3587a05b65963d55cfe26f2a42887abc77639d | menghaoshen/python | /12.文件的操作/13.异常使用的场景.py | 480 | 3.796875 | 4 | # age = input('请输入您的年龄')
# if age.isdigit():
# age = float(age)
# if age > 18:
# print('欢迎来到我的网站')
# else:
# print('未满18,请离开')
# else:
# print('输入的不是数字')
age = input('请输入您的年龄')
try:
age = float(age)
except ValueError as e:
print('输入的不是数字')
else:
if age > 18:
print('欢迎... |
fad7ffb3ad42e86b62a67e34e497f53f5cf01660 | menghaoshen/python | /06.列表的使用/14.列表相关一些方法.py | 835 | 4.03125 | 4 | nums = [4, 8, 2, 1, 7, 6]
#列表的sort方法,会对列表进行排序
nums.sort()
print(nums)
# sorted 内置函数,不会改变原有的数据,而是生产一个新的结果
ints = (5,9,1,3,5,8,7,4)
x = sorted(ints)
print(x)
students = [
{'name':'zhansan','age':18,'score':98,'height':180},
{'name':'lisi','age':19,'score':95,'height':185},
{'name':'wanwu','age':18,'score':8... |
af1b1b806a8f6ed557ee39f893d2c4f8ce733d48 | menghaoshen/python | /09.函数/24.闭包的概念.py | 358 | 3.609375 | 4 | def outer():
x = 10 #在外部函数里定义一个变量x,是一个局部变量
def inner():
nonlocal x #这里的x不再是新增的变量,而是外部的局部变量x
y = x +1
x = 20 # 不是修改外部的x变量,而是在inner函数内部又创建了一个新的变量
print(y)
return inner
outer()() |
f04ebf307b78d87f0579d1b5d10e8781b761ff7e | menghaoshen/python | /11.面向对象/20.面向对象相关的方法.py | 755 | 4.125 | 4 | class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
class X(object):
pass
class Student(Person,X):
pass
p1 = Person('张三',18)
p2 = Person('张三',18)
s = Student('jack',19)
print(p1 is p2) #is 身份运算符是用来比较是否是同一个对象
print(type(s) == Student) #True
print(type(s) == ... |
96431b45040a0ec8e116f220ae08368ee9702c78 | menghaoshen/python | /04.流程控制语句/01.条件判读语句.py | 301 | 3.875 | 4 | #python 里面的条件判断语句 if/ if else / if elif elif else
#python 里面不支持 switch case 语句
# if 条件判断:
# 条件成立后执行的代码
age = int(input('请输入你的年龄:'))
if age < 18:
print('未满18岁不能进入')
else:
print('可以来开黑了') |
9110d37b4f6c4b7e75bba20fe41bdf7ea71904d2 | menghaoshen/python | /03-进制转换,数据类型详解、类型转换、预算符/15.逻辑运算的短路.py | 752 | 4.1875 | 4 | #逻辑与运算,只有所有的运算符都是True,结果才是True
#只有有一个运算数是False,结果就是False
4 > 3 and print('hello')
4 < 3 and print('您好世界')
#逻辑或运算,只有所有的运算符都是False,结果测试False
#只要有一个运算符是True,结果就是True
4 > 3 or print('哈哈哈')
4 < 3 or print('嘿嘿')
#短路: 只要遇到False,就停止了,不在继续执行了
#逻辑运算的结果,不一定是布尔值
#逻辑与运算取值时,取得是第一个为False的值,如果所有的运算数都是True,取最后一个
print(3 and 5 and 0 a... |
6b2ce25db352a3670b9b4ce9db3b2cbb2e772fe9 | menghaoshen/python | /03-进制转换,数据类型详解、类型转换、预算符/09.算数运算符在字符串里面使用.py | 415 | 4 | 4 | #字符串里面有限度支持加法和乘法运算符
#加法运算符: 只能用于两个字符串类型的数据,用来拼接两个字符串
print('hello' + 'world') #将多个字符串拼接成一个字符串
# print('18' + 1) #在python里面数字喝字符串直接不能用加法运算
#乘法运算符:可以用于数字和字符串之间,用来将一个字符串重复多次
print('hello' * 2)
|
dd0e50f1e7acd00d1f93c02d647e73ed54dab5c1 | menghaoshen/python | /99.练习题/01.基础题.py | 1,176 | 3.671875 | 4 | #根据输入的百分制成绩打印及格和不及格,60以下不及格
# score = float(input('请输入您的成绩'))
# if score >= 60:
# print('恭喜你及格了')
# else:
# print('没有及格,接着努力')
# 根据输入的年龄打印成年和未成年,18岁以下为未成年,如果年龄不在正常范围内(0,150岁)打印不是人
# age = int(input('请输入您的年龄:'))
#
# if 150 >= age >= 0:
# if age < 18:
# print('未成年')
# else:
# print('成年... |
3ff5315a8b87e189ba05889a73171f0cb8b230c5 | menghaoshen/python | /04.流程控制语句/11.break和continue关键字的使用.py | 1,001 | 3.921875 | 4 | #break 和continue 在python里面只能用在循环语句里面
#break:用来结束整个循环
#continue:用来结束本轮循环,开启下一轮循环
# i = 0
# while i < 5:
# if i == 3:
# i += 1
# continue
# print(i)
# i += 1
#不断询问用户,我爱你,你爱我么? 只要答案不是,就一直问,直到答案是爱
# answer = input('我爱你,你爱我么?')
# while answer != '爱':
# answer = input('我爱你,你爱我么?')
#优化
#... |
8a1b3984664de20844fb6fe73324ae0a1c9363e0 | menghaoshen/python | /09.函数/12.传参的问题.py | 208 | 3.5625 | 4 | def test(a):
a = 100
def demo(nums):
nums[0] = 10
x = 1
test(x)
print(x) #字符串是是不可变的数据类型
y = [3,5,6,8,2]
demo(y)
print(y) #[10, 5, 6, 8, 2] 列表是可变的数据类型 |
e307754f24725867d1068e915f095c82e8ef9d84 | menghaoshen/python | /99.练习题/03.求素数.py | 282 | 3.734375 | 4 | #素数也叫质数,除了1和它本身以外,不能再被其他的任何数整除
for i in range(2,101):
for j in range(2,i):
if i % j == 0: #i 除以某一个数字,除尽了i就是合数
break #结束内循环
else:
print(i,'是质数') |
72cb7e9d73041025ecd0e17490fb4cf1dcf1b508 | jw0711qt/Lab4camelcase | /Lab4_camelCase.py | 641 | 4.3125 | 4 | def camel_case(sentence):
if sentence.isnumeric(): #if statment handling empty and numeric number
return 'enter only words'
elif sentence=="":
return 'please enter your input'
else:
split_sentence=sentence.split() #for loop handling the camel case.
cap_sentence=[split_senten... |
066986a36915689682c8886bf2ecb6dc02df1aff | PSauerborn/Kaggle--San-Francisco-Crime-Prediction | /dataTool.py | 3,979 | 3.796875 | 4 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class dataTool():
"""Convenience tool used to analyse data sets"""
def fit(self, data):
"""Function used to fit tool to a specific data set
Parameters
----------
data: pandas DataFrame
... |
aed301cab5fe7b5b9e74afbd6a3e1aef457df718 | FURRO404/Geometry_Caclulator | /Geometry.py | 6,214 | 4.125 | 4 | #------------------ Basic geometry :3 ------------------#
#Geometry.py
from math import sqrt
from math import pi
import pymsgbox
print("Commands are:")
print("pyth - Pythagorean Theorem")
print("comp - Complementary Angle")
print("supp - Supplementary Angle")
print("tri - Triangle Menu")
print("trap - Trapezoid Menu"... |
193b42fb03e3f0f3895528d7d1d2fa40d2284e6f | linjungz/py4e_exercises | /chapter11/ex1.py | 253 | 3.609375 | 4 | import re
fhand = open('mbox.txt')
p = input('Enter a regular expression: ')
cnt = 0
for line in fhand:
line = line.rstrip()
if re.search(p, line) != None:
cnt = cnt + 1
print('mbox.txt had {0} lines that matched {1} '.format(cnt, p))
|
6c272fbdedd87251c8d4033b649aa1bcd56093c8 | tmflleowow/Python | /16_字串|迭代運算(Iteration).py | 346 | 4.53125 | 5 | #迭代運算
#用for 理由:簡單
'''
for c in "abcdefg":
print(c, end = " ")
'''
#用iter() 理由:可自定迭代順序
iterator = iter("abcdefg") # ==> ['a' , ''b' , 'c', ... , 'g']
for i in iterator:
print(i)
#用enumerate() 理由:有索引值與內容
iterator = enumerate("abcdefg")
for i , j in iterator:
print(i , j)
|
91dcfcdbeeb40cfa5699d352386102264eecdfd1 | warisgill/computer-vision-assignments | /assignment1/comp451/classifiers/softmax.py | 7,609 | 3.625 | 4 | from builtins import range
import numpy as np
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg, regtype='L2'):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N ex... |
f8b8a619d54d58a2d10ca48b5c4565357e1c5a0b | munichpavel/clovek-ne-jezi-se | /clovek_ne_jezi_se/game_state.py | 26,195 | 3.5 | 4 | """Clovek ne jezi se game board and plays"""
from math import pi
from typing import Sequence, Union
import warnings
import attr
import numpy as np
import matplotlib.colors as colors
from matplotlib import cm
import networkx as nx
import matplotlib.pyplot as plt
from .utils import (
make_even_points_on_circle, ... |
fb497eef36676cef95e329ada036b16e3982cc1e | yunjimyung/lotto | /matplotlib.py | 118 | 3.578125 | 4 | import matplotlib.pyplot as plt
X=[1,2,3,4,5,6,7,8,9,10]
Y=[1,2,4,4,5,6,7,8,9,10]
plt.plot(X,Y)
plt.show()
print(X+Y)
|
d08646b64a30af9be6227ebe16d825725df21530 | ZhouZoey/LeetCode-python | /leet21_MergeTwoSortedList.py | 1,496 | 3.890625 | 4 | # 合并两个有序的 链表
# 方法一: 递归
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution1(object):
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
elif l2 is None:
re... |
8dbdcb437061dc6b5f34564c0be5c4fe9df0b726 | rainiera/bioinformatics | /src/Transcription.py | 222 | 3.96875 | 4 | def transcribe():
print raw_input().replace('T', 'U')
if __name__ == '__main__':
t = raw_input()
result = ""
for letter in transcribe(t):
result = result + letter
print result
transcribe()
|
4b244800a208fb58be6f68a9e75e78688dcf50e3 | FurfurV/Employee_management | /viktoria_cseke_project.py | 9,194 | 4.125 | 4 | #Project by: Viktoria Cseke
#This project is about getting users input that affects the stored data
import random
def load_data():#load in the file then place it in a list
employee_id=[]
first_name=[]
last_name=[]
email=[]
salary=[]
with open("employees.txt") as employee_file:
... |
e10c234ced6d58376c2dc650504134bca9077aad | MaxWang0/Interview | /Fib.py | 121 | 3.703125 | 4 | #!/usr/bin/python
def fib(n):
a, b = 0, 1
while a < n:
print (a, end = ' ')
a, b = b, a + b
print()
|
30d9791286c33c2b609f4bb07913281feaa86f92 | porollansantiago/sudoku-comp | /test_sudoku.py | 10,007 | 3.640625 | 4 | import unittest
from sudoku import Sudoku
from parameterized import parameterized
class Test_sudoku(unittest.TestCase):
def setUp(self):
self.orig_board = (["53xx7xxxx",
"6xx195xxx",
"x98xxxx6x",
"8xxx6xxx3",
... |
4fc63d35f74e1c2bc21b69a6f223df1ffa62bbf3 | ecly/adventofcode2019 | /day04/day04.py | 508 | 3.6875 | 4 | import regex as re
def is_valid(n):
decreases = n == int("".join(sorted(str(n))))
adjacent = bool(re.search(r"(\d)\1{1,}", str(n)))
return decreases and adjacent
def is_valid2(n):
matches = re.findall(r"((\d)\2++)", str(n))
return is_valid(n) and any(len(match) == 2 for match, _digit in matches)... |
1263080c583b7307ef7cb8d093ce04d8ca5f54a7 | Vishal12328/hackerrank | /simple array sum/main.py | 210 | 3.84375 | 4 | numbers = input()
total = 0
temp = 0
for char in numbers:
if char ==" ":
total = total +temp
temp = 0
else:
temp = temp*10+int(char)
total = total + temp
print(total)
|
9fc5e53671198ada7ea95a2308cf837f329e200a | mats-bf/Torronto-neighborhoods | /Exam_part2.py | 11,362 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Peer-graded Assignment: Segmenting and Clustering Neighborhoods in Toronto
#
#
# ## Part 1
# #### First we import the relevant libraries
# In[1]:
import pandas as pd # library for data analsysis
import requests # library to handle requests
import urllib.request
import ... |
b99fb0fb898f4c7d27b8f89e374eb4023bc3e409 | theriley106/GoogleCodeChallenge | /9.py | 550 | 3.5 | 4 | start = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
end = [4, 17, 13, 7, 1, 10, 8, 12, 11, 3, 19, 15, 9, 2, 18, 16, 6, 5, 0, 14]
db = {}
for i, val in enumerate(start):
db[end.index(val)] = i
print db
def sortVal(listVal):
for i, val in db.iteritems():
a = int(listVal[i])
a = [None] * ... |
2caa6bef444f6d48d21171823536ae3c5e88acf0 | mikeyy109/TicTacPython | /TicTacToe.py | 5,568 | 3.671875 | 4 | import random
theBoard = {'t_l': ' ', 't_m': ' ', 't_r': ' ',
'm_l': ' ', 'm_m': ' ', 'm_r': ' ',
'b_l': ' ', 'b_m': ' ', 'b_r': ' '}
moves = ['t_l', 't_m', 't_r', 'm_l', 'm_m', 'm_r', 'b_l', 'b_m', 'b_r']
def printBoard(board):
print('You are \'X\'\n')
print(board['t_l'] + '|' + boa... |
2f5eeabbad6d9f7cc4a53e85da174af7ab891002 | tushushu/pads | /pads/sort/select_sort.py | 1,315 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
@Author: tushushu
@Date: 2018-09-10 22:23:11
@Last Modified by: tushushu
@Last Modified time: 2018-09-10 22:23:11
"""
def _select_sort_asc(nums):
"""Ascending select sort.
Arguments:
nums {list} -- 1d list with int or float.
Returns:
list -- List in ascendin... |
0d0b304f707cf62b8cc7dba4d666287423d126a8 | ykomashiro/deep-learning | /BP/softmax.py | 3,623 | 3.84375 | 4 | import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
mnist_data_folder = r'/MNIST'
mnist = input_data.read_data_sets(mnist_data_folder, one_hot=False)
X_tr = mnist.train.images
y_tr = mnist.train.labels
X_te = mnist.test.images
y_te = mnist.test.labels
class Mo... |
83e97cc66cec4c18201ce08f30527e76a828633b | derrowap/MA490-MachineLearning-FinalProject | /evolveAddThem.py | 1,485 | 4.0625 | 4 | # Author: Austin Derrow-Pinion
# Purpose: Train a Neural Network to mimic the funcitonality of adding
# two numbers together.
#
# ============================================================================
import numpy as np
from tensorflow.contrib.learn import TensorFlowDNNRegressor
import evolutionLearning as e
fro... |
0cb72fd6793f369d6ca8302dcf2426e6172ce09e | derrowap/MA490-MachineLearning-FinalProject | /evolutionLearning.py | 2,843 | 3.5 | 4 | # Author: Austin Derrow-Pinion
# Purpose: Create an evolutionary algorithm to teach nueral networks.
#
# ============================================================================
import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
i... |
8ade6118129ce93cf0f8945a4aec21d69e12d324 | RickyZhong/CheckIO | /O'REILLY/Disposable teleports.py | 1,190 | 3.640625 | 4 | from functools import namedtuple
Node = namedtuple("Node", ("Priority", "Path"))
def checkio(teleports_string):
# return any route from 1 to 1 over all points
# Don't remove checkio function
teleports = teleports_string.split(",")
queue = [Node(0, "1")]
while queue:
current = queue.pop()... |
82b00f25740ee6d4af117933392255cd8433c4d6 | J404/TicTacToe | /board.py | 3,011 | 3.75 | 4 | class Board:
def __init__(self, board):
if board is None:
self.board = []
self.initializeBoard()
else:
self.board = board
self.winner = None
def initializeBoard(self):
k = 1
for i in range(3):
self.board.append([])
... |
f47c3e069494f0ce23cfa15d269f4fc4e5fc78c1 | NortheastState/CITC1301 | /chapter10/Student.py | 2,049 | 3.890625 | 4 | # ===============================================================
#
# Name: David Blair
# Date: 04/14/2018
# Course: CITC 1301
# Section: A70
# Description: This file is an example of a class in Python.
#
# ===============================================================
class Student:
firs... |
3061761432f324109681aa8c0eb1b3a26378a461 | NortheastState/CITC1301 | /chapter4/graphicalWindow.py | 1,487 | 4.09375 | 4 | #===============================================================
#
# Name: David Blair
# Date: 01/01/2018
# Course: CITC 1301
# Section: A70
# Description: This program is a introduction to graphic user
# interfaces using a wrapper class called
# graphics.py which wraps ... |
7fd24f06f3e47581d35635e1767bc230da26b20b | NortheastState/CITC1301 | /chapter10/Course1301.py | 1,507 | 4.1875 | 4 | # ===============================================================
#
# Name: David Blair
# Date: 04/14/2018
# Course: CITC 1301
# Section: A70
# Description: You can think of this Python file as a "driver"
# that tests the Student class. It can also be
# thought of as a... |
475cee6f9b8424e9028087a90c96fc1c6c69a2e8 | NortheastState/CITC1301 | /chapter1/foobar.py | 964 | 4.21875 | 4 | # ===============================================================
#
# Name: David Blair
# Date: 01/01/2018
# Course: CITC 1301
# Section: A70
# Description: In the program we will examine simple output
# using a function definition with no parameters
# and a print statem... |
6e716dcdd031f49791a595f0966388aa0c934b75 | gregokrol/Password_Generator | /main.py | 515 | 3.875 | 4 | import random
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_- ={}[]/'
while 1:
password_len = int(input("What lenght would you want for your Password: "))
password_count = int(input("How many Password option you want : "))
for x in range(0,password_count):
passw... |
78d15d058fac421d87da03884fcdf6299c6f6b11 | smpenna3/eink | /old/text.py | 1,701 | 3.921875 | 4 | import ImageFont
import Image
import ImageDraw
import logging
# Grab Logger
logger = logging.getLogger('mainlog')
'''
the rotated text function draws text rotated at an angle at a center coordinate pair
INPUTS:
imageObject: the image object to draw on
string: the text to write
angle: the angle to rotate
... |
1b391e1b7a6408c42f954d29652faff023f6949d | MackRoe/Superhero-Team-Dueler_Term2 | /ability.py | 715 | 3.65625 | 4 | import random
class Ability:
def __init__(self, name, attack_strength):
'''
Initialize the values passed into this
method as instance variables.
'''
# Assign the "name" and "max_damage"
# for a specific instance of the Ability class
self.name = name
#... |
6021300db0894a0bfa0f14169287ff24885206b1 | aliensmart/hackerranck | /nested_list.py | 994 | 3.984375 | 4 | def second_low():
marksheet = []
for _ in range(0,int(input())):
marksheet.append([input(), float(input())])
second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]
# print(sorted(marksheet))
print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))
... |
0409b3664268c3848c7a3f34557fd9bcaa612693 | linjinux/foxJobGui | /app/pagepyfile/xialakuang.py | 2,123 | 3.84375 | 4 | import tkinter as tk
from tkinter import ttk
win = tk.Tk()
win.title("Python GUI")
ttk.Label(win, text="Chooes a number").grid(column=1, row=0) # 添加一个标签0
ttk.Label(win, text="Enter a name:").grid(column=0, row=0) # 设置其在界面中出现的位置
# button被点击之后会被执行
def clickMe():
action.configure(text='Hello'+name.get()+''+numberChose... |
8fb7a4409106434b359249ce2a251d6940c6d22a | vntborgesjr/Python-Programmer | /Introdcution-to-Data-Science-in-Python/02-Loading-Data-in-Pandas.py | 2,974 | 3.75 | 4 | # -------------------------------------------------
# Introduction to Data Science in Python - Loading Data in Pandas
# 10 set 2020
# VNTBJR
# ------------------------------------------------
#
# Load packages ------------------------------------------------
library(reticulate)
# Loading modules ---------------------... |
d3d5e5f20d8d0a01e2afc4732b189711d9e93ccd | ethele/algebra-lib | /algebra/algebra.py | 1,094 | 3.75 | 4 | class Algebra:
def __init__(self):
return
def simplify(self, expression):
builder = ExpressionTreeBuilder()
builder.expression = expression
expression_tree = builder.build_tree()
return str(expression_tree)
class ExpressionTreeBuilder:
def __init__(se... |
7a1f1ac5ff13138f32f0ca8d496d1364b5768f19 | Asingjr2/testing_py | /basic_functions.py | 430 | 4 | 4 | """Practice with basic testing."""
def add(x, y):
return x + y
def minus(x, y):
return x - y
def multi(x, y):
return x * y
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by a zero")
return x / y
def floor_divide(x,y):
"""Floor division to round result down."""
if y... |
0c825dd98f8b41594eac28492e143fd7fd5a1acf | maykulkarni/algopy | /CTCI/heap.py | 1,782 | 3.78125 | 4 | import math
class Heap:
_arr = [0] * 15
size = 0
def __init__(self):
pass
# self._arr = [12, 3]
# self.size = 2
@staticmethod
def from_array(arr):
pass
def __str__(self):
return str(self._arr)
def __len__(self):
return self.size
def get_parent_index(self, index):
return math.ceil(index/2 - 1... |
17b2d08041cac631cdbec723d81931b004002b8e | LuRiPTO20/Test-Repository | /Aufg-4_Wörterbuch mit Listenmanipulation_2021-05-05_v3.py | 7,096 | 3.8125 | 4 | # Standard Wörterbücher
woerterbuch_deutsch = ["Apfel", "Birne", "Kirsche", "Melone", "Marille", "Pfirsich"]
woerterbuch_english = ["apple", "pear", "cherry", "melon", "apricot", "peach"]
# Start: Abfrage
auswahl = input("\nWas möchten Sie tun?\nWort einfügen [E], Wort löschen [L], Abfrage [A], Wörterbuch zurücks... |
d134aa47e657f392b2c3ca97bd61a63a91416e70 | xiaotiger/sometest | /reverseWords.py | 470 | 3.609375 | 4 | import sys
class Solution :
def reverseWords(self, s) :
s = self.reverseWord(s)
ss = s.split(" ")
res = []
for item in ss :
res.append(self.reverseWord(item))
return " ".join(res)
def reverseWord(self, s) :
s = [i for i in s]
l = len(s)
for i in xrange(l/2) :
s[i], s[l-i-1] = s[l-i-1], s[i]
... |
9bc5bf07fbc4a04940394c23bfd0d0116422749e | sahilg50/Python_DSA | /Array/reverse_array.py | 782 | 4.3125 | 4 | #Function to reverse the array
def reverse(array):
if(len(array)==0):
return ("The array is empty!")
L = 0
R = len(array)-1
while(L!=R and L<R):
array[R], array[L] = array[L], array[R]
L+=1
R-=1
return array
#Ma... |
bce89e3b0d776b65663d93be75f4a6e4e8524738 | sahilg50/Python_DSA | /Patterns/Rectangle.py | 196 | 4 | 4 | rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
for i in range(rows):
for j in range(columns):
print("*", end=" ")
print("")
|
8a962ec652a3d239af3a3b860cf7663ab173c070 | sahilg50/Python_DSA | /Array/Max_Min_in_Array.py | 1,463 | 4.28125 | 4 | # Find the maximum and minimum element in an array
def get_min_max(low, high, array):
"""
(Tournament Method) Recursive method to get min max.
Divide the array into two parts and compare the maximums and minimums of the two parts to get the maximum and the minimum of the whole array.
"""
# If arr... |
db3014d09eba3692367d403b709cf5b9879e55f7 | manofdale/pythonProgramming | /ForFun/programmingPuzzles/arrays.py | 13,934 | 3.59375 | 4 | '''
Created on Aug 11, 2015
@author: agp
'''
from math import floor
from queue import Queue
def searchInAdjacentElements(adjacentElements,elem):
'''find index of an elem in an array (adjacentElements)
of numbers that change +1 or -1, return -1 if it doesn't exist'''
elementsLen=len(adjacentElements)
... |
a64eddd18e1551ed712100d3a86451eb74a3545a | manofdale/pythonProgramming | /ForFun/test/stringPuzzles_unittest.py | 733 | 3.53125 | 4 | '''
Created on Sep 2, 2015
@author: agp
'''
import unittest
from interviewPrepAshay.secondPhoneQuestion import segment
class Test(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.wordSet=set(['is','help','need','needed','the','boy','he','eat','ate','ice','cream'])
... |
f16cce34990fd0dc65a11163966c3b84748b64a3 | jtrieb1/scientific-computing | /project2/interpolators.py | 1,068 | 3.9375 | 4 | import math
from operator import mul
from functools import reduce
def makeEquiDistRange(n):
"""This method simply returns a set of n equidistant points between -1 and 1."""
return [2*(i/n) - 1 for i in range(n+1)]
def makeCosRange(n):
"""This method returns the set of n roots of the nth Chebyshev polynomial wit... |
5a0db410339c0ece9f7318baa20ad12c109fa091 | KshitijSrivastava/pythonMIT | /ps0/ps0.py | 251 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 13 14:34:26 2018
@author: hp1
"""
import numpy
x=int(input(" enter a number X"))
y=int(input(" enter a number Y"))
#x**y
log_x=numpy.log2(x)
xpowy=x**y;
print("X**y= ",xpowy)
print("log(x) = ",log_x)
|
b3ec1bbca61b912d6bf4e92c6935f7b4862e9254 | dispe1/Problem-Solving | /String/suffixArray/suffixArrayManberMyers.py | 716 | 3.609375 | 4 | from collections import defaultdict
#접미사 배열을 계산하는 맨버와 마이어스의 알고리즘 O(n(lgn)^2)
def sortBucket(str, bucket, order=1):
d = defaultdict(list)
for i in bucket:
key = str[i:i+order]
d[key].append(i)
result = []
for k,v in sorted(d.items()):
if len(v) > 1:
result += sortBuck... |
8dddf58383d87a13d3c7dd7d7f38a8576f48f800 | dispe1/Problem-Solving | /Numerical analysis/ternary.py | 461 | 3.796875 | 4 | #삼분 검색, 최대치를 포함하는 후보 구간을 알고 있어야 함.
#우리가 최대치를 찾고 싶어하는 함수
def f(x):
return -x*x
#[lo, hi] 구간에서 f(x)가 최대치를 갖는 x를 반환한다.
def ternary(lo, hi):
for iter in range(100):
a = (2*lo + hi) / 3
b = (lo + 2*hi) / 3
if(f(a) > f(b)):
hi = b
else:
lo = a
return (lo ... |
c5847a4cfffa90dc265c60d9492fe6106e0e17de | AlekseyPauls/JBInternship | /statistics/mean.py | 2,882 | 3.625 | 4 | import pandas as pd
"""
Input:
current_template - Dict with keys 'question', 'answer' and 'delimiters'
dataset - name of csv file with dataset
args1 - list of dicts with keys 'feature', 'interval' and 'value'. This is a main part of question
connectors1 - list of string. Strings may be 'and' or 'or'. Last value alway... |
7b62197a3a0395b563b62d68bc34066d8fa2643f | Libbybacon/Python_Projects | /myDB.db.py | 1,068 | 4.125 | 4 | # This script creates a new database and adds certain files from a given list into it.
import sqlite3
conn = sqlite3.connect('filesDB.db')
fileList = ('information.docx','Hello.txt','myImage.png', \
'myMovie.mpg','World.txt','data.pdf','myPhoto.jpg')
# Create a new table with two fields in filesDB datab... |
8f1507a5140d329d2234f13fe0987291a7ff4df5 | Libbybacon/Python_Projects | /buildingClass2.py | 2,665 | 4.25 | 4 |
# Parent class Building
class Building:
# Define attributes:
numberSides = 4
numberLevels = 1
architectureType = 'unknown'
primaryUse = 'unknown'
energyEfficient = True
def getBuildingDetails(self):
numberSides = input("How many sides does the building have?\n>>> ")
number... |
ee1017a6bd11e9af4ce8564034c7abed186afc2b | Libbybacon/Python_Projects | /Python_Challenges/python_challenge_5_get_file_path.py | 1,563 | 4.03125 | 4 | # Create GUI with button widget and text widget
# Include button function that will invoke dialog modal when called
# Dialog modal will allow users the ability to select a folder directory from their system
# Script will show user's selected directory path in text field
# use askdirectory() method
# When user clicks b... |
ed6b412f083035a0326468f7ed9fcb1a8e5cee23 | teng-pongsakorn/Numeric-Matrix-Processor | /Numeric Matrix Processor/task/processor/processor.py | 6,073 | 4.3125 | 4 |
import copy
MENU_MESSAGE = """1. Add matrices
2. Multiply matrix by a constant
3. Multiply matrices
4. Transpose matrix
5. Calculate a determinant
6. Inverse matrix
0. Exit"""
TRANSPOSE_MENU = '''1. Main diagonal
2. Side diagonal
3. Vertical line
4. Horizontal line
Your choice: > '''
def read_matrix():
n, m = ... |
7c36c9b987ccda4cc01daeb96af21fdf4020de56 | maxmailman/GeekBrains | /Python2/04_SQLAlchemy/base_classic.py | 880 | 3.515625 | 4 | import sqlalchemy
from sqlalchemy import create_engine # Для соединения с СУБД используется функция create_engine()
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import mapper
print("Версия SQLAlchemy:", sqlalchemy.__version__) # посмотреть версию SQLALchemy
engine =... |
f666ab4c142e8289dba3acbdd5ee5f125e22da0d | lynn/ithkuil | /ithkuil/parser/visitor.py | 9,599 | 3.515625 | 4 | from arpeggio import PTNodeVisitor
def pass_visitor(num=0):
'''A visiting function that will pass the selected child unchanged
(by default: the first one)'''
def visitor(a, node, children):
return children[num]
return visitor
def collect_visitor(a, node, children):
'''A visiting function t... |
ba0a9245a460fd954892e01c4880948c756b3163 | lynn/ithkuil | /ithkuil/morphology/words/helpers.py | 1,979 | 3.53125 | 4 | from ..helpers import vowels, consonants_s, tones
from ..exceptions import InvalidCharacter
def split(s):
if not isinstance(s, str):
raise TypeError('Word should be a string')
s = s.lower()
if not s:
return []
elif s[0] in tones:
return [s[0]] + split(s[1:])
elif s[0] in con... |
c6761bf61008668320fb356d73a5fe496022f221 | emmDevs/rock_paper_scissors | /app/models/player_test.py | 381 | 3.640625 | 4 | import unittest
from app.models.player import Player
class TestPlayer(unittest.TestCase):
def setUp(self):
self.bob = Player("Bob", "scissors")
self.alice = Player("Alice", "rock")
def test_player_has_a_name(self):
self.assertEqual("Bob", self.bob.name)
def test_player_has_a_choi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.