blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b50c668c4c45f37217dfd6ade5a9e5de105ba91e | tjsaotome65/sec430-python | /module-06/transcript.py | 544 | 3.5 | 4 | """
File: transcript.py
Project 10.10
This module defines the Transcript class.
"""
class Transcript(object):
"""This class represents transcript of chat messages."""
def __init__(self):
"""Creates a list of messages."""
self.messages = ["No messages yet!\n"]
def __str__(self):
"""Returns the join of all messages,
separated by newlines."""
return '\n'.join(self.messages)
def add(self, message):
"""Adds message to list of messages."""
self.messages.append(message)
|
22fed7a45b55c4a9542c2d6e8691239161905e2d | yang199811225430/yang1 | /python/untitled1/day1.py | 26,296 | 3.859375 | 4 | #!/usr/bin/python #定义一个解释器
#-*- coding:utf-8 -*- 定义编码方式
#print('hello',123,456,789) 输出
# a=input('请输入密码:')
#print(a)
#a,b,c='ycx',1,2.1
#print(b+c)
#print(type(c))
# a='asbf1234de'
# print(a[2::-2])
#b=a.upper()
#b=a.replace(' ','',3)
#b=a.split('bf')
#b=a.rstrip()
#b=a.startswith('asb')
#b=a.endswith('de')
#c='+'.join(b)
#a='{a1},{a2},{a3},{a4}'
#c=a.format(a1='我',a2='爱',a3='我',a4='家')
#a='hello %s,我今年%d岁'
#b=a% ('小明',1000000)
#a='qewwre'
#b=a.index('w')
#a='qwewwrt'
#b=a.count('w')
#a=[1,'我',2,9,6]
#a.insert(4,5)
#print(a)
# a=0
# for i in range(2,101,1):
# for j in range(2,i+1,1):
# if i % j ==0:
# #print(i)
# break
# if i == j:
# a=a+i
# print(a)
# a=input('请输入字符串')
# b=len(a)
# q=a[i]
# w=a[-(i+1)]
# c=b//2
# #if a ==a[::-1]:
# #print('这是一个回文字符串')
# #else:
# #print('这不是一个回文字符串')
# #if b %2==0:
# for i in range(c):
# if q !=w:
# print('这不是一个回文字符串')
# break
# else:
# print('这是一个回文字符串')
# a=1
# b=0
# while a<101:
# b+=a
# a+=1
# print(b)
# while True:
# a=input("输入成绩")
# a=a.split(',')
# a=[int(i) for i in a]
# d=sum(a)//len(a)
# if a[0]< 0:
# break
# print('平均数为{}'.format(d))
# b = [k for k in a if k < d]
# print(b)
# a=[1,5,6,8,7,8,9,5,7]
# for k in a:
# if a[k] == a[k+1]:
# a.remove(a[k])
# else:
# break
# print(a)
# a=[1,5,6,8,7,8,9,5,7]
# for i in a:
# b=a.count(i)
# if b>1:
# for j in range(b-1):
# a.remove(i)
# b=a.sort()
# print(a)
# a=[1,5,6,8,7,8,9,5,7]
# b=[]
# for i in a:
# if a not in b:
# b.append(a)
# print(b)
# f=open(r'a.txt','w',encoding='utf-8')
# f.write('sadf')
# f.close()
# f=open(r'a.txt','w',encoding='utf-8')
# for i in range(1,10):
# for j in range(1,i+1):
# f.write('{}*{}={}\t'.format(i,j,i*j))
# f.write('\n')
# f.close()
# f=open(r'a.txt','r',encoding='utf-8')
# b=f.readlines()
# #print(b)
# for i in b:
# if print(i.startswith('abc'))==True:
# print(i)
#
#
# f.close()
# f=open(r'a.txt','r',encoding='utf-8')
# b=f.readlines()
# #print(b)
# for i in b:
# if i[:3]=='abc':
# print(i)
#
#
# f.close()
# f=open(r'a.txt','r',encoding='utf-8')
# b=f.readlines()
# print(b[14],b[15],b[16],b[17],b[18],b[19])
# f.close()
# f=open(r'a.txt','r',encoding='utf-8')
# for i in range(1,21):
# if i<15:
# f.readline()
# else:
# print(f.readline())
# f.close()
# import random
# a=random.randrange(1,10)
# print(a)
# for i in range(1,4):
# b=input('请输入数字')
# b=int(b)
# if b==a:
# print('恭喜你答对了')
# break
# elif i==3:
# print('真菜')
# elif b>a:
# print('大了大了还有{}次机会'.format(3-i))
# elif b<a:
# print('小了小了还有{}次机会'.format(3-i))
# a=input('请输入')
# a=a.split(',')
# a=[int(i) for i in a]
# for i in range(1,len(a)):
# for j in range(0,len(a)-1):
# if a[j]>a[j+1]:
# t=a[j]
# a[j] = a[j+1]
# a[j+1]=t
# print(a)
# a=input('请输入')
# a=a.split(',')
# a=[int(i) for i in a]
# for b in range(0,len(a)):
# for j in range(b+1,len(a)):
# if a[b] > a[j]:
# t=a[b]
# a[b]=a[j]
# a[j]=t
# print(a)
# for i in range(100,1000):
# a=i//100
# b=i//10%10
# c=i%10
# if i==a**3+b**3+c**3:
# print(i)
# a=1
# b=0
# for i in range(1,101):
# a=i*a
# b=a+b
# print(b)
# for i in range(1,10):
# for j in range(1,i+1):
# print('{}*{}={}'.format(i,j,i*j),end='\t')
# if i==j:
# print()
# for i in range(50):
# for j in range(100):
# b=100-i-j
# if i*2+j*1+b*0.5==100 :
# print(i,j,b)
# with open('a.txt','r+',encoding='utf-8') as f:
# # b=f.read()
# # f.write('河山')
# # print(b)
# def a():
# b=0
# for i in range(101):
# b+=i
# print(b)
# a='123'
# c=0
# for i in range(len(a)):
# for j in range(10):
# if str(j)==a[i]:
# c+=j*10**(len(a)-1-i)
# print(c)
# a=[1,9,9,8,7,9,8,5,6]
# b=a.reverse()
# print(a)
# b=1
# def a():
# global b #将局部变量变为全局变量
# b=0
# print(b)
# a()
# print(b)
# def a(b):
# print('hello')
# print(b)
# a(1)
# def a(b=100):
# x=0
# for i in range(b+1):
# x+=i
# print(x)
# a()
# def zs(q,w):
# a=0
# for i in range(q,w+1):
# for j in range(2,i+1):
# if i % j ==0:
# break
# if i == j:
# a=a+i
# print(a)
# zs(2,10)
# def a(c):
# x=0
# for i in range(1,c+1):
# x+=i
# return x
# for i in range(10,41,10):
# c=a(i)+2
# print(c)
# def jsq(x,y,z):
# q=0
# if y=='+':
# q=x+z
# elif y=='-':
# q=x-z
# elif y=='*':
# q=x*z
# elif y=='//':
# q=x//z
# elif y=='/':
# q=x/z
# return q
# print(jsq(6,'-',2))
# a =lambda x,y :x + y
# b =lambda x,y :x - y
# c =lambda x,y :x * y
# d =lambda x,y :x / y
# while True:
# s=input('请输入')
# if '-' in s:
# q=s.split('-')
# print(b(int(q[0]),int(q[1])))
# elif '+' in s:
# q= s.split('+')
# print(a(int(q[0]),(q[1])))
# elif '*' in s:
# q = s.split('*')
# print(c(int(q[0]),(q[1])))
# elif '/' in s:
# q = s.split('/')
# print(d(int(q[0]),(q[1])))
# else:
# break
# def sc(a,b,c):
# a=list(a)
# z=len(a)
# if z-b<b+c:
#vgv
#
#
# elif z-b>b+c:
# for i in range(b,b+c):
#
# b='',join(a)
# print(b)
# sc('qwert',1,3)
# a=input('请输入')
# ff=[str(i) for i in range(10)]+['a','b','c','d','e','f']
# c=''
# while True:
# a=int(a)
# b=a%16
# c=c+ff[b]
# a=a//16
# if a==0:
# break
# print(c[::-1])
# a=input('请输入')
# b=a.split(',')
# b=[int(i) for i in b]
# b.sort()
# c=[]
# d=b.count(b[-1])
# for j in range(1,d+1):
# c.append(b[-1])
# b.remove(b[-1])
# f=b.count(b[-1])
# for j in range(1,f+1):
# c.append(b[-1])
# print(c)
# def asd():
# print('hello')
# def qwe():
# print(123)
# if __name__=='__main__':
# for i in range(10):
# print(i)
# try:
# a=1
# print(a)
# except Exception as e:
# print(e)
# else:
# print(789)
# finally:
# print(456)
#将九九乘法表写入a.xls
# import xlwt
# f=xlwt.Workbook()
# sheet=f.add_sheet('python_test')
# for i in range(1,10):
# for j in range(1,i+1):
# sheet.write(i-1,j-1,'{}*{}={}'.format(i,j,i*j))
# f.save('a.xls')
#读取excel表的第15到20行的内容
# import xlrd
# f=xlrd.open_workbook('a.xls')
# # b=f.nsheets
# # sheet=f.sheets()[0]
# #b=f.sheet_names()
# sheet=f.sheet_by_name('python_test')
# b=sheet.ncols
# for i in range(15,21):
# c=sheet.row_values(i)
# print(c)
# b=sheet.cell(2,0).value
# print(b)
#将文件里的内容写入到excel表格中
# import xlwt
# ff=xlwt.Workbook()
# sheet=ff.add_sheet('python_test')
# c=[]
# f=open('a.txt','r',encoding='utf-8')
# b=f.readlines()
# for i in range(len(b)):
# q=b[i]
# w=q.split(',')
# c.append(w)
# u=c[0]
# f.close()
# for j in range(len(b)):
# for z in range(len(u)):
# sheet.write(j,z,c[j][z])
# ff.save('a.xls')
#将b.txt追加到excel表中
# from xlutils.copy import copy
# import xlrd
# c=[]
# f=xlrd.open_workbook('a.xls')
# sheet1=f.sheet_by_name('python_test')
# b=sheet1.ncols
# a=sheet1.nrows
# print(b,a)
# ff=open('b.txt','r',encoding='utf-8')
# bb=ff.readlines()
# for i in range(len(bb)):
# q=bb[i]
# w=q.split(',')
# c.append(w)
# print(c)
# u=c[0]
# #print(len(b))
# ff.close()
# new_f=copy(f)
# sheet=new_f.get_sheet(0)
# for i in range(len(bb)):
# for j in range(len(u)):
# sheet.write(i+a,j,c[i][j])
# new_f.save('a.xls')
# import time
# b=time.localtime(100)
# a=time.strptime('2011-10-01 12:25:00','%Y-%m-%d %H:%M:%S')
# time.sleep(0)
# b=(2019,4,18,11,24,0,456,789,1)
# a=time.mktime(b)
# print(a)
#输入一个日期 显示是否为闰年 一年中的第几天 星期几 前一天
# import time
# a=input('')
# b=time.strptime(a,'%Y-%m-%d')
# print(b)
# if b[0]%100==0:
# if b[0]%400==0:
# print('{}年为闰年'.format(b[0]))
# else:
# print('{}年不是闰年'.format(b[0]))
# else:
# if b[0]%4==0:
# print('{}年为闰年'.format(b[0]))
# else:
# print('{}年不是闰年'.format(b[0]))
# print('一年中的第{}天'.format(b[7]))
#
# print('今天星期{}'.format(b[6]+1))
# c=(b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8])
# a=time.localtime(time.mktime(c)-86400)
# print('前一天为{}年{}月{}日'.format(a[0],a[1],a[2]))
#将a.xls文件中的数据写入b.txt中
# import xlrd
# f=xlrd.open_workbook('a.xls')
# sheet=f.sheets()[1]
# b=sheet.nrows
# print(b)
# ff=open('b.txt','w+',encoding='utf-8')
# for i in range(b):
# c=sheet.row_values(i)
# c=' '.join(c)
# ff.write('{}'.format(c))
# ff.write('\n')
# ff.close()
#求和、平均数 并把小于平均数的打印出来
# def a(*c):
# b=0
# for i in range(len(c)):
# b=c[i]+b
# print(b)
# e=b/len(c)
# print(e)
# for j in range(len(c)):
# if c[j]<e and c[j]>0:
# print(c[j])
# elif c[j]<0:
# break
# a(6,1,-1)
#
#对数据库的操作
# import pymysql
import xlrd
# conn=pymysql.connect(host='192.168.0.222',
# port=3306,
# user='root',
# passwd='112233')
# m=conn.cursor()
# #m.execute('create databases yang;')
# m.execute('use test;')
# #m.execute('show databases;')
# #m.execute('create table qwe(name char(20),age int,sex char(20));')
# #m.execute('insert into qwe values("小龙","10","男");')
# #m.execute('delete from qwe where age=10;')
# f=xlrd.open_workbook('a.xls')
# sheet=f.sheets()[0]
# b=sheet.nrows
# for i in range(b):
# c=sheet.row_values(i)
# if i==0:
# continue
# m.execute('create table txt({} char(20),{} char(20),{} char(20),{} int)'.format(c[0],c[1],c[2],c[3]))
# else:
# m.execute('insert into txt values("{}","{}","{}","{}")'.format(c[0],c[1],c[2],c[4]))
# m.execute('select * from txt;')
# b=m.fetchall()
# print(b)
# import pymysql
# conn=pymysql.connect(host='192.168.0.222',
# port=3306,
# user='root',
# passwd='112233')
# m=conn.cursor()
#m.execute('create databases yang;')
# m.execute('use test;')
#m.execute('show databases;')
#m.execute('create table qwe(name char(20),age int,sex char(20));')
#m.execute('insert into qwe values("小龙","10","男");')
#m.execute('delete from qwe where age=10;')
# f=open('a.txt','r',encoding='utf-8')
# b=f.readlines()
# print(b[0])
# c=b[0]
# for i in range(b):
# c=sheet.row_values(i)
# if i==0:
# continue
# m.execute('create table txt({} char(20),{} char(20),{} char(20),{} int)'.format(c[0],c[1],c[2],c[3]))
# else:
# m.execute('insert into txt values("{}","{}","{}","{}")'.format(c[0],c[1],c[2],c[4]))
# m.execute('select * from txt;')
# b=m.fetchall()
# print(b)
#将a.txt文件导入数据库中
# import pymysql
# with open('a.txt','r',encoding='utf-8') as f:
# a=f.readlines()
# coon=pymysql.connect(host='192.168.0.222',port=3306,user='root',passwd='112233')
# m=coon.cursor()
# m.execute('use test')
# for i in range(len(a)):
# c=a[i]
# c=c.split(',')
# if i==0:
# m.execute('create table a({} char(255),{} char(255),{} char(255),{} char(255));'.format(c[0],c[1],c[2],c[3]))
# else:
# m.execute('insert into a values("{}","{}","{}","{}");'.format(c[0],c[1],c[2],c[3]))
# m.execute('select * from a')
# d=m.fetchall()
# print(d)
# coon.close()
#将数据库中的数据导入到txt文档中
# import xlrd
# import pymysql
# conn=pymysql.connect(host='192.168.0.222',port=3306,user='root',passwd='112233')
# m=conn.cursor()
# m.execute('use test;')
# m.execute('select * from txt;')
# b=m.fetchall()
# m.execute('desc txt')
# c=m.fetchall()
# q=[]
# for j in range(len(c)):
# w=c[j][0]
# q.append(w)
# b=list(b)
# f=open('a.txt','w',encoding='utf-8')
# for i in range(len(q)):
# f.write('{},'.format(q[i]))
# f.write('\n')
# for i in range(len(b)):
# r=len(b[i])
# g=b[i]
# for j in range(r):
# f.write('{},'.format(g[j]))
# f.write('\n')
# f.close()
#将数据库中的数据导入excel表中
# import xlwt
# import xlrd
# import pymysql
# from xlutils.copy import copy
# conn=pymysql.connect(host='192.168.0.222',port=3306,user='root',passwd='112233')
# m=conn.cursor()
# m.execute('use test;')
# m.execute('select * from txt;')
# b=m.fetchall()
# m.execute('desc txt')
# c=m.fetchall()
# q=[]
# for j in range(len(c)):
# w=c[j][0]
# q.append(w)
# b=list(b)
# f=xlrd.open_workbook('b.xls')
# new_f=copy(f)
# sheet=new_f.get_sheet(0)
# for i in range(len(b)+1):
# for j in range(len(b[0])):
# if i == 0:
#
# sheet.write(0,j,q[j])
# else:
# sheet.write(i,j,'{}'.format(b[i-1][j]))
# new_f.save('b.xls')
# conn.close()
#判断本目录下所有的.py文件并打印出来
# import os
# a=os.getcwd()
# # os.chdir(r'F:\学习总结\python')
# # print(os.getcwd())
# # #b=os.popen('ping 192.168.0.1')
# # #print(b.read())
# # print(os.listdir(r'F:\学习总结'))
# #os.mkdir(r'F:\学习总结\aaa')
# #os.rmdir(r'F:\学习总结\aaa')
# #os.makedirs(r'F:\学习总结\aaa\bbb\ccc')
# #os.removedirs(r'F:\学习总结\aaa\bbb\ccc')
# b=os.listdir(r'F:\学习总结\python\untitled1')
# print(b)
# for i in b:
# c=os.path.isfile(i)
# w = os.path.splitext(i)
# if c==True:
# if w[1]=='.py':
# print(i)
# def qwe(*a):
# a=[int(i) for i in a]
# for i in (1,len(a)):
# for j in (0,len(a)):
# if a[j] > a[j+1]:
# t = a[j]
# a[j] = a[j+1]
# a[j+1] = t
# print(a)
# qwe(2,1,4)
# import paramiko
# with paramiko.SSHClient() as ssh123:
#
# ssh123.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# ssh123.connect(hostname='192.168.0.222',port=22,username='yang',password='123456')
# while True:
# q=input('>>>')
# if q=='exit':
# break
# else:
# a,b,c=ssh123.exec_command(q)
# print(b.read().decode())
#
#
# qq=paramiko.Transport(('192.168.0.222',22))
# qq.connect(username='yang',password='123456')
# sftp=paramiko.SFTPClient.from_transport(qq)
# sftp.put('day1.py','/etc/day1.py')
# qq.close()
# import smtplib
# import email.mime.multipart as mu
# import email.mime.text as text
# mm='17637839607@163.com'
# yy=['zhaolq1998@163.com','1508295989@qq.com']
# message=mu.MIMEMultipart()
# message['Subject']='python_test'
# message['From']=mm
# message['To']='.'.join(yy)
# txt="""
# 今晚的消费由赵公子买单!!! 尖叫声。。。。。
# """
# tet=text.MIMEText(txt)
# message.attach(tet)
# att1=text.MIMEText(open('b.xls', 'rb').read(), 'base64', 'utf-8')
# att1["Content-Type"] = 'application/octet-stream'
# # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
# att1["Content-Disposition"] = 'attachment; filename="b.xls"'
# message.attach(att1)
#
#
# smtp123=smtplib.SMTP_SSL('smtp.163.com',465)
# smtp123.login(mm,'yang1998')
# smtp123.sendmail(mm,yy,message.as_string())
# import socket
# sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# sock.connect(('192.168.0.98、',3000))
# while True:
# qq=input('>>>')
# if qq=='关闭':
# sock.close()
# else:
# sock.send(qq.encode('utf-8'))
# ww=sock.recv(1024)
# print(ww.decode('utf-8'))
# def qwe(x,y):
# for i in range(len(x)):
# for j in range(len(x)):
# if x[i]!=x[j]:
# a=x[i]+x[j]
# if a==y :
# if x[i]>x[j]:
# print(x[i],x[j])
# qwe([12,12,13,14,15],27)
# def a(s):
# s=s[::-1]
# b=0
# for i,v in enumerate(s):
# for j in range(0,10):
# if v==str(j):
# b=b+j*(10**i)
# return b
#发送邮件 以及附件
#如果需要给多个用户发邮件 就把收件人写成一个集合 然后 message[To]='.'.join(yy)
# import smtplib #封装smtp协议
# import email.mime.multipart as mu #制作邮件
# import email.mime.text as text #对邮件的正文进行处理
# mm='17637839607@163.com'
# yy=['1508295989@qq.com','17629712980@163.com']
# message=mu.MIMEMultipart() #创建一个邮件
# message['Subject']='yang_test' #添加邮件的标题
# message['From']=mm #添加发件人
# message['To']='.'.join(yy) #添加收件人
# txt='''新年快乐!''' #正文内容
# tet=text.MIMEText(txt) #对正文进行处理
# message.attach(tet) #将处理过的正文加入到邮件里
# att1=text.MIMEText(open('a.txt','rb').read(),'base64','utf-8') #添加一个文件
# att1["Content-Type"]='application/octet-stream' #附件的字段,固定的
# att1["Content-Disposition"]='attachment;filename="b.txt"' #filename 是给你的附件起一个新的名字
# message.attach(att1) #将附件添加到邮件中
# smtp666=smtplib.SMTP_SSL('smtp.163.com',465) #定义邮件服务器
# smtp666.login(mm,'yang1998') #登录服务器
# smtp666.sendmail(mm,yy,message.as_string()) #发送邮件
#读取文件的内容
# import xlrd
# import xlwt
# f=open('a.txt','r',encoding='utf-8')
# b=f.readlines()
# print(b)
# ff=xlrd.open_workbook('a.xls')
# sheet=ff.sheets()[0]
# for i in range(len(b)):
# for j in range(len(b)):
# sheet.write(i,j,b[i])
#基于udp的服务器
# import socket
# s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# s.bind(('192.168.0.98',3000))
# while True:
# client,addr=s.recvfrom(1024)
# print(client.decode('utf-8'))
# msg=input('>>>')
# s.sendto(msg.encode('utf-8'),addr)
# print(hex(123))
# print(oct(123))
# print(bin(123))
# print(int(0b11101))
# a=[chr(i) for i in range(97,103)]
# print(a)
# print(ord(''))
# a=[1,3,7,9,5]
# print(max(a))
# print(min(a))
# print(sum(a))
# a,b=divmod(100,16)
# print(a,b)
# import re
# a=input('>>>')
# b=re.compile('[0-9]{2,}')
# c=b.findall(a)
# print(len(c))
# a=input('>>>')
# c=len(a)
# print(c)
# b=0
# for j in range(c):
# print(j)
# for i in range(10):
# if str(i)==a[j]:
# b=b+i*10**(c-j-1)
# print(b)
# print(type(b))
#爬虫
import re
import requests
# class FreeBuf():
# def send_qq(self,page):
# url='https://www.freebuf.com/page/{}'.format(page)
#
# res=requests.post(url)
# hh=res.content.decode('utf-8')
# return hh
# def gl(self,x):
# title=[]
# patt=re.compile('<div class="news-img">(.*?)<dd>',re.S)
# itesms=patt.findall(x)
# for i in itesms:
# aa=re.findall('title="(.*?)"',i)
# title.append(aa[0])
# return title
# def save(self,y):
# with open('a.txt','a',encoding='utf-8') as f:
# for i in y:
# f.write(i+'\n')
# fr=FreeBuf()
# for i in range(1,5):
# hh=fr.send_qq(i)
# gg=fr.gl(hh)
# fr.save(gg)
#保存图片
# url='http://www.qiushibaike.com/imgrank/'
# head={
# 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
# }
# res=requests.post(url,headers=head)
# hh=res.content.decode('utf-8')
# print(hh)
# patt=re.compile(r'<img src="//pic.qiushibaike.com/system/pictures/(.*?).jpg"')
# itesms=patt.findall(hh)
# a=0
# for i in itesms:
# j='https://pic.qiushibaike.com/system/pictures/'+i+'.jpg'
# msg=requests.get(j,headers=head)
# hh=msg.content
# with open('{}.jpg'.format(a),'wb') as f:
# f.write(hh)
# a=a+1
# lj = []
# title = []
# class FreeBuf():
# def send_qq(self,page):
# url='http://movie.douban.com/top250?start={}&filter='.format(page)
# head = {
# 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
# 'Content-Type':'text / html;charset = utf - 8'
# }
# res=requests.post(url,headers=head)
# hh=res.content.decode('utf-8')
# return hh
# def gl(self,x):
# patt=re.compile('<img width="100" alt="(.*)" src="https://img([0-9]+).doubanio.com/view/photo/s_ratio_poster/public/(.*?)jpg" class="">')
# items=patt.findall(x)
# for i in range(len(items)):
# title.append(itesms[i][0])
# a='https://img'+items[i][1]+'.doubanio.com/view/photo/s_ratio_poster/public/'+items[i][2]+'jpg'
# lj.append(a)
# return lj
# def save(self,y,b):
# for i in range(len(y)):
# msg=requests.get(y[i])
# r=msg.content
# f=open('{}.jpg'.format(b[i]),'wb')
# f.write(r)
# fr=FreeBuf()
# hh=fr.send_qq(0)
# gg=fr.gl(hh)
# ss=title
# fr.save(gg,ss)
# #!/usr/bin/python
# #-*- coding:utf-8 -*-
# a=int(input('请输入总资产'))
# c=''
# goods=[
# {'0':'电脑','prince':1999},
# {'1':'鼠标','prince':10},
# {'2':'游艇','prince':20},
# {'3':'美女','prince':998},
# ]
# class Mdx():
# def __init__(self,a):
# self.a=a
# def gwc(self,*x):
# c=[]
# for i in range(len(x)):
# if len(goods) >= x[i]:
# b=x[i]
# v=goods[b]
# c.append(v)
# return c
# def gm(self,x):
# g=0
# for i in x:
# w=i['prince']
# g+=w
# if self.a>=g:
# self.a-=g
# print('购买成功,余额为{}元'.format(self.a))
# else:
# print('余额不足请充值')
# def cz(self,q):
# self.a = q + self.a
# print('充值成功,余额{}元'.format(self.a))
# def yc(self,x,*y):
# for i in y:
# print(x)
# s=x
# s.pop(y)
# print(s)
#
# m=Mdx(a)
# hh=m.gwc(1,2)
# m.gm(hh)
# print(goods)
# p = len(goods)
# while True:
# try:
# q = int(input('序号'))
# if p >= q:
# c=list(c)
# v=goods[q]
# print(v)
# c.append(v)
# print(c)
# elif p<q:
# print('该商品不存在')
# except:
# break
# print(c)
# b=len(c)
# while True:
# q=input('')
# g=0
# if q=='移除商品':
# print(c)
# e=int(input(''))
# c.pop(e)
# print(c)
# elif q=='购买':
# for i in c:
# w=i['prince']
# g+=w
# print(g)
# while True:
# if a>=g:
# a = a - g
# print('购买成功,余额{}元'.format(a))
# break
# if a<g and a!=0:
# print('余额不足,请充值')
# if input()=='充值':
# y=int(input(''))
# a=y+a
# print('充值成功,余额{}元'.format(a))
# break
# import socket
# s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# s.bind(('192.168.0.98',3000))
# s.listen(3)
# while True:
# client,addr=s.accept()
# reg=client.recv(1024)
# print(reg.decode('utf-8'))
# msg=input('>>>')
# client.send(msg.encode('utf-8'))
# import socket
# # s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# # host=(('192.168.0.88',3000))
# # while True:
# # qq=input('>>>')
# # s.sendto(qq.encode('utf-8'),host)
# # ww=s.recv(1024)
# # print(ww.decode('utf-8'))
# class Asd():
# def __init__(self,x,y):
# self.name=x
# self.xueliang=y
# def ad(self):
# self.xueliang -= 100
# print('{}还有{}血'.format(self.name,self.xueliang))
# def ert(self):
# # self.xueliang += 200
# # print('{}还有{}血'.format(self.name,self.xueliang))
# q=Asd('一航',200)
# p=Asd('幺妹',300)
# q.ad()
# p.ert()
import requests
import json
url='https://fe-api.zhaopin.com/c/i/sou?start=90&pageSize=90&cityId=538&salary=0,0&workExperience=-1&education=-1&companyType=-1&employmentType=-1&jobWelfareTag=-1&kw=%E8%BD%AF%E4%BB%B6%E6%B5%8B%E8%AF%95&kt=3&=0&_v=0.80226492&x-zp-page-request-id=f14ab29fd9c84c6987a2d1a82d7259ab-1557219520461-956404'
head={'User-Agent':'Mozilla/5.0(Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
res = requests.get(url,headers=head)
p=res.content.decode('utf-8')
aa = json.loads(p)
f=open('b.txt','w+',encoding='utf-8')
for i in range(0,90):
b1=aa['data']['results'][i]['company']['name']
b2=aa['data']['results'][i]['jobName']
b3=aa['data']['results'][i]['salary']
b4=aa['data']['results'][i]['city']['display']
b5=aa['data']['results'][i]['eduLevel']['name']
f.write("{},".format(b1))
f.write("{},".format(b2))
f.write("{},".format(b3))
f.write("{},".format(b4))
f.write("{}".format(b5))
f.write('\n')
f=open('b.txt','r',encoding='utf-8')
# a=f.readlines()
# import pymysql
# import xlwt
# ww=xlwt.Workbook('a.xls')
# sheet=ww.add_sheet('zhilian')
# c=["公司ID","岗位名称","薪资","公司地点","学历"]
# for k in range(len(c)):
# sheet.write(0,k,c[k])
# for l in range(0,len(a)):
# bb=a[l].split(',')
# for a1 in range(len(c)):
# sheet.write(l+1,a1,bb[a1])
# ww.save('a.xls')
# conn=pymysql.connect(host='192.168.0.222',port=3306,user='root',passwd='112233')
# m=conn.cursor()
# m.execute('use test')
# m.execute('create table zhilian(公司ID char(45),岗位名称 char(35),薪资 char(15),公司地点 char(10),学历 char(10))')
# for j in range(0,len(a)):
# bb=a[j].split(',')
# m.execute('insert into zhilian values("{}","{}","{}","{}","{}");'.format(bb[0],bb[1],bb[2],bb[3],bb[4]))
|
4b382a778e2d2aba9bca7cc8abee78535f523409 | Jadams29/Coding_Problems | /Regular_Expressions/RegEx_MatchEmail.py | 720 | 3.828125 | 4 | import re
# ---------- PROBLEM ----------
# Match email addresses
# 1. 1 to 20 lowercase and uppercase letters, numbers, plus ._%+-
# 2. An @ symbol
# 3. 2 to 20 lowercase and uppercase letters, numbers plus .-
# 4. A period
# 5. 2 to 3 lowercase and uppercase letters
# \d : [0-9] ----> an number 0-9
# \D : [^0-9] ----> not 0-9
# \w : [a-zA-Z0-9_] --> Matches any alphabet (upper/lower) and number (0-9) and (_)
# \W : [^a-zA-Z0-9_] ->
# \s : [\f\n\r\t\v]
# \S : [^\f\n\r\t\v]
randStr = "db@aol.com m@.com @apple.com db@.com"
print("Matches: ", len(re.findall("\w{1,20}[._%+-][@]\w{2,20}[.-]\.\w{2,3}", randStr)))
print("Email Matches: ", len(re.findall("[\w._%+-]{1,20}@[\w.-]{2,20}.[A-Za-z]{2,3}", randStr)))
|
8bb7c7b6eea59dadbde8a20abcb0728dd5217533 | ddawidowicz/pywing | /pywing/norm_data.py | 680 | 4.125 | 4 | # Usage:
# normalize(X)
#
# Input:
# X = a numpy array of numbers where each column is a different feature
# and each row is a different observation
#
# Outputs:
# X_norm = normed X array (mean=0, std=1)
# mu = mean used in norming
# sigma = std used in norming
#
import numpy as np
def normalize(X):
num_r = X.shape[0]
num_c = X.shape[1]
mu = np.mean(X,axis=0) #by column
sigma = np.std(X,axis=0, ddof=1) #by column and use sample deviation (N-1)
X_norm = (X-mu)/sigma
return (X_norm, mu, sigma)
def tester():
#expected result
#-1, -1
# 0, 0
# 1, 1
X = np.array([[1,2],[3,4], [5,6]])
(X_norm, mu, sigma) = normalize(X)
tester()
|
5c9c89c341c0a7f81ba9cc78c8a241530d50b12a | Livenai/100-lambs | /scripts/geometry.py | 6,144 | 4 | 4 | from math import sqrt
class Point:
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __str__(self):
return "(x: {0}, y :{1})".format(self.x, self.y)
def __repr__(self):
return "(x: {0}, y :{1})".format(self.x, self.y)
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def __truediv__(self, number):
return Point(self.x/number, self.y/number)
def distance(self, p):
return sqrt((self.x - p.x)**2 + (self.y - p.y)**2)
@staticmethod
def average(*points):
x = 0
y = 0
for p in points:
x += p.x
y += p.y
n = len(points)
return Point(x/n, y/n)
@staticmethod
def mid_point(p0, p1):
return (p0+p1)/2
@staticmethod
def bisector(p0, p1):
p = Point.mid_point(p0, p1)
aux = p1 - p0
dir = Point(-aux.y, aux.x)
return Line(p, p+dir)
# Rectangulo alineado con los ejes x, y
class Rectangle:
def __init__(self, pos, width, height):
self.x0 = pos.x - (width / 2)
self.x1 = self.x0 + width
self.y0 = pos.y - (height / 2)
self.y1 = self.y0 + height
# distancia desde un punto hasta el rectangulo alineado con los ejes x e y
def distance(self, point):
if point.x < self.x0:
h = self.x0 - point.x
elif point.x > self.x1:
h = self.x1 - point.x
else:
h = 0
if point.y < self.y0:
v = self.y0 - point.y
elif point.y > self.y1:
v = self.y1 - point.y
else:
v = 0
return sqrt(h**2 + v**2)
class Circle:
def __init__(self, center = Point(0,0) , radius = 1):
self.center = center
self.radius = radius
def __str__(self):
return 'center: {0}, radius: {1}'.format(self.center, self.radius)
def includePoint(self, point):
return point.distance(self.center) <= self.radius #+ error TODO
# Funcion recursiva para calcular el circulo minimo
# Se llama desde min_cicle para iniciarla correctamente
# p inicialmente contiene todos los puntos que hay que incluir en el circulo
# r contiene puntos que podrian estar en la circunferencia exterior
@staticmethod
def _welzl(p, r):
if len(p) == 1 and len(r) == 0:
return Circle(center = p[0], radius = 0)
elif len(p) == 0 and len(r) <3:
if len(r) == 1:
return Circle(center = r[0], radius = 0)
elif len(r) == 2:
center = Point.mid_point(r[0], r[1])
radius = center.distance(r[0])
return Circle(center, radius)
elif len(r) >= 3:
a = Point.bisector(r[0],r[1])
b = Point.bisector(r[1],r[2])
center = Line.intersection(a, b)
if center != None:
radius = center.distance(r[0])
return Circle(center, radius)
else:
# en este caso los puntos de r estan alineados se excluye el que
# está en el medio y se hace el circulo minimo con los otros
p2 = [(v, sum([v.distance(z) for z in r[:3]])) for v in r[:3]]
p2.remove(min(p2, key=lambda x: x[1])) #estos elimina ese punto
center = Point.mid_point(p2[0][0], p2[1][0])
radius = center.distance(p2[0][0])
# return Circle(center, 0)
return Circle(center, radius)
else:
circle = Circle._welzl(p[1:], r)
if circle.includePoint(p[0]):
return circle
else:
return Circle._welzl(p[1:], r + [p[0]])
# @staticmethod
# def _welzl(p, r):
# # soluciones trivial
# print("p:{}".format(len(p)),end=', ')
# print("r:{}".format(len(r)))
# if len(p) == 1 and len(r) == 0:
# return Circle(center = p[0], radius = 0)
# elif len(p) == 0 or len(r) >= 3:
# if len(r) == 1:
# return Circle(center = r[0], radius = 0)
# elif len(r) == 2:
# center = Point.mid_point(r[0], r[1])
# radius = center.distance(r[0])
# return Circle(center, radius)
# else:
# a = Point.bisector(r[0],r[1])
# b = Point.bisector(r[1],r[2])
# center = Line.intersection(a, b)
# radius = center.distance(r[0])
# return Circle(center, radius)
# else:
# circle = Circle._welzl(p[1:], r)
# if circle.includePoint(p[0]):
# print("NO")
# return circle
# else:
#
#
# return Circle._welzl(p[1:], r + [p[0]])
#Devuelve el circulo más pequeño que incluye todos los puntos dados
@staticmethod
def min_circle(* points):
if len(points) == 0:
raise AttributeError("min_circle tiene que ser llamados con uno o mas puntos")
r = []
# randomize(points) #TODO en cierto modo se pueden considerar ya aleatorios
return Circle._welzl(points, r)
class Line:
def __init__(self, p0, p1):
dy = (p1.y -p0.y)
dx = (p1.x - p0.x)
if(dx != 0):
self.slope = dy/ dx
else:
self.slope = "inf"
self.p0 = p0
self.p1 = p1
# TODO getpointatx
@staticmethod
def intersection(l0, l1):
if l0.slope == l1.slope:
return None # son paralelas
if "inf" not in (l0.slope, l1.slope):
x = (l0.slope*l0.p0.x) -l0.p0.y -(l1.slope* l1.p0.x)+l1.p0.y
x /= (l0.slope - l1.slope)
y = l0.slope*(x - l0.p0.x) + l0.p0.y
else:
if l0.slope == "inf":
aux = l0
l0 = l1
l1 = aux
x = l1.p0.x
y = l0.slope *(x -l0.p0.x) + l0.p0.y
return Point(x, y)
|
9787cfeccc688635a52cefe11ad6d3172f77ed50 | lulini1/Code-book | /Exercise/知识.py | 1,265 | 3.828125 | 4 | #作图程序模版
##•首先,导入turtle模块
##•然后,生成一只海龟
##•可以做一些初始化设定
##•程序主体:用作图语句绘图
##•最后结束作图
##•可选隐藏海龟:t.hideturtle()
# 1. 导入海龟模块
import turtle
n = 300
# 2. 生成一只海龟,做一些设定
t = turtle.Turtle()
t.pencolor("black") # 画笔颜色
t.pensize(n*0.10) # 画笔粗细
t.fillcolor("yellow")
# 3. 用海龟作图
#for i in range(5):
#t.forward(50)
#t.right(60)
t.forward(n)
t.left(120)
t.begin_fill()
t.forward(n)
t.left(120)
t.forward(n)
t.left(120)
t.end_fill()
t.penup()
t.goto(n*0.50,n*0.15)
t.pendown()
t.dot(n*0.08,"black")
t.penup()
t.goto(n*0.50,n*0.22)
t.pendown()
t.left(82)
t.pensize(1)
t.fillcolor("black")
t.forward(n*0.30)
t.begin_fill()
t.circle(n*0.04,180)
t.left(15)
t.forward(n*0.30)
t.end_fill()
# 4. 结束作图
t.hideturtle()
turtle.done()
#反向输出一个三位数
s_list = input('')
print(s_list[::-1])#切片
#如何用循环语句画出一个4种颜色边的正方形?•四种颜色的列表
import turtle
t = turtle.Turtle()
t.pensize(5)
#n = 4
colors = ['red','green','blue','yellow']
for c in colors:
t.pencolor(c)
t.fd(100)
t.lt(90)
t._tracer(0)
t.updata(0) |
8350dd1c2f852c0bd55658ddf21e4ae3e3a06205 | ITianerU/algorithm | /leetcode/22_括号生成/python.py | 1,075 | 4.0625 | 4 | """
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
"""
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
result = []
self.recursion('', 0, 0, n, result)
return result
def recursion(self, s, left, right, n, result):
# 表示字符串长度满足, n的2倍
if len(s) == 2 * n:
result.append(s)
return
# 当左括号的数量 < n时, 递归, 添加左括号, 左括号(left)数量加一
if left < n:
self.recursion(s + "(", left+1, right, n, result)
# 当右括号的数量 < 左括号的数量, 递归, 添加右括号, 右括号(right)数量加一
if right < left:
self.recursion(s + ")", left, right+1, n, result) |
c4ac3b74c9d4677cdd90c55e89cfe81f23c342f0 | dsuyash08/Miscellaneous-Algorithms-Unordered | /data structure week 1/data structure week 1/tree-height.py | 1,399 | 3.71875 | 4 | # python3
import sys, threading
from collections import deque
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class TreeHeight:
def read(self):
self.n = int(sys.stdin.readline())
self.parent = list(map(int, sys.stdin.readline().split()))
def compute_height(self):
# Replace this code with a faster implementation
nodes= [[]]
for i in range(self.n):
nodes.append([])
for i in range(self.n):
if self.parent[i] == -1:
root = i
pass
nodes[self.parent[i]].append(i)
maxHeight = 0
q = deque()
index = 0
q.append(nodes[root])
while(len(q) != 0):
index = len(q)
while(index > 0):
temp = q.popleft()
index -= 1
for i in temp:
q.append(nodes[i])
maxHeight += 1
return maxHeight;
def main():
tree = TreeHeight()
tree.read()
print(tree.compute_height())
threading.Thread(target=main).start()
|
38da91009c281aee57076aafbe360111fe8bb3e2 | sandhyaramavathu/pythonprograms | /80.py | 168 | 3.6875 | 4 | n = int(raw_input())
digits = []
while n>0:
r = n%10
if r&1! = 0:
digits.append(str(r))
n = n/10
digits = reversed(digits)
print (" ".join(digits))
|
eb5cb4fd744625e2daf9780811bac643c0819898 | chanakyack15/code-in-python | /max.py | 261 | 4.125 | 4 |
value=int(input("enter 1st no"))
value1=int(input("enter 2nd no"))
value2=int(input("enter 3rd no"))
print ("MAX no in all 3 no is:")
print (max(value,value1,value2))
print ("MIN no in all 3 no is:")
print (min(value,value1,value2))
input("enter to exit")
|
8690400786239d6f14a22d39637f027d2df5c15d | vaibhavg12/udacity-introduction-to-python | /project/analyze_data_chicago.py | 4,723 | 3.5 | 4 | import pandas as pd
path = "C:\\Users\\gv01\\Desktop\\googleSync\\LEarning\\Udacity\\Data Scientists Foundation\\python\\Resources\\"
filename = 'chicago.csv'
chicago_df = pd.read_csv(path+filename)
# df.head(), df.columns, df.describe(), df.info()
# df['column_name'].value_counts(), df['column_name'].unique()
def print_generic_information(df):
'''
prints generic information like head, columns, describe and info for the given dataframe.
INPUT
df: dataframe
OUTPUT
output by the methods head(), columns(), describe(), info() and shape respectively.
'''
print(df.head())
print('---------------------------------------------------------------------------')
print(df.columns)
print('---------------------------------------------------------------------------')
print(df.describe())
print('---------------------------------------------------------------------------')
print(df.info())
print('---------------------------------------------------------------------------')
print(df.shape)
def print_each_column_value_counts(df):
'''
print each coumn value count (count of each unique value in the column) for the given dataframe.
INPUT
df: dataframe
OUTPUT
output by the method value_counts() for each column of the dataframe
'''
column_list = list(chicago_df)
for column in column_list:
print('columne_name: {}, --> value_count: {}'.format(column,df[column].value_counts()))
print('---------------------------------------------------------------------------')
def print_each_column_unique(df,print_unique):
'''
prints each column's unique values and the count for the given dataframe.
INPUT
df: dataframe
print_unique: true if you want to print both, the unique values and count; false if you want to only print the count
OUTPUT
column name, unique value count and values (depending upon the value of print_unique)
'''
column_list = list(chicago_df)
for column in column_list:
values = df[column].unique()
unique_count = len(values)
if print_unique:
print('columne_name: {},---- Unique value count: {},---- values: {}'.format(column,unique_count,values))
print('---------------------------------------------------------------------------')
else:
print('columne_name: {},---- Unique value count: {}'.format(column,unique_count))
print('---------------------------------------------------------------------------')
# convert the Start Time column to datetime
chicago_df['Start Time'] = pd.to_datetime(chicago_df['Start Time'])
'''print('---------------------------Start time------------------------------------------------')
print(chicago_df['Start Time'])'''
# extract hour from the Start Time column to create an hour column
# chicago_df['hour'] = chicago_df['Start Time'].dt.hour
'''print('-----------------------------hour----------------------------------------------')
print(chicago_df['hour'])'''
# find the most popular hour
# popular_hour = chicago_df['hour'].mode()[0]
# print('-----------------------------Compute the Most Popular Start Hour----------------------------------------')
# print('Most popular start time is: {}'.format(popular_hour))
# print(chicago_df['Start Time'].dt.weekday)
# print('----------------------------MONTHS---------------------------------------')
# print(chicago_df['Start Time'].dt.month)
#print_each_column_value_counts(chicago_df)
#print_each_column_unique(chicago_df,False)
# print value counts for each user type
# user_types = chicago_df['User Type'].value_counts()
# print('------------------------------Display a Breakdown of User Types---------------------------------------------')
#print(user_types)
#print(pd.value_counts(chicago_df['User Type']).values)
# print('--------------------------------------------------------------------------')
#print(chicago_df['Gender'].value_counts())
# ypes = chicago_df['User Type'].value_counts().index.tolist()
# print(types)
# values = chicago_df['User Type'].value_counts().values.tolist()
# print(values)
chicago_df['month'] = chicago_df['Start Time'].dt.month
df_month = chicago_df[chicago_df['month'] == 1]
print(df_month.columns)
print("-"*50)
'''print('most common day of week')
print(df_month['day_of_week'].mode()[0])
print('\n')'''
print('user types')
print(df_month['User Type'].value_counts())
print('\n')
print('gender')
print(df_month['Gender'].value_counts())
print('\n')
chicago_df['day'] = chicago_df['Start Time'].dt.weekday
df_day = chicago_df[chicago_df['day'] == 0]
#print(df_day.columns)
|
6d13073c4510cc78690909a2d6b0c7b6fba067d6 | PrarabdhGarg/CryptocurrencyTrial | /blockchain.py | 3,530 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 28 17:43:53 2020
@author: prara
"""
import datetime
import hashlib
import json
from flask import Flask, jsonify
# Building the blockchain
class Blockchain:
def __init__(self):
self.chain = []
self.create_block(proof = 1, prev_hash = '0')
# Create block function is called after the mine_block function has
# completed solving the cryptographic puzzle, and the proof of work has
# been obtained. This function basically creates an instance of the block
# to be added in the chain variable
def create_block(self, proof, prev_hash):
block = {'block_number': len(self.chain) + 1,
'timestamp': str(datetime.datetime.now()),
'nonce': proof,
'prev_block_hash': prev_hash}
self.chain.append(block)
return block
def get_last_block(self):
return self.chain[-1]
# In our cryptographic problem, we also take into account the proof of work
# of the privious block
# We define the cryptographic problem using the SHA-256 hash function, and
# restrincting the hash to have exactly [leading_zeros] leading zeros
# The function we are using to calculate the hash has to be unsymytric
# Also, currently, as the block contains no data, we have not used it in
# generating the hash
def get_proof_of_work(self, previous_nonce):
nonce = 1
solved = False;
while solved is False:
block_hash = hashlib.sha256(str(nonce**2 - previous_nonce**2).encode()).hexdigest()
if block_hash[:4] == '0000':
solved = True
else:
nonce += 1
return nonce
def hash(self, block):
encoded_block = json.dumps(block, sort_keys = True).encode()
return hashlib.sha256(encoded_block).hexdigest()
def verify_chain(self, chain):
previous_block = chain[0]
block_index = 1
while block_index < len(chain):
current_block = chain[block_index]
if current_block['prev_block_hash'] != self.hash(previous_block):
return False
previous_proof = previous_block['nonce']
current_proof = current_block['nonce']
hash_operation = hashlib.sha256(str(current_proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:4] != '0000':
return False
previous_block = current_block
block_index += 1
return True
# Mining the blockchain
# Creating a Web server with Flask
app = Flask(__name__)
blockchain = Blockchain()
@app.route('/mineBlock', methods=['GET'])
def mineBlock():
last_block = blockchain.get_last_block()
proof_of_work = blockchain.get_proof_of_work(last_block['nonce'])
prev_hash = blockchain.hash(last_block)
new_block = blockchain.create_block(proof_of_work, prev_hash)
response = {'message': 'Congratulations on mining a new block',
'block_number': new_block['block_number'],
'timestamp': new_block['timestamp'],
'nonce': new_block['nonce'],
'prev_block_hash': new_block['prev_block_hash']}
return jsonify(response), 200
@app.route('/getBlockchain', methods=['GET'])
def getBlockchain():
response = {'chain': blockchain.chain,
'length': len(blockchain.chain)}
return jsonify(response), 200
app.run(host='0.0.0.0', port=5000) |
c0563073d63d71e6aa8d6f5d830586202b0ca360 | Jexan/ProjectEulerSolutions | /src/E020.py | 299 | 3.6875 | 4 | # Get the sum of the digits of factorial of 100.
# OPTIMAL (<0.1s)
#
# APPROACH:
# Get the factorial, convert the number to string and sum all the digits.
from math import factorial
LIMIT = 100
def sum_fact_digits(n):
return sum(map(int, str(factorial(n))))
result = sum_fact_digits(100) |
6fa4724896eeb16797cd61cad4113f7e7dfeb13c | ryandawsonuk/UdemyMachineLearningAtoZPythonAndR | /17 - Apriori Association Rule Learning/Apriori_Python/apriori.py | 1,404 | 3.703125 | 4 | # Apriori
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
#The data set needs to be transformed to a list of lists
dataset = pd.read_csv('Market_Basket_Optimisation.csv', header = None)
transactions = []
for i in range(0, 7501):
#our master list should contain a list for each row (there are 20 columns)
transactions.append([str(dataset.values[i,j]) for j in range(0, 20)])
# Training Apriori on the dataset
# the apyori class is an implementation of the a priori algorithm taken from the python software foundation
# taking minimum support to be items purchased at least 3 times a day (so 7*3 / 7501 )
# this is number of transactions with those products as proportion of total - approximately 0.003
# to set confidence we actually start with default (0.8) and then play with it until we get useful rules
# the default gives no rules at all, since no rules obtain in 80% of transactions
# instead we settle on a lower confidence of 0.2
# min length is 2 as only want to consider transactions with at least 2 products
# filter by lift of at least 3 so we only get strong rules
from apyori import apriori
rules = apriori(transactions, min_support = 0.003, min_confidence = 0.2, min_lift = 3, min_length = 2)
# Visualising the results
# they should already be automatically sorted by the source library
results = list(rules) |
4dd5ffa53c4986b5c1726ec2e2b16d01a07b8cb2 | Alex7lav81/Group_22 | /Python_HW/HW_4/Task_2.py | 1,719 | 3.921875 | 4 | ''' Задача №2
===== Обменник =====
Создать скрипт, который будет запускаться из консоли 1 раз, выдавать результат и зарываться.
1. На вход обменнику вводишь количество денег int.
2. На выходе в консоль выводится отввет в таком виде:
"Вы ввёли int (Валюта)"
"Конвертированная сумма в USD = int"
"Конвертированная сумма в EUR = int"
"Конвертированная сумма в CHF = int"
"Конвертированная сумма в GBP = int"
"Конвертированная сумма в CNY = int"
3. Валюту пользователя определите сами.
'''
input_money_BYN = int(input("Введите сумму для конвертации: "))
input_money_USD = input_money_BYN / 2.50
input_money_EUR = input_money_BYN / 2.95
input_money_CHF = input_money_BYN / 2.71
input_money_GBP = input_money_BYN / 3.46
input_money_CNY = input_money_BYN / 0.38
print("Вы ввели ", input_money_BYN, " BYN")
print("Конвертированная сумма в USD = ", round(input_money_USD, 2))
print("Конвертированная сумма в EUR = ", round(input_money_EUR, 2))
print("Конвертированная сумма в CHF = ", round(input_money_CHF, 2))
print("Конвертированная сумма в GBP = ", round(input_money_GBP, 2))
print("Конвертированная сумма в CNY = ", round(input_money_CNY, 2)) |
0c6d396ce9e7830d888da0e77204992c40c91cc2 | shubhamoli/solutions | /leetcode/medium/1414-Min_fib_sum_k.py | 856 | 3.5 | 4 | """
Leetcode #1414
"""
class Solution:
# It is guaranteed that for the given constraints
# we can always find such fibonacci numbers that sum k.
def findMinFibonacciNumbers(self, k: int) -> int:
#find fib numbers up to k
fibo = [1,1]
while fibo[-1] <= k:
fibo.append(fibo[-1] + fibo[-2])
print(fibo)
# here we have our inventory
# greedy approach
value = 0
count = 0
while k > 0:
for i in fibo:
if i <= k:
value = i
count += 1
k -= value
return count
if __name__ == "__main__":
solution = Solution()
# assert solution.findMinFibonacciNumbers(7) == 2
# assert solution.findMinFibonacciNumbers(10) == 2
assert solution.findMinFibonacciNumbers(19) == 3
|
08f769856ca72e30a3d85fb8e6f8946252cce02f | AleksMaykov/GB | /lesson1_normal.py | 1,849 | 4.03125 | 4 | import time
# Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10.
# После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран.
# Например, пользователь вводит число 123, вы сообщаете ему, что число не верное,
# и сообщаете об диапазоне допустимых. И просите ввести заного.
# Допустим пользователь ввел 2, оно подходит, возводим в степерь 2, и выводим 4
num = 0
while num < 1 or num >10:
num = int (input('Введите любое число:'))
if num < 0:
print('ведите число заново и побольше!')
elif num >10:
print('Введите число заново и поменьше!')
num **=2
print(num)
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
# Решите задачу, используя только две переменные.
# Подсказки:
# * постарайтесь сделать решение через действия над числами;
a = input('Введите значение числа А:')
b = input('Введите значение числа B:')
print('Вы ввели 2 числа: А = ' + a + ' и B = ' + b )
time.sleep(3)
a,b = b,a
print('Или такие 2 числа: А = ' + a + ' и B = ' + b ) |
df1283b20d8eb7a8c35641d128d0a57df25e431e | Serjeel-Ranjan-911/CSES-Solution | /Introductory Problem/Tower of Hanoi/sol.py | 250 | 3.6875 | 4 | n = int(input())
print(2**n - 1)
def toh(n,source,destination,aux):
if n == 1:
print(source,destination)
return
toh(n-1,source,aux,destination)
print(source,destination)
toh(n-1,aux,destination,source)
toh(n,1,3,2)
|
c34ba7b063c024a76776566bc092cfffc35e62da | mousemgr/CETI-Python | /AdivinarNumeroWhile.py | 752 | 3.703125 | 4 | import random
respuesta = -1
piso = 0
techo = 50
intentos_jugador = 1
numero_random = random.randint(1,50)
intentos_totales = 4
print(numero_random)
print("Estoy pensando un numero entre 1 y 50")
while respuesta != numero_random and intentos_jugador<=intentos_totales:
respuesta = int(input("Intento " + str((intentos_jugador)) + "?"))
if respuesta == numero_random:
break
elif respuesta < numero_random:
piso = respuesta
else:
techo = respuesta
print("El numero esta entre " + str(piso) + " y " + str(techo))
intentos_jugador+=1
if intentos_jugador>intentos_totales:
print("Se acabaron los intentos, el numero que pense era " + str(numero_random))
else:
print("Felicidades, Ganaste...!!!")
|
b711cb64f4762919774c5d28911bcb3a41022ead | davidozhang/codeforces | /life_without_zeroes.py | 368 | 3.6875 | 4 | #!/usr/bin/python
'''
Problem 75A: http://codeforces.com/problemset/problem/75/A
Solved on: 2015-03-08
Result: Accepted 92 ms 8 KB
'''
def main():
first, second=raw_input(), raw_input()
if (int(str(int(first)+int(second)).replace('0','')))==int(first.replace('0',''))+int(second.replace('0','')):
print 'YES'
else:
print 'NO'
if __name__=='__main__':
main() |
49c58812085b9bb9d521523a19e6ec2d5f7dcdd6 | Parya1112009/mytest | /revstring.py | 142 | 3.890625 | 4 | import string
str1 = "this is new york"
a = str1.split()
a.reverse()
print a
result = " ".join(a)
s = type(result)
print result
print s
|
624ab4273f05b0acae793703dd00304c977ba260 | benzoa/pythonStudy | /basics/ex21_exception.py | 2,518 | 3.90625 | 4 | try:
x = int(input("number: "))
y = 10 / x
print(y)
except:
print("exception occured")
print("=" * 40)
val = [10, 20, 30]
'''
try:
idx, x = map(int, input("index and number: ").split())
print(val[idx] / x)
except ZeroDivisionError:
print("The number cannot be divided by zero.")
except IndexError:
print("Invalid index")
'''
'''
try:
idx, x = map(int, input("index and number: ").split())
print(val[idx] / x)
except ZeroDivisionError as e:
print("error:", e)
except IndexError as e:
print("error:", e)
'''
try:
idx, x = map(int, input("index and number: ").split())
print(val[idx] / x)
except Exception as e:
print("error:", e)
print("=" * 40)
try:
x = int(input("num: "))
y = 10 / x
except ZeroDivisionError as e:
print("error:", e)
else:
print("result: {}".format(y))
finally:
print("=" * 40)
'''
try:
x = int(input("a multiple of three: "))
if x % 3 != 0:
raise Exception('It\'s not a multiple of 3.')
print("x:", x)
except Exception as e:
print("error:", e)
'''
'''
def three_multiple():
x = int(input("a multiple of three: "))
if x % 3 != 0:
raise Exception('It\'s not a multiple of 3.')
print("x:", x)
try:
three_multiple()
except Exception as e:
print("error:", e)
'''
def three_multiple():
try:
x = int(input("a multiple of three: "))
if x % 3 != 0:
raise Exception('It\'s not a multiple of 3.')
print("x:", x)
except Exception as e:
print("e:", e)
raise RuntimeError("Error in three_multiple")
try:
three_multiple()
except Exception as e:
print("error:", e)
print("=" * 40)
x = int(input("a multiple of four: "))
assert x % 4 == 0, 'It\'s not a multiple of 4.'
print("x:", x)
print("=" * 40)
# Making Exception
# Type1
'''
class NotThreeMultipleError(Exception):
def __init__(self):
super().__init__('It\'s not a multiple of 3.')
def three_multiple():
try:
x = int(input("a multiple of three: "))
if x % 3 != 0:
raise NotThreeMultipleError
print(x)
except Exception as e:
print('e:', e)
three_multiple()
'''
# Type2
class NotThreeMultipleError(Exception):
pass
def three_multiple2():
try:
x = int(input("a multiple of three: "))
if x % 3 != 0:
raise NotThreeMultipleError('It\'s not a multiple of 3.')
print(x)
except Exception as e:
print('e:', e)
three_multiple2() |
968f4d2e8516d8045ef3507ddf3205a50ebf4705 | kevinrajk/pythonprogramming | /basicstring.py | 1,088 | 4.125 | 4 | program:
print("Hello World")
print("Hello ")
a=10
b=20
c=a+b
print(c)
mystring='hi python'+' programming'
print(mystring[2:9])
print(mystring.split(' '))
print(mystring.find('p'))
print(mystring.replace('hi','hello'))
print("the length of the string is",len(mystring))
output:
Hello World
Hello
30
python
['hi', 'python', 'programming']
3
hello python programming
the length of the string is 21
|
4b3dac461a3afc90e0df95d73559fe960453331b | J-RAG/DTEC501-Python-Files | /Lab1-2-1q2.py | 161 | 3.765625 | 4 | # Lab 1-1-2 question 2
# By Julan Ray Avila Gutierrez, jra0108@arastudent.ac.nz
first_name = input("Please enter your first name: ")
print("Hi")
print(first_name)
print("Pleased to meet you.") |
94e77c1f12be2d0e6c92d6bb8cefbc74caddc49a | ChaitanyaPuritipati/CSPP1 | /CSPP1-Practice/cspp1-assignments/m10/how many_20186018/how_many.py | 786 | 4.15625 | 4 | '''
Author: Puritipati Chaitanya Prasad Reddy
Date: 9-8-2018
'''
#Exercise : how many
def how_many(a_dict1):
'''
#aDict: A dictionary, where all the values are lists.
#returns: int, how many values are in the dictionary.
'''
counter_values = 0
for i in a_dict1:
counter_values = counter_values + len(a_dict1[i])
return counter_values
def main():
'''
Main Function starts here
'''
input_num = int(input())
a_dict = {}
i_num = 0
while i_num < input_num:
s_str = input()
l_list = s_str.split()
if l_list[0][0] not in a_dict:
a_dict[l_list[0][0]] = [l_list[1]]
else:
a_dict[l_list[0][0]].append(l_list[1])
i_num = i_num+1
print(how_many(a_dict))
if __name__ == "__main__":
main()
|
5920ecffab483d5d8a99bcf4bdce9eff3cb72efe | AtindaKevin/BootCamp | /flow control/simapp.py | 601 | 4.3125 | 4 | """Create a console application that asks that does the following
-ask the user to set their pin
-the user has three attempts to log in
-if the user enters a wrong pin, he can reenter it and display the number of attempts left
-if attempts are exhausted, display sim blocked
"""
set_pin = int(input("Set your pin:"))
i = 3
while i>0:
pin = int(input("Enter your pin:"))
if pin==set_pin:
print("login successful")
break
elif pin!=set_pin:
i-=1
if i==0:
print("sim blocked")
else:
print("You have",i,"attempts left") |
aed693d0e3adfeebacb6d76c8b497828cb4c8b82 | saurabhkulkarni77/Demonstration-of-vanishing-gradient-from-scratch | /SimpleNN_Comparison_of_sigmoid_Relu_Vanishing_gradient.py | 2,114 | 3.6875 | 4 |
#For exploding gradient problem:
#First introduced by mikolov. Its states that if value is above threshold value just cap it to 5 or something low.
#Although being simplle it makes huge difference in RNNs
#So why clipping doesnt solve vanishing gradient problem? because in vanishing gradient value gets smaller and smaller
#and it doesnt make sense to clip it.. so why not just bump it?, consider this scenerio where if we bump it by some value then
#its like trying to say hey 50th word doesnt make sense lets go to 100th word which will (?) make sense.. so it doesnt work here either..
#For this, we will initialize Ws to identity matrix I and f(z) = rect(z) = max(z,0) or try LSTMs..
import numpy as np
import matplotlib.pyplot as plt
N = 100 # number of points per class
D = 2 # dimensionality
K = 3 # number of classes
X = np.zeros((N*K,D)) # data matrix (each row = single example)
y = np.zeros(N*K, dtype='uint8') # class labels
for j in xrange(K):
ix = range(N*j,N*(j+1))
r = np.linspace(0.0,1,N) # radius
t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
y[ix] = j
# lets visualize the data:
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
#plt.show()
# initialize parameters randomly
W = 0.01 * np.random.randn(D,K)
b = np.zeros((1,K))
# compute class scores for a linear classifier
scores = np.dot(X, W) + b
num_examples = X.shape[0]
# get unnormalized probabilities
exp_scores = np.exp(scores)
# normalize them for each example
probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)
correct_logprobs = -np.log(probs[range(num_examples),y])
# compute the loss: average cross-entropy loss and regularization
data_loss = np.sum(correct_logprobs)/num_examples
reg = 1e-3
# some hyperparameters
step_size = 1e-0
reg_loss = 0.5*reg*np.sum(W*W)
loss = data_loss + reg_loss
dscores = probs
dscores[range(num_examples),y] -= 1
dscores /= num_examples
dW = np.dot(X.T, dscores)
db = np.sum(dscores, axis=0, keepdims=True)
dW += reg*W # don't forget the regularization gradient
W += -step_size * dW
b += -step_size * d
|
862b091109212d657725bdc8e29521b6371eea52 | Lil-Bowie/python_feb_2017 | /loop.py | 382 | 3.6875 | 4 | num = 1
for num in range(1,1000):
print num
#start my counter
value = 5
for value in range(5,1000000) :
if value % 5 == 0:
print value
#print the multiples of 5
def fSum():
i = 0
arr = [1,2,5,10,255,3]
i = sum(arr)
print i
fSum()
#take the sum of List.
def fAvg():
i = 0
arr = [1,2,5,10,255,3]
i = sum(arr)/len(arr)
print i
fAvg()
|
ba6f46765a407a20ee08e78d71e7eee646b5c9d5 | Lee-W/leetcode | /problem/p_0094_binary_tree_inorder_traversal/solutions.py | 737 | 3.921875 | 4 | from typing import List, Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
Runtime: 39 ms (56.66%)
Memory Usage: 13.8 MB (99. 3%)
"""
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
cur = root
stack: List[TreeNode] = []
result = []
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
result.append(cur.val)
cur = cur.right
return result
|
d608414a105347004066fd7e6bf5426d3227ce79 | Mikemraz/Data-Structure-and-Algorithms | /LeetCode/Search in Rotated Sorted Array.py | 843 | 3.75 | 4 | class Solution:
"""
@param A: an integer rotated sorted array
@param target: an integer to be searched
@return: an integer
"""
def search(self, A, target):
# write your code here
if len(A)==0:
return -1
start = 0
end = len(A) - 1
while end-start>1:
mid = (end-start)//2 + start
if target == A[mid]:
return mid
if target>A[-1]:
if A[-1]<A[mid]<target:
start = mid
else:
end = mid
else:
if target<A[mid]<A[-1]:
end = mid
else:
start = mid
if target==A[start]:
return start
if target==A[end]:
return end
return -1
|
0dac62fdc52bbb6c36ea63742ec3c4fa539b662e | ocdarragh/Computer-Science-for-Leaving-Certificate-Solutions | /Chapter 1/pg17.py | 195 | 3.828125 | 4 | # pi=3.14
# r=7
# answer=((4/3)*pi)*r**3
# print(answer)
pi=3.14
r=7
answer=((4/3)*pi)*r**3
answer=round(answer,2) # 2 arguments (1st is the value,2nd is decimal places)
print(answer)
|
67696159ca06382a84bb1140c061a7d6f85749e1 | vasalf/mammoth-world | /W2/helpers/geom.py | 4,581 | 3.546875 | 4 | #!/usr/bin/python3
"""This is a library that provides geometry classes and functions
It is a part of mammoth-world project
(https://github.com/vasalf/mammoth-world)
"""
from random import *
from math import log
"""A place to import modules is up to that comment.
"""
__author__ = "vasalf"
def cross_product(a, b):
return a[0] * b[1] - b[0] * a[1]
def dot_product(a, b):
return a[0] * b[0] + a[1] * b[1]
def sq_point_distance(a, b):
x = a[0] - b[0]
y = a[1] - b[1]
return x * x + y * y
def vector(a, b):
return (b[0] - a[0], b[1] - a[1])
class __sorted_by_polar_angle_point:
"""This is a helper class to convex
"""
def __init__(self, p, first):
self.__pt = p[:]
self.__first = first[:]
def __getitem__(self, i):
return self.__pt[i]
def __lt__(self, other):
if cross_product(vector(self.__first, self),
vector(self.__first, other)) == 0:
return sq_point_distance(self.__first, self) < \
sq_point_distance(self.__first, other)
else:
return cross_product(vector(self.__first, self),
vector(self.__first, other)) > 0
def __tuple__(self):
return self.__pt
def convex(point_set):
"""That functions builds the convex of a point_set.
It uses Graham algotirhm.
"""
start = min(point_set)
set_copy = []
for p in point_set:
set_copy.append(__sorted_by_polar_angle_point(p, start))
set_copy.sort()
set_copy.append(start)
res = set_copy[:2]
for p in set_copy[2:]:
while len(res) >= 2 and \
cross_product(vector(res[-1], res[-2]), vector(res[-1], p)) >= 0:
res.pop()
res.append(p)
return list(map(tuple, res[:-1]))
def unite(lst):
res = []
for pol in lst:
for p in pol:
res.append(p)
return res
"""Here are some geometry helper functions
"""
def is_point_in_segment(p, a, b):
return cross_product(vector(p, a), vector(p, b)) == 0 and \
dot_product(vector(p, a), vector(p, b)) <= 0
def do_segments_intersect(a, b, c, d):
if cross_product(vector(a, b), vector(c, d)) == 0:
return is_point_in_segment(a, c, d) or \
is_point_in_segment(b, c, d) or \
is_point_in_segment(c, a, b) or \
is_point_in_segment(d, a, b)
else:
return cross_product(vector(a, c), vector(a, b)) * \
cross_product(vector(a, b), vector(a, d)) >= 0 and \
cross_product(vector(c, a), vector(c, d)) * \
cross_product(vector(c, d), vector(c, b)) >= 0
def do_segments_strongly_intersect(a, b, c, d):
if not do_segments_intersect(a, b, c, d):
return False
if cross_product(vector(a, b), vector(c, d)) == 0:
if a == c:
return not is_point_in_segment(d, a, b) and \
not is_point_in_segment(b, c, d)
if a == d:
return not is_point_in_segment(c, a, b) and \
not is_point_in_segment(b, c, d)
if b == c:
return not is_point_in_segment(d, a, b) and \
not is_point_in_segment(a, c, d)
if c == d:
return not is_point_in_segment(c, a, b) and \
not is_point_in_segment(a, c, d)
return not is_point_in_segment(a, c, d) and \
not is_point_in_segment(b, c, d) and \
not is_point_in_segment(c, a, b) and \
not is_point_in_segment(d, a, b)
def signum(a):
if a < 0:
return -1
elif a == 0:
return 0
else:
return 1
def do_segment_and_hor_ray_intersect(p, a, b):
q = p[0] + 1, p[1]
if b[1] == p[1]:
return False
return signum(cross_product(vector(p, q), vector(p, a))) != \
signum(cross_product(vector(p, q), vector(p, b))) and \
cross_product(vector(p, a), vector(p, b)) > 0
def is_point_in_polygon(p, lst):
num = 0
for i in range(len(lst)):
if is_point_in_segment(p, lst[i - 1], lst[i]):
return True
if lst[i][1] == lst[i - 1][1]:
continue
if lst[i - 1][1] > lst[i][1] and \
do_segment_and_hor_ray_intersect(p, lst[i], lst[i - 1]):
num += 1
elif lst[i - 1][1] < lst[i][1] and \
do_segment_and_hor_ray_intersect(p, lst[i - 1], lst[i]):
num += 1
return (num & 1) == 1
def middle(a, b):
return (a[0] + b[0]) / 2, (a[1] + b[1]) / 2
|
59ad8ccdb912edae17904c8c1aee37990c8c7630 | MUGABA/dataStructures-js | /python-d_and_algo/searchAlgo/linearSearch.py | 184 | 3.78125 | 4 | def linearSeach(array, item):
if not array or not item:
return
for i in range(len(array)):
if array[i] == item:
return 1
return -1
print(linearSeach([1, 99, 45, 3, 7], 8)) |
547584e530bf58418ebdca1316d4f431d4d3c8ac | ClaudioChagas/Introducao-a-Ciencia-da-Computacao-com-Python | /corponumero.py | 181 | 4 | 4 | N = int(input("Digite um número: "))
soma=1
while (N > 0):
resto= N % 2
N= (N - resto)/2
soma= soma + resto
print("A soma dos números é: ", N)
|
916d4869d4849d3e3da1e311664aba88b31692c6 | thephak/twitter_api | /app/twitter_api.py | 3,425 | 3.671875 | 4 | import requests
import urllib.parse
TWITTER_TOKEN = "" # REQUIRED
DEFAULT_LIMIT = 30
TWITTER_API_BASE = "https://api.twitter.com/2"
DEFAULT_TWEET_FIELDS = "author_id,created_at,entities,public_metrics"
class TwitterAPI:
def __init__(
self
):
self.headers = {"Authorization": "Bearer " + TWITTER_TOKEN}
def search_by_hashtag(
self,
hashtag: str,
limit: int
):
"""
To get Tweets by searching from hashtag
:param hashtag: Twitter hashtag
:param limit: Maximum number of tweets fetching. The number must be between 10-100.
:return: Response from Twitter API with data eg. tweet id, text
"""
limit = DEFAULT_LIMIT if (limit == None or limit < 10) else limit
hashtag_parse = urllib.parse.quote_plus(hashtag)
url = TWITTER_API_BASE + "/tweets/search/recent?query=%23" + hashtag_parse + "&max_results=" + str(limit)
print("Sending request to Twitter API: " + url)
response = requests.get(url, headers=self.headers)
return response
def search_by_user(
self,
username: str,
limit: int
):
"""
To get Tweets by searching from user who tweeted
:param username: Twitter username
:param limit: Maximum number of tweets fetching. The number must be between 10-100.
:return: Response from Twitter API with data eg. tweet id, text
"""
limit = DEFAULT_LIMIT if (limit == None or limit < 10) else limit
url = TWITTER_API_BASE + "/tweets/search/recent?query=from:" + username + "&max_results=" + str(limit)
print("Sending request to Twitter API: " + url)
response = requests.get(url, headers=self.headers)
return response
def get_tweets_details(
self,
tweet_ids: list
):
"""
To get Tweets details
:param tweet_ids: list of Tweet id
:return: Response from Twitter API with data eg. created_at, author_id, lang, source, public_metrics, context_annotations, entities
"""
url = TWITTER_API_BASE + "/tweets?ids=" + (','.join(id for id in tweet_ids)) + "&tweet.fields=" + DEFAULT_TWEET_FIELDS
print("Sending request to Twitter API: " + url)
response = requests.get(url, headers=self.headers)
return response
def get_user_details_by_username(
self,
username: str
):
"""
To get Twitter user details
:param username: username of the Twitter user
:return: Response from Twitter API with data eg. user id, name, username
"""
url = TWITTER_API_BASE + "/users/by/username/" + username
print("Sending request to Twitter API: " + url)
response = requests.get(url, headers=self.headers)
return response
def get_user_details_by_id(
self,
userId: str
):
"""
To get Twitter user details
:param userId: user ID of the Twitter user
:return: Response from Twitter API with data eg. user id, name, username
"""
url = TWITTER_API_BASE + "/users/" + userId
print("Sending request to Twitter API: " + url)
response = requests.get(url, headers=self.headers)
return response |
962cf34cdb1d51118014544758c4746c21d11708 | mbuon/Leetcode | /36. Valid Sudoku.py | 1,346 | 3.78125 | 4 | class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
rows = {}
cols = {}
blocks = {}
for i in range(0, len(board)):
for j in range(0, len(board)):
value = board[i][j]
if i not in rows:
rows[i] = {}
if j not in cols:
cols[j] = {}
if (i%3 == 0 and j%3 == 0):
if (i/3, j/3) not in blocks:
blocks[i/3, j/3] = {}
if (board[i][j] == "."):
continue
if ((value in rows[i]) or (value in cols[j]) or (value in blocks[int(i/3), int(j/3)])):
return False
rows[i][value] = True
cols[j][value] = True
blocks[int(i/3), int(j/3)][value] = True
return True
print(Solution().isValidSudoku([
[".",".","4",".",".",".","6","3","."],
[".",".",".",".",".",".",".",".","."],
["5",".",".",".",".",".",".","9","."],
[".",".",".","5","6",".",".",".","."],
["4",".","3",".",".",".",".",".","1"],
[".",".",".","7",".",".",".",".","."],
[".",".",".","5",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."]])) |
8b04a65e25666e033eebe5aafaa3f1507b9548d7 | preston-scibek/Python | /ch7Exercise2.py | 737 | 4.1875 | 4 | __author__ = "Preston Scibek"
# This Python file uses the following encoding: utf-8
#Encapsulate this loop in a function called square_root that takes a as a parameter,
#chooses a reasonable value of x, and returns an estimate of the square root of a.
def square_root(a):
a = float(a)
x = a + 1.0
y = (x + (a/x)) / 2
print "An estimate of the square root of %f = %f" %(a, y)
return y
def bttr_square_root(a, b):
a = float(a)
x = b
y = (x + (a/x)) / 2.0
return y
def better_square_root(a, times):
y = bttr_square_root(a, a+1)
for num in range(times):
y = bttr_square_root(a, y)
return y
#print better_square_root(4, 10)
if __name__ == "__main__":
x = input("Enter number to be rooted: ")
square_root(x) |
00799642a9c66a8fbefc15da04008d5c615a00d3 | sehgalsakshi/Content-Based-Recommendation-System | /preprocess.py | 781 | 3.515625 | 4 | import re
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
#Utitlity functions for removing ASCII characters, converting lower case, removing stop words, html and punctuation from description
def _removeNonAscii(s):
return "".join(i for i in s if ord(i)<128)
def make_lower_case(text):
return text.lower()
def remove_stop_words(text):
text = text.split()
stops = set(stopwords.words("english"))
text = [w for w in text if not w in stops]
text = " ".join(text)
return text
def remove_html(text):
html_pattern = re.compile('<.*?>')
return html_pattern.sub(r'', text)
def remove_punctuation(text):
tokenizer = RegexpTokenizer(r'\w+')
text = tokenizer.tokenize(text)
text = " ".join(text)
return text |
50cc557f481c0756cfb92d9a3253707bebcc80e7 | tnaswin/PythonPractice | /Aug20/argskwargs.py | 1,252 | 3.984375 | 4 | def some_args(arg_1, arg_2, arg_3):
print("arg_1:", arg_1)
print("arg_2:", arg_2)
print("arg_3:", arg_3)
my_list = [2, 3]
some_args(1, *my_list)
def some_kwargs(kwarg_1, kwarg_2, kwarg_3):
print("kwarg_1:", kwarg_1)
print("kwarg_2:", kwarg_2)
print("kwarg_3:", kwarg_3)
print
kwargs = {"kwarg_1": "A", "kwarg_2": "B", "kwarg_3": "C"}
some_kwargs(**kwargs)
###
def multiply(*args):
z = 1
for num in args:
z *= num
print(z)
multiply(4, 5)
multiply(10, 9)
multiply(2, 3, 4)
multiply(3, 5, 10, 6)
print
###
def print_values(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))
print_values(
name_1="Alex",
name_2="Gray",
name_3="Harper",
name_4="Phoenix",
name_5="Remy",
name_6="Val"
)
print
###
def some_args2(arg_1, arg_2, arg_3):
print("arg_1:", arg_1)
print("arg_2:", arg_2)
print("arg_3:", arg_3)
mylist2 = raw_input('Enter your list: ')
mylist2 = [int(x) for x in mylist2.split(',')]
some_args2(1, *my_list2)
def some_kwargs2(kwarg_1, kwarg_2, kwarg_3):
print("kwarg_1:", kwarg_1)
print("kwarg_2:", kwarg_2)
print("kwarg_3:", kwarg_3)
|
55c9d26a3411ce12d84cb21bd769a7cd19aaee4f | priyanshuc4423/snakegame | /scoreboard.py | 1,004 | 3.828125 | 4 | import turtle as t
class ScoreBoard(t.Turtle):
def __init__(self):
super().__init__()
self.hideturtle()
self.point = 0
with open("data.txt",mode="r") as file:
self.high_point = int(file.read())
self.penup()
self.goto(0,280)
self.color("white")
self.score_update()
def add_score(self):
self.point += 1
def score_update(self):
self.clear()
self.write(f"Score = {self.point} High score {self.high_point}",align = "center",font=("Arial", 14, "normal"))
def refresh(self):
if self.point > self.high_point:
self.high_point = self.point
with open("data.txt",mode="w") as file:
file.write(str(self.high_point))
self.point = 0
self.score_update()
# def game_over(self):
# self.goto(0,0)
# self.write("GAME OVER",align="center",font=("Arial", 14, "normal"))
|
6d794be32f19f61cce03a54fa7c3df93bbf9247c | Aish32/data-chronicles | /Preprocessing Structured Data/handling-imbalanced-classes-with-upsampling.py | 1,084 | 3.890625 | 4 | """
In upsampling, for every observation in the majority class,
we randomly select an observation from the minority class with replacement.
The end result is the same number of observations from the minority and majority classes.
"""
# load libraries
import numpy as np
from sklearn import datasets
# load iris data
iris = datasets.load_iris()
# create a feature matrix
x = iris.data
# create a target vector
y = iris.target
# make iris dataset imbalanced
# remove first 40 observations
x = x[40:,:]
y = y[40:]
# create binary target vector indicating if class if 00
y = np.where((y==0), 0, 1)
# indices of each class observations
i_class0 = np.where(y ==0)[0]
i_class1 = np.where(y ==1)[0]
# number of observations in each class
n_class0 = len(i_class0)
n_class1 = len(i_class1)
# for every observation in class 1, randomly sample from class 0 with replacement
i_class0_upsampled = np.random.choice(i_class0, size=n_class1, replace=True)
# join together class 0's upsampled target vector with class 1 target vector
np.concatenate((y[i_class0_upsampled], y[i_class1]))
|
ccbe6b67877e7fbce4206bd759ff12280eeca577 | gogopavl/hadoop-streaming-tasks | /task3/mapper.py | 754 | 3.953125 | 4 | #!/usr/bin/env python2
# task3/mapper.py
import sys
from collections import defaultdict
numberOfActors = 0
def map_function(line):
"""If a person's record contains "actor" or "actress" in their profession field returns 1
Parameters
----------
line : String type
A line from the input stream
Returns
-------
1 : Integer
The occurrence
"""
primaryProfession = line.split("\t")[4].strip()
if ("actor" in primaryProfession) or ("actress" in primaryProfession):
yield 1 # Emit 1 - same reducer, 1 (occurence of actor/actress)
for line in sys.stdin:
for key in map_function(line):
numberOfActors += key # Local sum instead of emitting each occurrence
print(str(numberOfActors))
|
f50bd90ed7c20b46670b66568af84f7227fc80ba | liorch1/learning-python | /100.py | 360 | 3.9375 | 4 | #!/usr/bin/env python36
#####
#name: lior cohen
#date: 11/6/18
#description: get a name and age from the user and tell
#them the year they will turn 100 years old
####
name = str(input("please entar your name: "))
age = int(input("please enter yout age: "))
year = (str((2018 - age) +100))
print("{}, will be 100 years old in the year {}".format(name, year))
|
5fe193f603c26f995005cfb34f6b92f6a1fb29b2 | micjo/snippets | /python/decorating_with_class_function.py | 897 | 3.53125 | 4 | #!/usr/bin/python
class Foo:
def timer(orig_func):
import time
def wrapper():
start_time = time.time()
result = orig_func()
end_time = time.time()
delta_time = end_time - start_time
print "{} ran for {} seconds".format(orig_func.__name__, delta_time)
return wrapper
stat=staticmethod(timer)
# this is equivalent to (second one is more pythonic) :
class Foo:
@staticmethod
def timer(orig_func):
import time
def wrapper():
start_time = time.time()
result = orig_func()
end_time = time.time()
delta_time = end_time - start_time
print "{} ran for {} seconds".format(orig_func.__name__, delta_time)
return wrapper
@Foo.timer
def display():
import time
print "Display Function"
time.sleep(1)
display()
|
c588a13cf4a9bf2b84ddfaf209c9e5a9fe617995 | daniel-reich/ubiquitous-fiesta | /gphnuvoHDANN2Fmca_0.py | 116 | 3.578125 | 4 |
def odd_sort(lst):
odds = iter(sorted(i for i in lst if i%2))
return [next(odds) if n%2 else n for n in lst]
|
977ea5a145764351e0a9d798077fab0176352bc8 | snehahegde1999/sneha | /session-4.py | 93 | 3.75 | 4 | n=7
if n>3:
print ("the condition is true")
if n<5:
print ("the condition is false")
|
c1918447e030eb87fcc464643e6a6c4a8c8c24a1 | DDR7707/Final-450-with-Python | /Arrays/10.Sorting Negative , positive Numbers.py | 1,451 | 4.1875 | 4 | # Loumtors , horesrs algo
def rearrange(arr, n ) :
# Please refer partition() in
# below post
# https://www.geeksforgeeks.org / quick-sort / j = 0
j = 0
for i in range(0, n) :
if (arr[i] < 0) :
temp = arr[i]
arr[i] = arr[j]
arr[j]= temp
j = j + 1
print(arr)
# Driver code
arr = [-1, 2, -3, 4, 5, 6, -7, 8, 9]
n = len(arr)
rearrange(arr, n)
# Two pointer approach
def shiftall(arr,left,right):
# Loop to iterate while the
# left pointer is less than
# the right pointer
while left<=right:
# Condition to check if the left
# and right pointer negative
if arr[left] < 0 and arr[right] < 0:
left+=1
# Condition to check if the left
# pointer element is positive and
# the right pointer element is
# negative
elif arr[left]>0 and arr[right]<0:
arr[left], arr[right] = \
arr[right],arr[left]
left+=1
right-=1
# Condition to check if the left
# pointer is positive and right
# pointer as well
elif arr[left]>0 and arr[right]>0:
right-=1
else:
left+=1
right-=1
# Function to print the array
def display(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
# Driver Code
if __name__ == "__main__":
arr=[-12, 11, -13, -5, \
6, -7, 5, -3, 11]
n=len(arr)
shiftall(arr,0,n-1)
display(arr)
|
fe05844faf110d4bdea209c19263b64f3e3c524b | ArhiTegio/GB-Higher-Mathematics | /Lesson_3/Lesson3.py | 5,216 | 3.609375 | 4 | import matplotlib.pyplot as plt
import numpy as np
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
import math
# Урок 3
# Задание 1.2
# Напишите код на Python, реализующий расчет длины вектора, заданного его координатами. (в программе)
# def LineLengthXY(x1, y1, x2, y2):
# return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
#
#
# def LineLengthXYZ(x1, x2, y1, y2, z1, z2):
# return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2)
#
#
# print('Длина вектора составит: ' + str(LineLengthXY(
# int(input('Введите x1 вектора:')),
# int(input('Введите у1 вектора:')),
# int(input('Введите x2 вектора:')),
# int(input('Введите у2 вектора:'))
# )))
# Задание 2
# Почему прямые не кажутся перпендикулярными? (см.ролик)
# fig, ax_f = plt.subplots()
#
# x = np.linspace(-5, 5, 30)
# k = 6
# y1 = (k * x) + 1
# y2 = (-1/k) * x + 1
#
# ax_f.plot(x, y1)
# ax_f.plot(x, y2)
# n = 5 + x * 0
# ax_f.plot(x, n)
# ax_f.plot(x, -n)
# ax_f.plot(n, x)
# ax_f.plot(-n, x)
# ax_f.set_xlim(-15, 15)
# ax_f.set_ylim(-15, 15)
# ax_f.set_title('Задание 2.')
#
# plt.show()
# Задание 3.1
# Напишите код на Python, реализующий построения окружности
# fig, ax_f = plt.subplots()
#
# x = np.linspace(-5, 5, 100)
# r = 5
# y = (r ** 2 - x ** 2) ** (1/2)
# n = 5 + x * 0
#
# ax_f.plot(x, y)
# ax_f.plot(x, -y)
# ax_f.plot(x, n)
# ax_f.plot(x, -n)
# ax_f.plot(n, x)
# ax_f.plot(-n, x)
# ax_f.set_xlim(-15, 15)
# ax_f.set_ylim(-15, 15)
# ax_f.set_title('Задание 3.1.')
#
# plt.show()
# Задание 3.2
# Напишите код на Python, реализующий построения эллипса
# fig, ax_f = plt.subplots()
#
# x = np.linspace(-5, 5, 100)
# r = 5
# b = 3
# y = (b/r) * (r ** 2 - x ** 2) ** (1/2)
#
# ax_f.plot(x, y)
# ax_f.plot(x, -y)
# n = 5 + x * 0
# ax_f.plot(x, n)
# ax_f.plot(x, -n)
# ax_f.plot(n, x)
# ax_f.plot(-n, x)
# ax_f.set_xlim(-15, 15)
# ax_f.set_ylim(-15, 15)
# ax_f.set_title('Задание 3.2.')
#
# plt.show()
# Задание 3.3
# Напишите код на Python, реализующий построения гиперболы
# fig, ax_f = plt.subplots()
#
# x = np.linspace(-10, 10, 100)
# r = 5
# b = 5
# y = (r ** 2 + x ** 2) ** (1/2)
#
# ax_f.plot(x, y)
# ax_f.plot(x, -y)
# ax_f.set_xlim(-15, 15)
# ax_f.set_ylim(-15, 15)
# ax_f.set_title('Задание 3.3.')
#
# plt.show()
# Задание 5.1
# Нарисуйте трехмерный график двух параллельных плоскостей.
# fig = figure()
# ax = Axes3D(fig)
# X = np.arange(-5, 5, 0.5)
# Y = np.arange(-5, 5, 0.5)
# X, Y = np.meshgrid(X, Y)
# Z = 2*X + 5*Y
# ax.plot_wireframe(X, Y, Z)
# ax.plot_wireframe(X + 1, Y + 1, Z + 1)
# ax.scatter(0, 0, 0, 'z', 50, 'red')
# show()
# Задание 5.2
# Нарисуйте трехмерный график двух любых поверхностей второго порядка.
# fig = figure()
# ax = Axes3D(fig)
# X = np.arange(-3, 3, 0.5)
# Y = np.arange(-7, 7, 0.5)
# a = 2
# b = 4
# X, Y = np.meshgrid(X, Y)
# Z = (X ** 2/a ** 2) - (Y ** 2/b ** 2)
# ax.plot_wireframe(X, Y, Z)
# ax.scatter(0, 0, 0, 'z', 50, 'red')
# show()
# Задание 1
# Нарисуйте график функции: y(x) = k∙cos(x – a) + b
# fig, ax_f = plt.subplots()
#
# x = np.linspace(-5, 5, 100)
# y1 = 1 * np.cos(x - 2) + 3
# y2 = 3 * np.cos(x - 2) + 1
# y3 = 2 * np.cos(x - 4) + 2
#
# ax_f.plot(x, y1)
# ax_f.plot(x, y2)
# ax_f.plot(x, y3)
# ax_f.set_xlim(-15, 15)
# ax_f.set_ylim(-15, 15)
# ax_f.set_title('Задание 1.')
#
# plt.show()
# Задание 3
# Напишите код, который будет переводить полярные координаты в декартовы.
# r = 5
# a = 1 #угол в радианах
# x = r * math.cos(a)
# y = r * math.sin(a)
# print("x = " + str(x))
# print("y = " + str(y))
# Напишите код, который будет рисовать график окружности в полярных координатах.
# a = np.linspace(0, 2*math.pi, 50)
# r = 10
# x = r * np.cos(a)
# y = r * np.sin(a)
#
# plt.plot(x, y)
# plt.show()
#
# #Напишите код, который будет рисовать график отрезка прямой линии в полярных координатах.#
# x = np.linspace(0, 10, 50)
# a = math.pi / 4
# y = x * np.sin(a)
#
# plt.plot(x, y)
# plt.show()
# Задание 4
# 4.1 Решите систему уравнений:
# x = np.linspace(-10, 10, 50)
#
# y1 = x ** 2 - 1
# y2 = (np.exp(x) + x)/-x
#
#
# plt.plot(x, y1)
# plt.plot(x, y2)
# plt.show()
# 4.2 Решите систему уравнений:
# x1 = np.linspace(-500, 500, 300)
# y1 = x1 ** 2 - 1
# xy = [[_x, (np.exp(_x) + _x) / - _x] for _x, _y in zip(x1, x1) if math.exp(_x) + _x * (_x - (math.exp(_x) + _x)/-_x) > 1]
# x2 = [x for x, y in xy]
# y2 = [y for x, y in xy]
#
# plt.plot(x1, y1)
# plt.plot(x2, y2)
#
# plt.show() |
ad56824ffee92a92048ba8e22b75b9e55aa99d48 | WAT36/procon_work | /procon_python/src/atcoder/arc/past/B_026.py | 298 | 3.671875 | 4 | import math
n=int(input())
divisor=[]
for i in range(1,int(math.sqrt(n)//1)+1):
if(n%i==0):
divisor.append(i)
divisor.append(n//i)
#print(divisor)
sum_div=sum(set(divisor))-n
if(sum_div<n):
print("Deficient")
elif(sum_div>n):
print("Abundant")
else:
print("Perfect") |
3cb618b5cc690c85d0e1ecd9e27f817e3791b3dd | gaoi311/python_learning | /day26/4.转义符.py | 582 | 3.71875 | 4 | # 正则表达式中的转义 :
# '\(' 表示匹配小括号
# [()+*?/$.] 在字符组中一些特殊的字符会现出原形
# 所有的 \w \d \s(\n,\t, ) \W \D \S都表示它原本的意义
# [-]只有写在字符组的首位的时候表示普通的减号
# 写在其他位置的时候表示范围[1-9]
# 如果就是想匹配减号 [1\-9]
# python中的转义符
# 分析过程
'\n' # \转义符 赋予这个n一个特殊的意义 表示一个换行符
# print('\\n')
# print\\n('C:\\next')
# print(r'C:\next')
# '\\\\n' '\\n'
# 结论
# r'\\n' r'\n' 在python中
|
07a6252f51ff3c179ef3dcee4cd0cd33cb8db813 | nanduvankam/DSP-LAB | /Day1/leapif.py | 190 | 3.953125 | 4 | n=input("enter year=");
if (n%4==0):
print n,"is leap year"
elif (n%100==0):
print n,"is not a leap year"
elif (n%400==0):
print n,"is leap year"
else:
print n,"is not leap year" |
665468a26c2a4d8a27757314ee3ec8ae722f29d5 | jjsalomon/python-analytics | /numpy/numpy1 - Checks and Generation.py | 2,237 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 13 16:48:11 2017
This script is for learning about numpy library for Data Science Projects
@author: azkei
"""
# importing NumPy module withing Python session
import numpy as np
# Using ndarray - the heart of the library
a = np.array([1,2,3])
# Checking the newly created object thats an ndarray
type(a)
# Checking the associated data type of the ndarray
a.dtype
# Checking the axis of the ndarray
a.ndim
# Checking the array length
a.size
# Checking the shape attribute of the array
a.shape
# More Examples
b = np.array([0.234,0.1234,0.1234])
c = np.array([[0.2, 0.4, 0.3],[0.2,0.5,0.1]])
d = np.array([[3.212,5.123512,32.12351, 22.3244522,2.2345,233331,233],
[988.2331,3231.34422334,22334.2221,233.21123],
[23.3333,2124.2333,2123321.23333,22.2]])
# defines the size of each bytes of item in the array
d.itemsize
# Buffer containing the aactual elements of the array.
d.data
# Numpy arrays can contain a wide variety of data types
# e.g. String
stringArray = np.array([['a','b'],['c','d']],dtype = '|S1')
stringArray.dtype
stringArray.dtype.name
# The Array function does not just accept a single argument.
# You can use the dtype option to define an array with complex values
f = np.array([[1,2,3],[4,5,6]],dtype = complex)
# Intrinsic creation of an Array
# The NumPy library provides a set of functions that generate the ndarrays with an initial content
# with values depending on the function
# Generate a 3x3 ndarry with 0 values
np.zeros((3,3))
# Generate a 3x3 ndarray with 1 values
np.ones((3,3))
# It's also possible to generate a sequence of values with precise intervals
np.arange(0,12,3)
# The third argument can even be a float
np.arange(0,6,0.3)
# So far you've only generated one dimensional arrays
# You can add reshape() to add extra dimensions
np.arange(0,6,0.5).reshape(3,4)
# Another function similar to arange() is linspace()
# This function still takes the first 2 arguments as the range
# However the third argument defines the number of elements we want to split
np.linspace(0,6,5)
# Lastly another way to fill an array with values is with numpy.random
np.random(3)
# Add extra dimensions
np.random.random((3,3))
|
a14d2a5d5ae5a39147973299e29bacc0f9d8d4fe | fbarneda/pythonProjects | /Blackjack Game/main.py | 7,905 | 4.21875 | 4 | """
This is the Blackjack game
"""
import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10,
'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11}
playing = True
class Card:
# This method is used to initialize the attributes of an object, passed as arguments
def __init__(self, card_suit, card_rank, card_value):
# The card has 3 attributes
self.card_suit = card_suit
self.card_rank = card_rank
self.card_value = card_value
def __str__(self):
return self.card_rank + " of " + self.card_suit + ", value " + str(self.card_value)
class Deck:
def __init__(self):
# Only one attribute is needed here
self.my_deck_of_52_cards = []
# Creating Card objects and appending them to the list attribute
for suit in suits:
for rank in ranks:
self.my_deck_of_52_cards.append(Card(suit, rank, values[rank]))
# Shuffling the deck, now they are not ordered
Deck.shuffle(self)
def __str__(self):
string = ""
for card in self.my_deck_of_52_cards:
string += (card.card_rank + " of " + card.card_suit + ", value " + str(card.card_value) + "\n")
return string
def shuffle(self):
random.shuffle(self.my_deck_of_52_cards)
def deal(self):
self.my_deck_of_52_cards.pop(0)
return self.my_deck_of_52_cards[0]
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def __str__(self):
string = ""
for card in self.cards:
string += ("\t" + card.card_rank + " of " + card.card_suit + ", value " + str(card.card_value) + "\n")
return string
def add_card(self, card):
self.cards.append(card)
self.value += card.card_value
if card.card_value == 11:
self.aces += 1
Hand.adjust_for_ace(self)
def adjust_for_ace(self):
# Aces will never be higher than 1, since we are checking the value in every card_add
if self.value > 21 and self.aces == 1:
self.value -= 10
self.aces = 0
class Chips:
def __init__(self):
self.total = 100
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
def take_a_bet(chips):
print("\nChips available: " + str(chips.total) + "\n")
while True:
try:
cust_bet = int(input("How much you wanna bet? "))
except:
print("Enter a number and try again.")
continue
else:
if cust_bet > chips.total:
print("You don't have enough chips available to bet this amount. ")
continue
elif cust_bet <= 0:
continue
else:
chips.bet = cust_bet
print("\nBet accepted! Good luck!")
break
def hit(deck, hand):
hand.add_card(deck.deal())
def hit_or_stand(deck, hand):
global playing
while True:
try:
if hand.value <= 21:
action = input("Do you wanna HIT[H] or STAND[S]? ")
else:
break
except:
print("Enter a valid action and try again.")
continue
else:
if action.upper() == "H":
hit(deck, hand)
break
elif action.upper() == "S":
playing = False
break
else:
print("Enter a valid action and try again.")
continue
def show_some(player_hand, dealer_hand):
print("\n** PLAYER CARDS -- Total value: " + str(player_hand.value))
print(player_hand)
print("** DEALER CARDS")
string = ""
for card in dealer_hand.cards[1:]:
string += ("\t" + card.card_rank + " of " + card.card_suit + ", value " + str(card.card_value) + "\n")
print(string)
def show_all(player_hand, dealer_hand):
print("+" * 50)
print("\n** PLAYER CARDS -- Total value: " + str(player_hand.value))
print(player_hand)
print("** DEALER CARDS -- Total value: " + str(dealer_hand.value))
print(dealer_hand)
print("+" * 50)
def player_busts(final_chips):
print("PLAYER BUSTED - You lost your " + str(final_chips.bet) + "chips bet")
final_chips.lose_bet()
def player_wins(final_chips):
print("PLAYER WINS - You won your " + str(final_chips.bet) + "chips bet")
final_chips.win_bet()
def dealer_busts(final_chips):
print("PLAYER WINS - You won your " + str(final_chips.bet) + "chips bet")
final_chips.win_bet()
def dealer_wins(final_chips):
print("DEALER WON - You lost your " + str(final_chips.bet) + "chips bet")
final_chips.lose_bet()
def push(final_chips):
print("IT'S A PUSH - You keep your " + str(final_chips.bet) + "chips bet")
def wanna_play_again():
while True:
try:
x = input("\nDo you wanna play again? Yes[Y] / No[N] ")
except:
print("Please enter a valid option")
else:
if x.upper() == "Y":
break
elif x.upper() == "N":
break
else:
continue
return x.upper()
if __name__ == "__main__":
# Print an opening statement
print("\n" + "*" * 50)
print("Welcome to the BlackJack Game")
print("*" * 50)
# Set up the Player's chips
chips = Chips()
while True:
# Create & shuffle the deck,
deck = Deck()
# Deal two cards to each player
player_hand = Hand()
player_hand.add_card(deck.deal())
player_hand.add_card(deck.deal())
# Deal two cards to each player
dealer_hand = Hand()
dealer_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
# Prompt the Player for their bet
take_a_bet(chips)
# Show cards (but keep one dealer card hidden)
show_some(player_hand, dealer_hand)
while playing: # recall this variable from our hit_or_stand function
# Prompt for Player to Hit or Stand
hit_or_stand(deck, player_hand)
# Show cards (but keep one dealer card hidden)
show_some(player_hand, dealer_hand)
# If player's hand exceeds 21, break out of loop
if player_hand.value > 21:
break
# If Player hasn't busted, play Dealer's hand until Dealer reaches 17
while dealer_hand.value <= 17 and player_hand.value <= 21:
dealer_hand.add_card(deck.deal())
# Show all cards
show_all(player_hand, dealer_hand)
# Run different winning scenarios
if player_hand.value > 21:
player_busts(chips)
elif (player_hand.value <= 21) and (player_hand.value > dealer_hand.value):
player_wins(chips)
elif (dealer_hand.value <= 21) and (dealer_hand.value > player_hand.value):
dealer_wins(chips)
elif (dealer_hand.value > 21) and (player_hand.value <= 21):
dealer_busts(chips)
elif dealer_hand.value == player_hand.value:
push(chips)
# Inform Player of their chips total
print("Your total chips are " + str(chips.total))
# Ask to play again
play_again = wanna_play_again()
if play_again == "Y":
if chips.total == 0:
print("\nSorry, you ran out of chips, no chips no play, bye!")
break
else:
playing = True
continue
else:
break |
e23bb744472afc4a44c1253dec7890a14dd70cdc | SeanPeer/Ex3_OOP | /tests/Test_G.py | 1,449 | 3.921875 | 4 | from DiGraph import DiGraph
def build_graph(name="g"):
print(f"Creating Graph {name}:")
g = DiGraph()
print("adding nodes [0,4] \n"
"adding edges: [0,1], [0,2], [1,2], [2,3] ,[3,4]")
for i in range(5):
g.add_node(i)
g.add_edge(0, 1, 1)
g.add_edge(0, 2, 1)
g.add_edge(1, 2, 2)
g.add_edge(2, 3, 3)
g.add_edge(3, 4, 5)
return g
def test_g():
g = build_graph()
print(f"Test: add existing node -> (false) = {g.add_node(0)}")
print(f"Test: add existing edge -> (false) = {g.add_edge(0, 1, 1)}")
print("removing edge 0 -> 1")
g.remove_edge(0, 1)
print(f"Test: remove non-existing edge -> (false) = {g.remove_edge(0, 1)}")
print(f"Test: edge to a non-existing node -> (false) = {g.add_edge(0, 50, 5)}")
print("removing node 0")
g.remove_node(0)
print(f"Test: add node after node removal -> (true) = {g.add_node(0)}")
print(f"Test: add edge after node removal -> (true) = {g.add_edge(0, 1, 2)}")
print(f"Test: print graph -> (|V|=5 , |E|=4) -> = {g}")
g = build_graph()
g_copy = build_graph("g_copy")
print(f"Test: copy of graph -> (|V|=5 , |E|=5) -> = {g_copy}")
print(f"Test: equals for a copy -> (true) = {g == g_copy}")
g_copy.remove_node(0)
print(f"Test: equals after change -> (false) = {g == g_copy}")
if __name__ == '__main__':
test_g()
|
f235024fa26be8992292125e8dda449454fe9393 | XuShaoming/CompVision_ImageProc | /project1/code/task1.py | 5,801 | 3.578125 | 4 | import numpy as np
import cv2
import math
import mynumpy as mnp
VERTICAL_SOBEL_3BY3 = np.array([[1,0,-1],
[2,0,-2],
[1,0,-1]])
HORIZONTAL_SOBEL_3BY3 = np.array([[1,2,1],
[0,0,0],
[-1,-2,-1]])
def texture_filtering(img_gray, kernel):
"""
Purpose:
use to filter the gray image given the kernel
Input:
img_gray:
an two dimension ndarray matrix, dtype:usually is uint8 representint the gray image.
kernel:
a two dimension ndarray matrix
Output:
The filtered image without padding around.
"""
row_pad = math.floor(kernel.shape[0] / 2)
col_pad = math.floor(kernel.shape[1] / 2)
img_gray = np.ndarray.tolist(img_gray)
img_gray = np.asarray(mnp.pad(img_gray, row_pad, row_pad, col_pad, col_pad, 0))
img_res = np.asarray(mnp.zeros(img_gray.shape[0], img_gray.shape[1]))
flipped_kernel = np.asarray((mnp.flip(np.ndarray.tolist(kernel))))
for i in range(row_pad, img_gray.shape[0] - row_pad):
for j in range(col_pad, img_gray.shape[1] - col_pad):
patch = mnp.inner_product(img_gray[i-row_pad:i+row_pad+1, j-col_pad:j+col_pad+1], flipped_kernel)
img_res[i,j] = mnp.sum_all(patch)
return img_res[row_pad: img_res.shape[0] - row_pad, col_pad:img_res.shape[1] - col_pad]
def eliminate_zero(img, method=1):
"""
Purpose:
two ways to eliminate the negative value or the value out of 255.
Input:
img: two dimension matrix
the raw image. dtype usually is float64 with pixel < 0 or pixel > 255
method: int
default is 1 which directs to first method
the 2 will direct to the second method.
Output:
a matrix dtype range zero to one.
"""
if method == 1:
return (img - mnp.min_all(img)) / (mnp.max_all(img) - mnp.min_all(img))
elif method == 2:
return np.asarray(mnp.abs_all(img)) / mnp.max_all(mnp.abs_all(img))
else :
print("method is 1 or 2")
# magnitude of edges (conbining horizontal and vertical edges)
def magnitude_edges(edge_x, edge_y):
"""
Purpose:
Combine the vertical image and horizontal image.
Input:
edge_x: two dimension matrix
the image filted by VERTICAL_SOBEL
edge_y: two dimension matrix
the image filted by HORIZONTAL_SOBEL
Output:
edge_magnitude: two dimension matrix
the image combined by edge_x and edge_y
"""
edge_magnitude = np.sqrt(edge_x ** 2 + edge_y ** 2)
edge_magnitude /= mnp.max_all(edge_magnitude)
return edge_magnitude
def direction_edge(edge_x, edge_y):
edge_direction = np.arctan(edge_y / (edge_x + 1e-3)) * 180. / np.pi
edge_direction /= mnp.max_all(edge_direction)
return edge_direction
if __name__ == "__main__":
img = cv2.imread("../task1_img/task1.png", 0)
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
name = "../task1_img" + "/image" + ".png"
cv2.imwrite(name, img)
# Computing vertical edges
edge_x = texture_filtering(img,VERTICAL_SOBEL_3BY3)
cv2.namedWindow('edge_x_dir', cv2.WINDOW_NORMAL)
cv2.imshow('edge_x_dir', edge_x)
cv2.waitKey(0)
cv2.destroyAllWindows()
name = "../task1_img" + "/edge_x" + ".png"
cv2.imwrite(name, edge_x)
# Eliminate zero values with method 1
pos_edge_x_1 = eliminate_zero(edge_x, 1)
cv2.namedWindow('pos_edge_x_dir', cv2.WINDOW_NORMAL)
cv2.imshow('pos_edge_x_dir', pos_edge_x_1)
cv2.waitKey(0)
cv2.destroyAllWindows()
name = "../task1_img" + "/pos_edge_x_1" + ".png"
cv2.imwrite(name, pos_edge_x_1 * 255)
# Eliminate zero values with method 2
pos_edge_x_2 = eliminate_zero(edge_x, 2)
cv2.namedWindow('pos_edge_x_dir', cv2.WINDOW_NORMAL)
cv2.imshow('pos_edge_x_dir', pos_edge_x_2)
cv2.waitKey(0)
cv2.destroyAllWindows()
name = "../task1_img" + "/pos_edge_x_2" + ".png"
cv2.imwrite(name, pos_edge_x_2 * 255)
# Computing horizontal edges
edge_y = texture_filtering(img,HORIZONTAL_SOBEL_3BY3)
cv2.namedWindow('edge_y_dir', cv2.WINDOW_NORMAL)
cv2.imshow('edge_y_dir', edge_y)
cv2.waitKey(0)
cv2.destroyAllWindows()
name = "../task1_img" + "/edge_y" + ".png"
cv2.imwrite(name, edge_y)
# Eliminate zero values with method 1
pos_edge_y_1 = eliminate_zero(edge_y, 1)
cv2.namedWindow('pos_edge_y_dir', cv2.WINDOW_NORMAL)
cv2.imshow('pos_edge_y_dir', pos_edge_y_1)
cv2.waitKey(0)
cv2.destroyAllWindows()
name = "../task1_img" + "/pos_edge_y_1" + ".png"
cv2.imwrite(name, pos_edge_y_1 * 255)
# Eliminate zero values with method 2
pos_edge_y_2 = eliminate_zero(edge_y, 2)
cv2.namedWindow('pos_edge_y_dir', cv2.WINDOW_NORMAL)
cv2.imshow('pos_edge_y_dir', pos_edge_y_2)
cv2.waitKey(0)
cv2.destroyAllWindows()
name = "../task1_img" + "/pos_edge_y_2" + ".png"
cv2.imwrite(name, pos_edge_y_2 * 255)
# magnitude of edges (conbining horizontal and vertical edges)
edge_magnitude = magnitude_edges(edge_x, edge_y)
cv2.namedWindow('edge_magnitude', cv2.WINDOW_NORMAL)
cv2.imshow('edge_magnitude', edge_magnitude)
cv2.waitKey(0)
cv2.destroyAllWindows()
name = "../task1_img" + "/edge_magnitude" + ".png"
cv2.imwrite(name, edge_magnitude * 255)
edge_direction = direction_edge(edge_x, edge_y)
cv2.namedWindow('edge_direction', cv2.WINDOW_NORMAL)
cv2.imshow('edge_direction', edge_direction)
cv2.waitKey(0)
cv2.destroyAllWindows()
name = "../task1_img" + "/edge_direction" + ".png"
cv2.imwrite(name, edge_direction * 255)
print("Original image size: {:4d} x {:4d}".format(img.shape[0], img.shape[1]))
print("Resulting image size: {:4d} x {:4d}".format(edge_magnitude.shape[0], edge_magnitude.shape[1]))
|
860e71bd4526e21b3dc7bc103f0a34c06cc52340 | KAU93/hhhomework | /core/classes.py | 1,284 | 4.09375 | 4 | class Car:
# Реализовать класс машины Car, у которого есть поля: марка и модель автомобиля
# Поля должны задаваться через конструктор
def __init__(self, mark, model):
self.mark = mark
self.model = model
class Garage:
# Написать класс гаража Garage, у которого есть поле списка машин
# Поле должно задаваться через конструктор
# По аналогии с классом Company из лекции реализовать интерфейс итерируемого
# Реализовать методы add и delete(удалять по индексу) машин из гаража
def __init__(self, listCar):
if type(listCar) == type([]):
self.listCar = listCar
else:
print("Передан не правильный тип данных")
exit
def __len__(self):
return len(self.listCar)
def __getitem__(self, position):
return self.listCar[position]
def add(self, car):
self.listCar.append(car)
def delete(self, index):
del self.listCar[index]
|
7635fbfbdf3f8639c31e6f1a6c6f6e0f33f71256 | Alogenesis/Basic-Python-Udemy | /21ForLoop.py | 1,478 | 4.09375 | 4 | # For Loop are repeat every single thing in list[]
blog_post = ['The 10 Coolest math functions in Python',
'How to make HTTP requests in Python',
'A tutorial about data type in Python']
for post in blog_post:
print(post)
sep = '-------------------------------'
print(sep)
# use continue to skip the step of the loop
blog_post = ['',
'The 10 Coolest math functions in Python',
'',
'How to make HTTP requests in Python',
'A tutorial about data type in Python']
for post in blog_post:
print(post)
print(sep)
# using continue to skip '' blank
for post in blog_post:
if post == '':
continue
print(post)
print(sep)
myString = 'This is my String'
for char in myString:
print(char)
print(sep)
for x in range(0,10):
print(x)
print(sep)
person = {'Name' : 'Karen Smith', 'Age': 25 , 'Gender' : 'female'} # 3 Element
for i in person:
print(i, ':' , person[i]) #i just a variable and ':' just seperator text
print(sep)
#list in dict
blog_post = {'Python' : ['The 10 Coolest math functions in Python',
'How to make HTTP requests in Python',
'A tutorial about data type in Python'],
'Javascript' : ['Namespace in Javasript', 'New function available']}
for catagory in blog_post:
print('Post about', catagory)
for post in blog_post[catagory]:
print(post)
print(sep) |
a7206a21c98268ead84e302bec276d973d52b0ab | xLuis190/Python-School-work | /fib.py | 246 | 3.625 | 4 | def fib(n):
previous, result = 0 , 1;
x = 0
while(x < n -1):
temp = result
result = previous + result
previous = temp
x = x +1;
return result;
fib(8)
|
5e8a626435c65238b03db48eef3127cb100f2752 | 91xie/FYP2 | /Archive/DateTimeCheck1.py | 846 | 3.765625 | 4 | # keep adding a random number to a list of numbers
# if a timer constant is exceeded, process the data
# see what you get
from datetime import datetime, date, time, timedelta
import time
from random import randint
deltamin = 1
now = datetime.now()
now_plus_delta = now + timedelta(minutes = deltamin)
print "now " + str(now)
print "later" + str(now_plus_delta)
alist = []
while True:
if datetime.now() < now_plus_delta:
##append values to a list
print "if statement entered"
print datetime.now()
alist.append(randint(1,10))
else:
#process the list and then clear it.
#seem straightforward enough.
print "else statement entered"
print alist
alist = []
now = now_plus_delta
now_plus_delta = now + timedelta(minutes = deltamin)
time.sleep(5)
|
ae0f11eae522ca9dfaf5f59f79414d7e4cc5c249 | davll/practical-algorithms | /LeetCode/1-two_sum.py | 762 | 3.5625 | 4 | def two_sum_v1(nums, target):
lut = {}
for i in range(len(nums)):
if nums[i] in lut:
return [lut[nums[i]], i]
else:
lut[target - nums[i]] = i
def two_sum_v2(nums, target):
n = len(nums)
index = list(range(n))
index.sort(key = lambda i: nums[i])
l, r = 0, n-1
while l < r:
i, j = index[l], index[r]
if nums[i] + nums[j] == target:
return [i, j]
elif nums[i] + nums[j] < target:
l += 1
else: # nums[i] + nums[j] > target
r -= 1
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
return two_sum_v2(nums, target)
|
ecf247561a725796ad3aec445ec1398e16e521be | yaolinxia/algorithm | /a常用函数python汇总.py | 1,018 | 3.90625 | 4 | # 给定一个字符串,转化为列表
"""
2,3,4,1
['2', '3', '4', '1']
[2, 3, 4, 1]
"""
def str2list(s="[2,3,4,1]"):
s_cut = s[1:-1]
print(s_cut)
s_l = s_cut.strip().split(',')
print(s_l)
l = []
for c in s_l:
l.append(int(c))
print(l)
# 字典里面基于字进行排序
def sorted_dict(d={"a":3, "f":5, "b":6}):
s_d = sorted(d, key=lambda i:d[i])
print(s_d)
# 按照字符串的第一个字母进行对整个字符串对排序
def sorted_s(l=["delphi" ,"Delphi" ,"python" ,"Python" ,"c++" ,"C++" ,"c" ,"C" ,"golang" ,"Golang"]):
l.sort(key=lambda s: s[0])
print(l)
def test():
from functools import reduce
def fn(m,n):
return m*10+n
print(reduce(fn, [8,9,5,6,3,2]))
def match_str(source="我是中国人", word="中国人"):
print(source.find(word))
# if source.find(word):
# print(source.replace("中国人", "zhongguoren"))
if __name__ == '__main__':
# str2list()
# sorted_dict()
# test()
match_str() |
d92122d3b8c292c1fbd66dc23cee18dec4afcf70 | anshu0157/AlgorithmAndDataStructure | /AlgorithmAndDatastructure_Python/DataStructure/1_LinkedList.py | 1,613 | 3.828125 | 4 | class Node :
def __init__(self, data, next=None):
self.data = data
self.next = next
def init():
global node1
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node1.next = node2
node2.next = node3
node3.next = node4
def delete(del_data):
global node1
# 1. 지운 뒤 앞노드와 뒷노드를 연결하기 위해 앞노드의 정보 저장
pre_node = node1
next_node = pre_node.next
# 2. delete
# 2_1. 지울 노드가 시작 node라면
if pre_node.data == del_data:
# node1의 다음 노드가 node1이 되고
node1 = next_node
# 원래의 node1은 delete!
del pre_node
return
# 2_2. next_node가 존재할때까지만 while
while next_node:
# 다음 노드가 삭제 대상 노드라면
if next_node.data == del_data:
# 현재 노드(pivot node) 다음 노드의 next로 저장 (즉, 현재 노드의 다음을 수정)
pre_node.next = next_node.next
# 삭제 대상 노드를 삭제하고 while문 종료
del next_node
break
# pivot 이동
pre_node = next_node
next_node = next_node.next
# 추가하기 ( node1 앞 쪽에 추가 )
def insert(ins_data):
global node1
new_node = Node(9, node1)
node1 = new_node
def print_list():
global node1
pv_node = node1
while pv_node:
print(pv_node.data)
pv_node = pv_node.next
def LinkedList():
init()
delete(2)
insert("9")
print_list()
LinkedList()
|
31edd7da1a77ccacf1fc06a43b15207be088dc01 | chuanyuj/product | /product.py | 495 | 3.8125 | 4 | products = [] # 有一個叫做 products 的空清單
while True: # 進入迴圈
name = input('請輸入商品名稱:') # 請使用者輸入商品名稱,創建為 name
if name == 'q': # 如果使用者輸入 q
break # 離開程式
price = input('請輸入商品價格:') # 請使用者輸入商品價格,創建為 price
products.append([name, price]) # 把 p 這個清單裝到 products 這個清單裡
print(products)
products[0][0] # products 清單的第 0 格中的第 0 格 |
792be0535b784a2eadfbaf2f150c5d0b5d9e59d5 | TungTNg/itc110_python | /Assignment/pizzaCalculator.py | 902 | 4.5625 | 5 | # pizzaCalculator.py
# A program to calculate the cost per square inch of a circular
# by Tung Nguyen
import math
def main():
# declare program function:
print("This program calculates the cost per square inch of a pizza.")
print()
# prompt user to input the pizza diameter in inches:
diameter = float(input("Enter the diameter of the pizza (in inches): "))
# prompt user to input the price of the pizza in cents:
price = float(input("Enter the price of the pizza (in cents): "))
# conversion formular (I googled the formular for a circle's area => A=1/4πd^2)
# then cost per square inch will be price/area:
area = 1/4 * math.pi * math.pow(diameter, 2)
cost = price / area
# print out result that was calculated & rounded to the first decimal point:
print()
print("The cost is", round(cost, 2), "cents per square inch.")
main() |
940d1334f74438e609f0e25255fbe6c722c506f5 | Mamonter/GB_les_Petryaeva | /bas/less4/ex5.py | 794 | 4.15625 | 4 | #Реализовать формирование списка, используя функцию range() и возможности генератора.
#В список должны войти четные числа от 100 до 1000 (включая границы).
#Необходимо получить результат вычисления произведения всех элементов списка.
#Подсказка: использовать функцию reduce().
from functools import reduce
def my_func(el_1, el_2):
return el_1 * el_2
my_list = [i for i in range(100, 1001, 2)]
print(f'Четные числа от 100 до 1000 {my_list}')
print(f'Вычисления произведения всех элементов списка {reduce(my_func, my_list)}') |
c641a2f9241152be9c8f1eb96892772300f34827 | swathythadukkassery/60DaysOfCode | /Backtracking/knight.py | 981 | 3.796875 | 4 | def possible(board,rownew,colnew,n):
if(rownew>=0 and rownew<n) and(colnew>=0 and colnew<n) and board[rownew][colnew]==0:
return True
return False
def find(board,n,move,row,col):
rowInc=[2,1,-1,-2,-2,-1,1,2]
colInc=[1,2,2,1,-1,-2,-2,-1]
if move==(n**2):
for i in range(n):
print(board[i])
return True
else:
for i in range(n):
rownew=row+rowInc[i]
colnew=col+colInc[i]
if possible(board,rownew,colnew,n):
move+=1
board[rownew][colnew]=move
if(find(board,n,move,rownew,colnew)):
return True
move-=1
board[rownew][colnew]=0
return False
def start(n):
board=[[0 for x in range(n)]for y in range(n)]
move=1
board[0][0]=1
if find(board,n,move,0,0)==True:
print(board)
else:
print("np")
n=int(input())
start(n) |
7173544be821a1ec4e5df9c9907debf09ee4e2a5 | tonabarrera/problemas | /fibo.py | 189 | 3.5625 | 4 | def fib(n):
a,b = 1,1
contador = ''
for i in range(n-1):
a,b = b,a+b
if a > n:
break
contador = contador + '%s ' % a
return contador
k = int(raw_input())
print fib(k) |
e542e3ae5324e91c5420cfa66bb7dbd878fd5009 | apoorvaagrawal86/PythonLetsKodeIt | /PythonLetsKodeIt/Basic Syntax/numbers.py | 192 | 3.875 | 4 | int_num = 10
float_num = 20.0
print(int_num)
print(float_num)
a = 10
b = 20
print("*********")
add = a+b
print(add)
sub = b - a
print(sub)
mul = a*b
print(mul)
div = b/a
print(div) |
5b42d22a4e26e93ef4bcf9e6d2bd3e14df50e74d | cjstaples/morsels | /snippets/all_unique/unique.py | 153 | 3.5625 | 4 | def is_all_unique(lst):
return len(lst) == len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
is_all_unique(x) # False
is_all_unique(y) # True |
3a625245a43638e3fba0179872f91907385d8958 | davidcoxch/PierianPython | /6_Methods_and_Functions/paper_doll.py | 373 | 4.1875 | 4 | """
PAPER DOLL: Given a string, return a string where for every character in the original there are three characters¶
paper_doll('Hello') --> 'HHHeeellllllooo'
paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'
"""
def paper_doll(text):
st = ''
for x in text:
st = st + x*3
return st
print(paper_doll('Hello'))
print(paper_doll('Mississippi')) |
cb28c7cbabfd134ac2eb312cd65252394de02e51 | TetianaHrunyk/DailyCodingProblems | /challenge7.py | 470 | 4 | 4 | def is_char(code):
return 0 if code > 26 or code < 1 else 1
def decode(code):
code_str = str(code)
if len(code_str) == 1:
count = 1
elif len(code_str) == 2:
count = 1 + is_char(code)
else:
count = decode(int(code_str[1:]))
if is_char(int(code_str[:2])):
count += decode(int(code_str[2:]))
return count
if __name__ == '__main__':
assert decode(123) == 3
assert decode(1311) == 4
|
dd26253d30182bf69a27068ac02f6c4dd48c2043 | qmnguyenw/python_py4e | /geeksforgeeks/algorithm/hard_algo/5_19.py | 6,844 | 3.71875 | 4 | Program to generate all possible valid IP addresses from given string | Set 2
Given a string containing only digits, restore it by returning all possible
valid IP address combinations.
A valid IP address must be in the form of **A.B.C.D** , where **A** , **B** ,
**C** and **D** are numbers from **0 – 255**. The numbers cannot be **0**
prefixed unless they are **0**.
**Examples:**
> **Input:** str = “25525511135”
> **Output:**
> 255.255.11.135
> 255.255.111.35
>
> **Input:** str = “11111011111”
> **Output:**
> 111.110.11.111
> 111.110.111.11
## Recommended: Please try your approach on **__{IDE}__** first, before moving
on to the solution.
**Approach:** This problem can be solved using backtracking. In each call we
have three options to create a single block of numbers of a valid ip address:
1. Either select only a single digit, add a dot and move onto selecting other blocks (further function calls).
2. Or select two digits at the same time, add a dot and move further.
3. Or select three consecutive digits and move for the next block.
At the end of the fourth block, if all the digits have been used and the
address generated is a valid ip-address then add it to the results and then
backtrack by removing the digits selected in the previous call.
Below is the implementation of the above approach:
## C++
__
__
__
__
__
__
__
// C++ implementation of the approach
#include <iostream>
#include <vector>
using namespace std;
// Function to get all the valid ip-addresses
void GetAllValidIpAddress(vector<string>& result,
string givenString, int index,
int count, string ipAddress)
{
// If index greater than givenString size
// and we have four block
if (givenString.size() == index && count == 4) {
// Remove the last dot
ipAddress.pop_back();
// Add ip-address to the results
result.push_back(ipAddress);
return;
}
// To add one index to ip-address
if (givenString.size() < index + 1)
return;
// Select one digit and call the
// same function for other blocks
ipAddress = ipAddress
+ givenString.substr(index, 1) + '.';
GetAllValidIpAddress(result, givenString, index + 1,
count + 1, ipAddress);
// Backtrack to generate another poosible ip address
// So we remove two index (one for the digit
// and other for the dot) from the end
ipAddress.erase(ipAddress.end() - 2, ipAddress.end());
// Select two consecutive digits and call
// the same function for other blocks
if (givenString.size() < index + 2
|| givenString[index] == '0')
return;
ipAddress = ipAddress + givenString.substr(index, 2) + '.';
GetAllValidIpAddress(result, givenString, index + 2,
count + 1, ipAddress);
// Backtrack to generate another poosible ip address
// So we remove three index from the end
ipAddress.erase(ipAddress.end() - 3, ipAddress.end());
// Select three consecutive digits and call
// the same function for other blocks
if (givenString.size() < index + 3
|| stoi(givenString.substr(index, 3)) > 255)
return;
ipAddress += givenString.substr(index, 3) + '.';
GetAllValidIpAddress(result, givenString, index + 3,
count + 1, ipAddress);
// Backtrack to generate another poosible ip address
// So we remove four index from the end
ipAddress.erase(ipAddress.end() - 4, ipAddress.end());
}
// Driver code
int main()
{
string givenString = "25525511135";
// Fill result vector with all valid ip-addresses
vector<string> result;
GetAllValidIpAddress(result, givenString, 0, 0, "");
// Print all the generated ip-addresses
for (int i = 0; i < result.size(); i++) {
cout << result[i] << "\n";
}
}
---
__
__
## Python3
__
__
__
__
__
__
__
# Python3 implementation of the approach
# Function to get all the valid ip-addresses
def GetAllValidIpAddress(result, givenString,
index, count, ipAddress) :
# If index greater than givenString size
# and we have four block
if (len(givenString) == index and count == 4) :
# Remove the last dot
ipAddress.pop();
# Add ip-address to the results
result.append(ipAddress);
return;
# To add one index to ip-address
if (len(givenString) < index + 1) :
return;
# Select one digit and call the
# same function for other blocks
ipAddress = (ipAddress +
givenString[index : index + 1] + ['.']);
GetAllValidIpAddress(result, givenString, index + 1,
count + 1, ipAddress);
# Backtrack to generate another poosible ip address
# So we remove two index (one for the digit
# and other for the dot) from the end
ipAddress = ipAddress[:-2];
# Select two consecutive digits and call
# the same function for other blocks
if (len(givenString) < index + 2 or
givenString[index] == '0') :
return;
ipAddress = ipAddress + givenString[index:index + 2] +
['.'];
GetAllValidIpAddress(result, givenString, index + 2,
count + 1, ipAddress);
# Backtrack to generate another poosible ip address
# So we remove three index from the end
ipAddress = ipAddress[:-3];
# Select three consecutive digits and call
# the same function for other blocks
if (len(givenString)< index + 3 or
int("".join(givenString[index:index + 3])) > 255) :
return;
ipAddress += givenString[index:index + 3] + ['.'];
GetAllValidIpAddress(result, givenString,
index + 3, count + 1, ipAddress);
# Backtrack to generate another poosible ip address
# So we remove four index from the end
ipAddress = ipAddress[:-4];
# Driver code
if __name__ == "__main__" :
givenString = list("25525511135");
# Fill result vector with all valid ip-addresses
result = [] ;
GetAllValidIpAddress(result, givenString, 0, 0, []);
# Print all the generated ip-addresses
for i in range(len(result)) :
print("".join(result[i]));
# This code is contributed by Ankitrai01
---
__
__
**Output:**
255.255.11.135
255.255.111.35
Attention reader! Don’t stop learning now. Get hold of all the important DSA
concepts with the **DSA Self Paced Course** at a student-friendly price and
become industry ready. To complete your preparation from learning a language
to DS Algo and many more, please refer **Complete Interview Preparation
Course** **.**
My Personal Notes _arrow_drop_up_
Save
|
444e1da5d03416dafbaf831c109362c761b3afb3 | tobiasjpalacios/TP2-AED | /Tiempo.py | 573 | 3.53125 | 4 | import time
#import random
inicio = time.time()
ahora = inicio
fin = inicio + 240
#turno = (fin - inicio)
#print(turno)
while (ahora < fin):
actual = int(ahora - inicio)
if actual > 180:
hora = 4
#print("Hora 4 Minuto", actual)
elif actual > 120:
hora = 3
#print("Hora 3 Minuto", actual)
elif actual > 60:
hora = 2
#print("Hora 2 Minuto", actual)
else:
hora = 1
#print("Hora 1 Minuto", actual)
#print(actual)
time.sleep(1)
ahora = time.time()
|
6fc50fbcdc621b69437752cbdff1150d42ebf558 | LucasGVallejos/Master-en-MachineLearning-y-RedesNeuronales | /01-PrincipiosYFundamentosDePython/09-Listas.py | 695 | 3.75 | 4 | sabores = ["chocolate","crema americana","vainilla", True, 20]
sabores2 = ["chocolate amargo","CREMA del CIELO", False, -20]
print("\nla lista contiene: ",sabores)
print("\nen la posicion 4 esta: ", sabores[4])
elementoEliminado = sabores.pop(4)
print("\nel elemento que se elimino es: ",elementoEliminado)
print("la lista contiene: ",sabores)
sabores.append("DDL")
print("\nagregamos el dulce de leche")
print("la lista contiene: ",sabores)
sabores.insert(0,"Heladeria EL VALLE")
print("\nAgregamos el nombre de la heladeria al comienzo de la lista")
print("la lista contiene: ",sabores)
print("\nAgregamos nuevos valores de otra lista")
sabores.extend(sabores2)
print("la lista contiene: ",sabores)
|
746f99ba639120f73fd8457a7a418eb8ac8e6133 | gsrr/leetcode | /leetcode/823. Binary Trees With Factors.py | 4,203 | 3.78125 | 4 | '''
Method1
這個問題直覺想法就是bottom-up的暴力法方式.
一個兩個for loop的方式, 但會遇到一個問題,
那就是新增加的值要如何再與前面的值相乘?
(append? 那會造成list亂掉, 所以只好新增一個新的list來儲存)
然後重跑迴圈, 繼續將這個list互乘, 直到list不會再增加為止.
Method2
感覺只是對array裡面的值一直在互乘而已, 所以用dictionary來存次數.
Method3
感覺並不需要新的dp, 也就是可以拿掉外面迴圈.
(但array需要先sort, 這樣的話, 前面乘就代表該值已經固定了)
ex: 若6之前的人都已經乘完, 那代表6最多就是目前這個次數.
所以就從6開始乘所有的人即可
不對, 後面做的會影響前面 --> 像3 * 2 = 6, 6 * 2 = 12這個case就算不到.
[2, 3, 6, 12]
其實可以用遞迴: 12 = (2 * 6), 所以只要確認6的方法數.
而6 = (2 * 3), (3 * 2)
Top - Down method.
'''
import collections
def ans1(arr):
'''
Brute force method
Result : Time expired
Time complexity: O(logn * n^2)
The inner loop is n^2 + (n + n/2) * (n + n/2) + (n + n/2 + n/4) * (n + n/2 + n/4) + ...--> O(n^2)
The outer loop is logn because minval is 2, so the candidate will be remove half at least for every loop.
Space complexity : O(n^2) in dictionary to store pairs.
'''
dic = collections.Counter(arr)
arr.sort()
base = list(arr)
pre = 0
cur = len(base)
while pre != cur:
tmp = []
n = len(base)
#print base
for i in xrange(n):
for j in xrange(n):
v1 = base[i]
v2 = base[j]
if dic.has_key(v1 * v2):
tmp.append(v1 * v2)
pre = cur
base = arr + tmp
cur = len(base)
return len(base)
def ans2(arr):
'''
Speedup from brute force method
Result : Accept
Time complexity :
Outer loop : O(logn)
Inner loop : n/2 * n/2 + n/2 * n/2 + ... --> O(n^2)
'''
base = 10 ** 9 + 7
arr.sort()
dp = collections.Counter(arr)
cands = []
for i in xrange(len(arr)):
for j in xrange(len(arr)):
v1 = arr[i]
v2 = arr[j]
val = v1 * v2
if val > arr[-1]:
break
if dp.has_key(v1 * v2):
cands.append([v1, v2])
pre = 0
cur = len(arr)
cnt = 0
while pre != cur:
pre = cur
cur = 0
ndp = {}
for cand in cands:
v1 = cand[0]
v2 = cand[1]
val = (v1 * v2 )
if ndp.has_key(val) == False:
ndp[val] = (dp[v1] * dp[v2])
else:
ndp[val] += (dp[v1] * dp[v2])
ndp[val] = ndp[val] % base
for i in xrange(len(arr)):
if ndp.has_key(arr[i]) == False:
ndp[arr[i]] = 0
ndp[arr[i]] += 1
cur += ndp[arr[i]]
dp = ndp
cnt += 1
return sum(dp.values()) % base
def ans(arr):
'''
Speedup from brute force method
Result : Accept
Time complexity :
Outer loop : O(logn)
Inner loop : n/2 * n/2 + n/2 * n/2 + ... --> O(n^2)
'''
base = 10 ** 9 + 7
arr.sort()
dp = collections.Counter(arr)
print arr
for i in xrange(len(arr)):
for j in xrange(len(arr)):
v1 = arr[i]
v2 = arr[j]
val = v1 * v2
if val > arr[-1]:
break
if dp.has_key(v1 * v2):
print v1, v2
dp[val] += (dp[v1] * dp[v2])
print dp
return sum(dp.values()) % base
class Solution(object):
def numFactoredBinaryTrees(self, A):
"""
:type A: List[int]
:rtype: int
"""
return ans2(A)
|
f679bda14e06f181042000c8406ffc076bf2040a | aalsher/CodingProgression | /Python/ScoresAndGrades.py | 441 | 3.734375 | 4 | import random
random_num = random.randint(60,100)
def ScoresAndGrades(random_num):
if random_num >= 60 and random_num <= 69:
grade = "D"
if random_num >= 70 and random_num <= 79:
grade = "C"
if random_num >= 80 and random_num <= 89:
grade = "B"
if random_num >= 90 and random_num <= 100:
grade = "A"
print "Score:", random_num, ";", "Your grade is", grade
ScoresAndGrades(random_num) |
edd453776f5ce410e2d3ccf8468347acf5d3da09 | arun5061/Python | /Revision/input_for.py | 311 | 3.671875 | 4 | list=[]
x=int(input('Enter no of students:'))
for i in range(x):
list.append(input('Enter student name{}:'.format(i)))
print(list)
d=dict()
s=0
for j in list:
val=input('Enter value{}:'.format(s))
s+=1
d[j]=val
print('d:',d)
for k,v in d.items():
print('Key:',k,'\t','value:',v)
|
2a9ac6b28f0e209758a71741f4601682856db8f8 | morawer/practicaNate1 | /ejercicio1.py | 365 | 3.828125 | 4 |
frase_usuario = input("Introduce un texto: ")
simbolos = [" ", ".", ","]
espacio = 0
punto = 0
coma = 0
for caracter in frase_usuario:
if caracter is " ":
espacio += 1
elif caracter is ".":
punto += 1
elif caracter is ",":
coma += 1
print("El texto contiene {} espacios, {} puntos y {} comas.".format(espacio, punto, coma))
|
b84616ed8b95f93e5cb7aff57c22d1ed6d86570f | marshallgrimmett/CS-undergrad-projects | /principlesProg2/topic6/dynamicStrong.py | 651 | 3.671875 | 4 | # Python is dynamic and strong typed
# Strong typing in Python
print "The answer is " + 7
# Runtime error
# Problems with dynamic
myVariable = 7
myVaraible = myVariable + 10
print myVariable
# When run prints: 7
# This is because we created another variable 'myVaraible' (spelling mistake)
# Some dynamic languages can simulate static languages (i.e. Perl with 'strict')
my_variable = 10
while my_variable > 0:
i = foo(my_variable)
if i < 100:
my_variable++
else
my_varaible = (my_variable + i) / 10
document.write("The answer is " + 7);
|
300bf4aa09cb9e9b48bcbf088a3d6176fab41cf8 | zhoucong2/python- | /exercises/week_exe.py | 184 | 3.640625 | 4 | y=["星期一","星期二","星期三","星期四","星期五","星期六","星期天"]
s=int(input("请输入数字"))
if s in range(1,8):
print(y[s-1])
else:
print("无效")
|
7e3bd6e77106881622b9a89c6dcd0f54b55cee1a | alex-moffat/Python-Projects | /Tkinter Phonebook/SQL_functions.py | 3,518 | 3.625 | 4 | # PYTHON: 3.8.2
# AUTHOR: Alex Moffat
# PURPOSE: General use SQLite3 functions
"""
TAGS:
SQL, sqlite3.version, error handling, connect, cursor, execute, CREATE, INSERT, SELECT
slice, upper, fetchall, isinstance, ValueError as
"""
# ============================================================================
#===== IMPORTED MODULES
import sqlite3
#========== CONNECT - establish connection to DB and print sqlite3 version
def dbConnect(db):
conn = None
try:
conn = sqlite3.connect(db) # creates a db if one does not exist
print(sqlite3.version)
except ValueError as e:
print("DB Connection Error: {}".format(e))
finally:
if conn: conn.close() # close db connection if open
#========== USE CONNECTION - establish connetion to DB and return open connection
def dbUse(db):
conn = None
try:
conn = sqlite3.connect(db) # creates a db if one does not exist
except ValueError as e:
print("DB Connection Error: {}".format(e))
return conn
#========== EXECUTE - pass database and a non-parameterized SQL statement
def sqlExecute(db, statement):
conn = dbUse(db)
if conn != None: #===== EXECUTE
try:
cur = conn.cursor() # creates cursor object 'cur'
cur.execute(statement)
switch = statement[slice(0,6)].upper()
if switch == 'SELECT': #===== SELECT
dataset = cur.fetchall()
if conn: conn.close()
return dataset
else:
conn.commit()
r = "record"
if cur.rowcount > 1: r = "records"
if switch == 'UPDATE': #===== UPDATE
printStr = "{} {} updated in database {}".format(cur.rowcount, r, db)
elif switch == 'DELETE': #===== DELETE
printStr = "{} {} deleted in database {}".format(cur.rowcount, r, db)
elif switch == 'INSERT': #===== INSERT
printStr = "{} {} inserted in database {}".format(cur.rowcount, r, db)
else:
printStr = "Execute complete in database {}".format(db)
print(printStr)
except ValueError as e:
print("DB Execute Error: {}".format(e))
finally:
if conn: conn.close()
else:
print("DB Connection Error...cannot execute SQL statement")
#========== INSERT - can pass SQL db, table statement, values statement (can be single tuple or list of tuples)
def sqlInsert(db, statement, iValue):
conn = dbUse(db)
if conn != None: #===== INSERT
try:
cur = conn.cursor() # creates cursor object
if isinstance(iValue, list): #===== MULTIPLE ROW INSERT
cur.executemany(statement, iValue)
conn.commit()
print(cur.rowcount, " records inserted.")
elif isinstance(iValue, tuple): #===== SINGLE ROW INSERT
cur.execute(statement, iValue)
conn.commit()
print(cur.rowcount, " record inserted.")
else:
print("DB INSERT Error: Values are not formatted correctly - need list or tuple")
except ValueError as e:
print("DB INSERT Error: {}".format(e))
finally:
if conn: conn.close()
else:
print("DB Connection Error...cannot execute SQL statement")
if __name__ == '__main__':
pass
|
cfe32eb727b56a5eb301261f3cc3d7a0a0b25ea6 | ashi1994/PythonPractice | /PythonOops/VariablePython.py | 443 | 3.84375 | 4 | '''
Created on May 19, 2018
@author: aranjan
'''
'''
In Python when you want to use the same variable for rest of your program or module you declare
it a global variable,
while if you want to use the variable in a specific function or method, you use a local variable.
'''
class VarTest:
a=101
print(a)
def locaLFunction(self):
a="heloo java"
print(a)
obj=VarTest()
obj.locaLFunction() |
d201f4f9ac0f383d07451a860327a06e50ebc778 | mytwenty19/weight_tracker | /date_utils.py | 3,146 | 3.671875 | 4 | from datetime import date
import datetime
import dateutil.parser
import csv
import pandas as pd
import calendar
import matplotlib.pyplot as plt
# Define a function that converts a date to a string
def date2str(date_obj):
return date_obj.isoformat()
# Define a function that converts a date string to a date object
def str2date(date_str):
date_time = dateutil.parser.parse( date_str )
return date_time.date()
# Define a function that returns a string representing todays date
def today2str():
today = datetime.date.today()
return today.isoformat()
# Define a function that writes all days in the year to file
def write_weights_file(year, file_name):
start = datetime.date(year, 1, 1)
end = datetime.date(year, 12, 31)
step = datetime.timedelta(days=1)
with open(file_name, 'w') as csvfile:
day_writer = csv.writer(csvfile)
while start <= end:
day_writer.writerow([start.isoformat()] + ['NaN'])
start += step
# Define a function to read weights file as a DataFrame
def read_weights_file(file_name):
data_frame = pd.read_csv(file_name,header=None, names=['act_weight'],parse_dates=True)
return data_frame
# Select a part of the data frame
def select_by_date(data_frame, from_date_str, to_date_str):
from_date = str2date(from_date_str)
to_date = str2date(to_date_str)
step = datetime.timedelta(days=1)
date_list = []
while from_date <= to_date:
date_list.append(from_date)
from_date += step
return data_frame.loc[date_list]
# Define a function to write monthly goal weights file
def write_goal_file(year, goal_weights, file_name):
assert len(goal_weights)==12, "Expected goal_weights to have 12 elements."
with open(file_name, 'w') as csvfile:
goal_writer = csv.writer(csvfile)
for month in range(1,13):
month_range = calendar.monthrange(year, month)
goal_wt = goal_weights[month-1]
for day in range(1,month_range[1]+1):
day_date = datetime.date(year, month, day)
goal_writer.writerow([day_date.isoformat(), goal_wt])
# Define a function to read goal weights file as a DataFrame
def read_goal_file(file_name):
data_frame = pd.read_csv(file_name,header=None, names=['goal_weight'], parse_dates=True)
return data_frame
# Define function to generate plot for weights
def save_weight_progress_for_month(img_name, month_num):
act_wts = read_weights_file('2019_weights.csv')
goal_wts = read_goal_file('2019_goal_weights.csv')
year = 2019
wts = act_wts.join(goal_wts)
rng = calendar.monthrange(year, month_num)
start = datetime.date(2019, month_num,1)
end = datetime.date(2019, month_num, rng[1])
step = datetime.timedelta(days=1)
date_list = []
while start <= end:
date_list.append(start)
start += step
selected_wts = wts.loc[date_list]
ax = selected_wts.plot()
ax.set_title('Weight Progress Chart')
ax.set_xlabel('2019')
ax.set_ylabel('Weight (lbs)')
ax.set_ylim(150, 200)
plt.savefig(img_name) |
5b8c03f05910c635e28c9084ee5ebfaa417d44cd | mwesigwapita/AIMB | /server/helpers/password_hasher.py | 467 | 3.546875 | 4 | # Import libraries
from Crypto.Hash import SHA256
# Class that hashes the password
class PasswordHasher:
def hash_password(self, password: str, salt: str = None) -> str:
# Create salted password
if (salt):
salted_password = str.encode(password + salt)
else:
salted_password = str.encode(password)
# Create hash
hash = SHA256.new(salted_password)
# Return
return hash.hexdigest() |
23d9d18d27f1a18d08beee5dc348801ad42192c3 | Apologise/Python_sublime | /第八章/8-9魔术师.py | 253 | 3.640625 | 4 | magicians = ['杨浩','刘谦','我','我']
def make_great(lists):
for i in range(len(lists)):
lists[i] = "The Great" + lists[i]
def show_magicians():
for i in range(len(magicians)):
print(magicians[i])
make_great(magicians[:])
show_magicians() |
a649cf0242341e4828c337092c5c6e07ac63cea6 | Slawak1/pands-problem-set | /plotfunction.py | 847 | 3.703125 | 4 | # Problem No 10
# Problem No. 9
# Slawomir Sowa
# Date: 11.02.2019
# Write a program that displays a plot of the functions x, x2 and 2x in the range [0, 4].
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0,4.0,0.2) # NumPy arange() function returns evenly spaced numeric value with step 0.2
# functions calculated
f1 = x
f2 = x**2
f3 = 2**x
# print (type(f1))
plt.plot(x,f1, 'r',x,f2, 'g', x,f3,'b' ) # plot chart, different colour of lines assigned to each function
# Setup chart
plt.title ('Chart x, $x^2$, $2^x$ in range (0,4)') # Title of chart
plt.xlabel('X axis') # X axis and Y axis description
plt.ylabel('Y axis')
plt.legend(['f1 = x', 'f2 = $x^2$', 'f3 = $2^x$'], loc='upper left') # Legend of Chart
plt.grid (True) # shows grid on chart
plt.show() # shows chart window
|
8c348ff9bd810a51e2271a5b402c23edbeada4ff | fitrepoz/810A | /810A/test.py | 363 | 3.515625 | 4 | import re
def main():
filename = "hw5_text.txt"
output = ''
with open(filename) as f:
for line in f:
if line.rstrip().endswith('\\'):
next_line = next(f)
line = line.rstrip()[:-1] + next_line
output += line
if __name__ == "__main__":
main() |
ed4a89966ff99e2a41125bdee54bf3f0d284794f | All4nXp/Tarea_06 | /Tarea 6 final.py | 1,519 | 3.8125 | 4 | #encoding: UTF-8
#Autor: Allan Sánchez Iparrazar
def cazeriaInsectos():
dias = 0
insectosCazados = 0
faltantes = 30
while faltantes <= 30 :
insectos = int(input("Numero de Insectos cazados hoy"))
insectosCazados = insectosCazados + insectos
dias = dias + 1
faltantes = faltantes - insectos
if faltantes < 0 :
faltantes = faltantes * -1
print("Despues de ",dias,"dias recolectaste",insectosCazados,"\nLograste tu meta con",faltantes,"insectos de mas")
print("\n")
faltantes = 31
else :
print("Despues de ",dias,"dias recolectaste",insectosCazados,"insectos, te faltan",faltantes,"insectos para llegar a la meta")
def calcularMayor():
x = 0
y = 0
while y != -1:
y = int(input("Ingresa un numero, presiona -1 para salir:\n"))
if y == -1 and x == 0 :
print("No hay datos para encontrar el mayor numero\n")
elif y > x :
x = y
elif y == -1 :
print("El mayor numero tecleado es:",x)
def main():
menu = int(input("1. Cazeria de insectos\n2. Calcular mayor \n3. Salir\n"))
while menu != 8 :
if menu == 1 :
cazeriaInsectos()
elif menu == 2 :
calcularMayor()
elif menu == 0 :
print("1. Cazeria de insectos\n2. Calcular mayo\n3. Salir")
menu = int(input("Ingresa una nueva opcion, si deseas ver el menu presiona 0\n"))
if menu==3:
print("Gracias y adios")
menu = 8
main()
|
5f8e6e2b03f9e0d7cafe6a621e8e53d38223d647 | anlutfi/MScCode | /Space.py | 12,574 | 3.5625 | 4 | ##@package Space
# File containing Cell, Grid and GameSpace class definitions
from GameObject import GameObject
X = 0
Y = 1
Z = 2
D3 = 3
D2 = 2
cellassert = "Cell."
class Cell:
"""a Grid object's cell"""
def __init__(self, xb, xe, yb, ye):
"""Cell.__init__(self, xb, xe, yb, ye)
Initialization function for a Cell Object
xb is xbegin
xe in xend
same for yb and ye
"""
fassert = cellassert + "__init__(). "
assert xb.__class__ == float, fassert + "xb not float"
assert xe.__class__ == float, fassert + "xb not float"
assert yb.__class__ == float, fassert + "xb not float"
assert ye.__class__ == float, fassert + "xb not float"
##x begin, lowest x coordinate that is in the cell
self.xb = xb
##x end, highest x coordinate that is in the cell
self.xe = xe
##y begin, lowest y coordinate that is in the cell
self.yb = yb
##y end, highest y coordinate that is in the cell
self.ye = ye
##List of GameObjects (GameObject) currently in the Cell
self.gameobjects = []
def center(self):
"""Cell.center(self)
Returns the (X, Y) coordinate of the Cell's center point
"""
return ( (self.xb + self.xe) / 2, (self.yb + self.ye) / 2, 0 )
def addObject(self, obj):
"""Cell.addObject(obj)
adds a GameObject obj to the cell's gameobjects[].
Returns True for success and False for failure
"""
fassert = cellassert + "addObject()."
assert obj.getSuperClassName() == 'GameObject', fassert + "obj not instance of GameObject"
if obj not in self.gameobjects:
self.gameobjects.append(obj)
return True
return False
def removeObject(self, obj):
"""Cell.removeObject(obj)
removes a GameObject obj from the cell's gameobjects[].
"""
try:
self.gameobjects.remove(obj)
return True
except ValueError:
return False
def getObjects(self):
"""Cell.getObjects()
returns a list of game objects located in the Cell
"""
return self.gameobjects
def introduction(self):
"""Generates a JSON friendly dictionary with
all the object's attributes and values.
This function is intended as a first introduction of the object,
to receivers that are unaware of its existence.
"""
return {"class": self.__class__.__name__,
"xb": self.xb,
"xe": self.xe,
"yb": self.yb,
"ye": self.ye,
"gameobjects": [obj.objid for obj in self.gameobjects]
}
def catchingUp(self):
"""Generates a JSON friendly dictionary with
all the object's attributes and values.
This function is intended as a update on the object's state,
sent to receivers that are already able to identify the object.
"""
return self.introduction()
gridassert = "Grid."
class Grid:
"""Class that divides a GameSpace object's floor plane in a grid"""
def __init__(self, xmin, xmax, ymin, ymax, cellsize):
"""Grid.___init(xmin, xmax, ymin, ymax, cellsize)
Initialization Function for a Grid object
xmin is the lowest x coordinate
xmax is the highest x coordinate
ymin is the lowest y coordinate
ymax is the highest y coordinate
cellsize is the size of each cell
"""
fassert = gridassert + "__init__(). "
assert xmin.__class__ == float, fassert + "xmin not float"
assert xmax.__class__ == float, fassert + "xmax not float"
assert ymin.__class__ == float, fassert + "ymin not float"
assert ymax.__class__ == float, fassert + "ymax not float"
assert cellsize.__class__ == float, fassert + "cellsize not float"
assert xmax - xmin >= cellsize, fassert + "a single cell does not fit in the grid (xmax - xmin >= cellsize)"
assert ymax - ymin >= cellsize, fassert + "a single cell does not fit in the grid (ymax - ymin >= cellsize)"
##The size of a Cell
self.cellsize = cellsize
##The lowest x coordinate in the Grid
self.xmin = xmin
##The highest x coordinate in the Grid
self.xmax = xmax
##The lowest y coordinate in the Grid
self.ymin = ymin
##The highest y coordinate in the Grid
self.ymax = ymax
##Grid's Cell matrix
self.g = [ [Cell(i * cellsize, i * cellsize + cellsize,
j * cellsize, j * cellsize + cellsize
)
for j in range( int( ( self.ymax - self.ymin ) / cellsize ) )
] for i in range( int( ( self.xmax - self.xmin ) / cellsize ) )
]
def getGridPosition(self, pos):
"""Grid.getGridPosition(pos)
cell coordinates of a given 3d or 2d position pos
"""
#assert pos.__class__ == numpy.ndarray, fassert + "pos not numpy.ndarray"
return ( int(pos[X] / self.cellsize), int(pos[Y] / self.cellsize) )
def getCellObjects(self, x, y):
"""Grid.getCellObjects(x, y)
return the list of GameObjects in the x,y cell
"""
try:
return self.g[x][y].getObjects()
except IndexError:
return None
def introduction(self):
"""Generates a JSON friendly dictionary with
all the object's attributes and values.
This function is intended as a first introduction of the object,
to receivers that are unaware of its existence.
"""
return {"class": self.__class__.__name__,
"xmin": self.xmin,
"xmax": self.xmax,
"ymin": self.ymin,
"ymax": self.ymax,
"cellsize": self.cellsize,
"g": dict( [((i, j), self.g[i][j].introduction())
for i in range( int( (self.xmax - self.xmin)
/ self.cellsize
)
)
for j in range( int( (self.ymax - self.ymin)
/ self.cellsize
)
)
]
)
}
def catchingUp(self):
"""Generates a JSON friendly dictionary with
all the object's attributes and values.
This function is intended as a update on the object's state,
sent to receivers that are already able to identify the object.
"""
return {"class": self.__class__.__name__,
"xmin": self.xmin,
"xmax": self.xmax,
"ymin": self.ymin,
"ymax": self.ymax,
"cellsize": self.cellsize,
"g": dict( [((i, j), self.g[i][j].catchingUp())
for i in range( int( (self.xmax - self.xmin)
/ self.cellsize
)
)
for j in range( int( (self.ymax - self.ymin)
/ self.cellsize
)
)
]
)
}
gamespaceassert = "GameSpace."
class GameSpace:
"""Class that defines the game's 3d coordinate system"""
def __init__(self,
xmin,
xmax,
ymin,
ymax,
zmin,
zmax,
origin = (0, 0, 0),
cellsize = 0.0
):
"""GameSpace.__init__(xmin,
xmax,
ymin,
ymax,
zmin,
zmax,
origin,
cellsize = 0.0
)
Initialization Function for a GameSpace Object
xmin is the lowest x coordinate
xmax is the highest x coordinate
ymin is the lowest y coordinate
ymax is the highest y coordinate
zmin is the lowest z coordinate
zmax is the highest z coordinate
origin is a tuple (x,y,z) that sets the systems origin
cellsize is the size of a cell in a grid to be superimposed over the floor.
a zero size indicates there will be no grid
"""
fassert = gamespaceassert + "__init__(). "
assert xmin.__class__ == float, fassert + "xmin not float"
assert xmax.__class__ == float, fassert + "xmax not float"
assert ymin.__class__ == float, fassert + "ymin not float"
assert ymax.__class__ == float, fassert + "ymax not float"
assert zmin.__class__ == float, fassert + "zmin not float"
assert zmax.__class__ == float, fassert + "zmax not float"
#assert origin.__class__ == numpy.ndarray, fassert + "origin not numpy.ndarray"
assert cellsize.__class__ == float, fassert + "cellsize not float"
assert (xmin <= xmax), fassert + "xmin < xmax"
assert (ymin <= ymax), fassert + "ymin < ymax"
assert (zmin <= zmax), fassert + "zmin < zmax"
assert (len(origin) == D3
and xmin <= origin[X] <= xmax
and ymin <= origin[Y] <= ymax
and zmin <= origin[Z] <= zmax
), fassert + "invalid origin"
assert cellsize >= 0, fassert + "invalid cellsize"
##Lowest x coordinate in GameSpace
self.xmin = xmin
##Highest x coordinate in GameSpace
self.xmax = xmax
##Lowest y coordinate in GameSpace
self.ymin = ymin
##Highest y coordinate in GameSpace
self.ymax = ymax
##Lowest z coordinate in GameSpace
self.zmin = zmin
##Highest z coordinate in GameSpace
self.zmax = zmax
##3D origin of GameSpace
self.origin = origin
##An object of Class Grid.
#If not None, it divides the GameSpace's ground plane in Cell's
self.grid = None
if cellsize != 0:
self.grid = Grid(xmin, xmax, ymin, ymax, cellsize)
def introduction(self):
"""Generates a JSON friendly dictionary with
all the object's attributes and values.
This function is intended as a first introduction of the object,
to receivers that are unaware of its existence.
"""
return {"class": self.__class__.__name__,
"xmin": self.xmin,
"xmax": self.xmax,
"ymin": self.ymin,
"ymax": self.ymax,
"zmin": self.zmin,
"zmax": self.zmax,
"origin": self.origin,
"grid": None if self.grid == None else self.grid.introduction()
}
def catchingUp(self):
"""Generates a JSON friendly dictionary with
all the object's attributes and values.
This function is intended as a update on the object's state,
sent to receivers that are already able to identify the object.
"""
return {"class": self.__class__.__name__,
"xmin": self.xmin,
"xmax": self.xmax,
"ymin": self.ymin,
"ymax": self.ymax,
"zmin": self.zmin,
"zmax": self.zmax,
"origin": self.origin,
"grid": None if self.grid == None else self.grid.catchingUp()
}
|
59809770870b0cd2b7f77a209987aa9d94900feb | DavidCichy/w05_si | /exercises.py | 3,244 | 4.28125 | 4 | import poker_hand_logic
def most_frequent_number_in_array(array):
'''
Check what is the most frequent number in an array.
>>> most_frequent_number_in_array([3, 3, 3, 2, 2, 2, 4, 4])
3
>>> most_frequent_number_in_array([3, 3, 3, 5, 5, 5, 7, 7, 0, 2, 2, 2])
5
'''
array.sort()
dict_of_array = {}
highest_number_frequency = 0
for number in array:
if number in dict_of_array.keys():
dict_of_array[number] +=1
else:
dict_of_array[number] = 1
for number in dict_of_array:
if dict_of_array[number] >= highest_number_frequency:
highest_number_frequency = dict_of_array[number]
most_frequent_number = number
return most_frequent_number
def cyclic_rotation(input_string, rotation):
'''
Calculate a cyclic rotation of a string;
i.e. move the last N elements from the end to the beginning.
For example, cyclic_rotation('abcde', 2) should return 'deabc'.
>>> cyclic_rotation('abcde', 2)
'deabc'
>>> cyclic_rotation('abvba', 5)
'abvba'
>>> cyclic_rotation('abcde', -2)
'cdeab'
'''
string_list = list(input_string)
string_len = len(input_string)
string_last_index = string_len - 1
new_string_list = list(input_string)
string_character_id = 0
new_string = ""
for character in string_list:
new_string_character_id = string_character_id + rotation
if new_string_character_id > string_last_index:
new_string_character_id -= string_len
new_string_list[new_string_character_id] = str(character)
string_character_id += 1
new_string = ''.join(new_string_list)
return new_string
def poker_hand(cards_on_hand):
'''
Write a poker_hand function that will score a poker hand.
The function will take an array 5 numbers and
return a string based on what is inside.
It should recognize the following patterns:
five five of a kind [1, 1, 1, 1, 1]
four four of a kind [2, 2, 2, 2, 3]
three three of a kind [1, 1, 1, 2, 3]
twopairs two pairs [2, 2, 3, 3, 4]
pair a single pair [1, 2, 2, 3, 4]
fullhouse a pair and a three [1, 1, 2, 2, 2]
nothing none of the above [1, 2, 3, 4, 6]
>>> poker_hand([1, 1, 1, 1, 1])
'five'
>>> poker_hand([2, 2, 2, 2, 3])
'four'
>>> poker_hand([2, 2, 3, 3, 4])
'twopairs'
>>> poker_hand([2, 2, 2, 3, 4])
'three'
>>> poker_hand([1, 2, 2, 3, 4])
'pair'
>>> poker_hand([1, 1, 2, 2, 2])
'fullhouse'
>>> poker_hand([1, 2, 3, 4, 6])
'nothing'
'''
cards_dict = poker_hand_logic.make_dictonary_of_hand(cards_on_hand)
if poker_hand_logic.check_if_five(cards_dict):
return 'five'
elif poker_hand_logic.check_if_four(cards_dict):
return 'four'
elif poker_hand_logic.check_if_fullhouse(cards_dict):
return 'fullhouse'
elif poker_hand_logic.check_if_three(cards_dict):
return 'three'
elif poker_hand_logic.check_if_twopairs(cards_dict):
return 'twopairs'
elif poker_hand_logic.check_if_pair(cards_dict):
return 'pair'
else:
return 'nothing' |
8c6832edb946dd22e78330a981126b275a448f0b | TianyuYang/ZOLA | /Math 480Hw5.py | 1,279 | 3.84375 | 4 | Homework 5
Part 1
# this is a method that can calculate large number mod faster
def modular_exponent(base, exponent, mod):
exponent = bin(exponent)[2:][::-1]
x = 1
power = base % mod
for i in range(0, len(exponent)):
if exponent[i] == '1':
x = (x * power) % mod
power = (power ** 2) % mod
return x
n = 4654252230393111226989449826741007006486078009450861095070222439898324342353927553909251532232407850265642079868425916328810273416481567992145162141358151
m = n-1
(modular_exponent(2,m,n))
#Output: 1631275335353718272688521136992205307778996921510751912836784958121590177271097904110560032076219875741821572502979807785676850802289166219856576501165317
# Since 2^(n-) mod n is not equal 1. we can say based on Fermat's
# little theorem, the number n is a composite number.
Part 2
# since p and q a little "too close for comfort" we assume that p and q close to sqrt of n
s = int(sqrt(n))
p = next_prime(s);p
q = int(n/p);q
# Check if q is also a prime number.
is_prime(q)
# Check if n = pq.
(n == p*q)
# Output:
# p = 68222080226222296181917368518534332259513625527062166102114730123514248558499
# q = 68222080226222296181917368518534332259513625527062166102114730123514248558349L
# q is a prime number
# n is equal p times q |
4aed3b4e8c69d552384a1c2d4b68b816ad31249d | Ge0dude/PythonCookbook3 | /Chapter1/1.2UnpackingArbitraryLength.py | 1,513 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 18 08:21:34 2017
@author: brendontucker
this section seems really useful for data processing, especially for
really ugle data
"""
'''can use Python star expressions (*expression) to accomplish this goal'''
testList = list(range(24))
def drop_first_last(grades):
first, *middle, last = grades
return middle
print(drop_first_last(testList))
#this does indeed drop 0 and 23, the first and last entries
#also works to grab an unknown amount of ending characters
record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
name, email, *phoneNumbers = record
#in this code, phoneNumbers will always be a list
#works for dealing with the front end of a section of data also
testList2 = list(range(10))
*begining, nextToLast, last = testList2
'''Discussion--need to work through this because I don't quite get it yet'''
records = [
('foo', 1, 2),
('bar', 'hello'),
('foo', 3, 4),
]
def do_foo(x, y):
print('foo', x, y)
def do_bar(s):
print('bar', s)
for tag, *args in records:
if tag == 'foo':
do_foo(*args)
elif tag == 'bar':
do_bar(*args)
#ah, okay, just allowing for more variation in printing of unequal len data
'''again, super impressive what these star expressions can do with strings'''
line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
uname, *fields, homedir, sh = line.split(':')
|
bd9dbf29b7052ee159755edd39610dc4cc137211 | Programmable-school/Python-Training | /lesson/lessonSet/main.py | 774 | 4.03125 | 4 | """
集合型
"""
# 順序なし、重複を許されないデータ型
values1 = set([0, 1, 2, 3, 4])
values2 = {0, 1, 2, 3, 4}
print(values1) # {0, 1, 2, 3, 4}
print(values2) # {0, 1, 2, 3, 4}
values3 = {0, 0, 1, 1, 2, 3, 4, 0, 5, 6}
print(values3) # {0, 1, 2, 3, 4, 5, 6}
# 要素の確認
print(4 in values1) # True
print(10 in values1) # False
# 値を追加
values1.add(10)
print(values1) # {0, 1, 2, 3, 4, 10}
print(10 in values1) # True
# 値を削除
values1.remove(0)
print(values1) # {1, 2, 3, 4, 10}
print(0 in values1) # False
values4 = {1, 3, 5, 8}
values5 = {3, 5, 6, 10}
# 和集合
print(values4 | values5) # {1, 3, 5, 6, 8, 10}
# 積集合
print(values4 & values5) # {3, 5}
# 差集合
print(values4 - values5) # {8, 1}
|
d8156bfc7612ccb0e7ab19598c3d07bd73dd7f2b | CJLucido/Excel | /addLineToExcel.py | 1,624 | 3.71875 | 4 |
#!!!!!!This will overwrite your excel file!!!!!!!!!!!!
# excel file must have an empty first column
import pandas as pd
import os
from openpyxl import load_workbook
file=input('File Path: ')
pth=os.path.dirname(file)
df=pd.read_excel(file)
file_cols = list(df)#Alternate to # file_cols = df.columns.values.tolist()
df_state = df
def addInstance(file_cols=file_cols, df=df, file=file):
instance = {}
writer = pd.ExcelWriter(file, engine='openpyxl')
for i in file_cols:
if i == file_cols[0]:
continue
else:
param_entry = input(f'Add {i} Value: ')
instance[i] = param_entry
new_row = pd.DataFrame(instance, index=[0]) # index otherwise ValueError: If using all scalar values, you must pass an index
newdf = pd.concat([new_row, df]).reset_index(drop=True)
newdf.to_excel(writer, "Main", columns=file_cols, index=False, index_label=None)#index False AND index_label=None to get rid on Unnamed 0
writer.save()
global df_state
df_state = newdf
print(f'\nNew Instance Completed, {len(df)} ')
print('Thanks for using this program.')
return
while True:
x=input('Add an instance (Y/N): ').lower()
if x == 'y':
addInstance(df=df_state)
y=input('Would you like to add another? (Y/N): ').lower()
if y == 'n':
print('\nThanks for using this program.')
break
elif y == 'y':
continue
elif x=='n':
print('\nThanks for using this program.')
break
else: continue |
f513d16416a4e571044a044fe03d141e9ff85fd1 | mischelay2001/WTCSC121 | /CSC121FinalProject_WakeMartUpgrade/scan_items.py | 5,636 | 4.375 | 4 | __author__ = 'Michele Johnson'
""" 3. scan_prices
Write a scan_prices function for the customer to order items.
First call the read_price_list function to read the price list from a text file.
Display all items in the price dictionary.
Then use a loop for the customer to enter product code of each item he wants.
Every time a product code is entered, check to see whether the code is in the dictionary.
If it is not, display “Item not found”. If the code is in the dictionary,
display “Item found” and the price of the item. When the customer has no more product code to enter,
she types ‘9999’ to exit the loop. The scan_prices function will calculate,
display and return the total price of all the items ordered. """
# Import Statements
from CSC121FinalProject_WakeMartUpgrade.show_list_prices import ProductList
from CSC121FinalProject_WakeMartUpgrade import valid_entry
from CSC121FinalProject_WakeMartUpgrade import formatting
def request_num():
# Function validates the number of items user request to be purchased
# Initialize Variables
request_entry = 0
confirm_entry = 0
# # Loop: Item Requests
is_request_valid = False
while is_request_valid is False:
# Number of requests: User enters number of items to be purchased
entry = "\nEnter the number of items to be purchased"
# Current number of requests
request_entry = valid_entry.integer_entry(entry)
# Request count less than 1
if request_entry <= 0:
entry_test1 = False
print("\tThe number of items must be greater than 0.")
# Greater than 10 without confirmation
elif request_entry > 10:
entry = "\tPlease confirm the number of items to be purchased"
confirm_entry = valid_entry.integer_entry(entry)
# If quantities not equal, display message and try again
if request_entry != confirm_entry:
print("\tThe number of items to be purchased was not confirmed.")
else:
is_request_valid = True
else:
is_request_valid = True
return request_entry
def scan_and_total_items(generated, products):
""" This function collects, counts, and total price of items ordered by user.
The customer enters the prices one by one with a loop until they desire to quit.
Function also checks each item against the product list to verify the item is listed.
The function returns items ordered as a dictionary, item count, and total price of all items ordered. """
# Continue to add items to order until user stops
order = {}
total = 0
item_count = 0
request_count = 0
# Order Items
# Loop until user confirms to end ordering items
is_order_done = False
while is_order_done is False:
# Loop: Item Requests
is_request_valid = False
while is_request_valid is False:
# Get valid number of requests
request_entry = request_num()
# Request tally of all requests
request_count = request_count + request_entry
# Loop processes item; repeats to equal number of requests
for i in range(request_entry):
# Loop: Look up item number
is_item_valid = False
while is_item_valid is False:
# User enters item number
request_text = "\n\t\t\t\t\tEnter item code:"
item = valid_entry.clean_string_digits(request_text, 4)
# Look for item as a key
# If item is valid
if item in generated:
# Get item price and name; display item
item_price, item_name = ProductList.ShowProduct(products, item)
print("\t\t\t\t\t\t Item Found:\t" + item_name + "\t$" + item_price)
# Running tally of items ordered
item_count += 1
# add item to order list
item_price = float(item_price)
order[item_count] = item, item_price, item_name
# Running tally of order total
total = total + float(item_price)
# Loop ends
is_item_valid = True
# If item number is not valid, error
else:
print("\nItem Not Found")
# Loop ends: all requests processed
if item_count == request_count:
is_request_valid = True
# Loop ends; input from user to end ordering items
stop_order = input("\nEnter -1 to stop order entry:\t")
if stop_order == '-1':
is_order_done = True
return order, item_count, total
def show_order_list(a_order):
# Function displays the list of items ordered by customer
# Customer order heading
print()
heading_customer_order = "YOUR ORDERED ITEMS"
formatting.headings(heading_customer_order)
print("Item Number\t\t\tItem Code\t\t\tPrice\t\t\tItem Name")
for key in a_order:
item_data = a_order[key]
item_code = item_data[0]
item_price = format(float(item_data[1]), ',.2f')
item_name = item_data[2]
print(" ", key, "\t\t\t\t", item_code, "\t\t\t\t$" + str(item_price), "\t\t\t", item_name)
|
a43bb19ea5e718524d772fe5c72d50d7728eb071 | elinfalla/CMEEGroupWork | /Ioan/Code/LV3_2.py | 2,343 | 3.953125 | 4 | #!/usr/bin/env python3
"""Defining and plotting a discrete-time version of the Lotka-Volterra model of population dynamics for inputted parameters."""
### The Lotka-Volterra model
## Imports
import scipy as sc
import numpy as np
import scipy.integrate as integrate
import matplotlib.pylab as p
import sys
# Define the function
def dCR_dt(pops):
R = pops[0]
C = pops[1]
Rnext = R * (1 + r * (1 - R / K) - a * C)
Cnext = C * (1 - z + e * a * R)
return np.array([Rnext, Cnext])
def plot1(pops, t):
"""Plot lines showing consumer and resource population dynamics against time"""
# create an empty figure object
f1 = p.figure()
# plot consumer density and resource density
p.plot(t, pops[:,0], 'g-', label = 'Resource density')
p.plot(t, pops[:,1], 'b-', label = 'Consumer density')
p.grid()
p.legend(loc='best')
p.xlabel('Time')
p.ylabel('Population density')
p.title('Consumer-Resource population dynamics')
# save the figure as a pdf
f1.savefig('../Results/LV3_model1.pdf')
def plot2(pops):
""" """
# create an empty figure object
f2 = p.figure()
# plot consumer density and resource density in another way
p.plot(pops[:,0], pops[:,1], 'r-')
p.grid()
p.xlabel('Resource density')
p.ylabel('Consumer density')
p.title('Consumer-Resource population dynamics')
# save the figure as a pdf
f2.savefig('../Results/LV3_model2.pdf')
def main(argv):
"""main function of the program"""
# Read parameters from command line
global r, a, z, e, K
r = 0.05
a = 0.05
z = 0.05
e = 0.02
K = 10000
# Set the initial conditions for the two populations, convert the two into an array
R0 = 10
C0 = 5
RC0 = np.array([R0, C0])
# Define population density array
pops = np.array([[R0, C0]])
# Define starting point of time
t = 0
# Create 1000 density data of each population
while t < 999:
RC0 = dCR_dt(RC0)
pops = np.append(pops, [[RC0[0], RC0[1]]], axis = 0)
t = t + 1
# Define total t series
t = np.array(range(1000))
# Plot population dynamic of consumer and resource and save to Results
plot1(pops, t)
plot2(pops)
if __name__ == "__main__":
status = main(sys.argv)
sys.exit(status) |
45e19880d1efb152f4a3f563ebc15d76d0dee5c7 | deimelperez/HackerRank | /Problem Solving/Sock Merchant.py | 431 | 3.640625 | 4 | import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(ar):
colors = list(set(ar))
count = 0
for i in range(0, len(colors)):
count += ar.count(colors[i]) // 2
print(ar.count(colors[i]) // 2)
return count
if __name__ == '__main__':
ar = list(map(int, input().rstrip().split()))
result = sockMerchant(ar)
print(result)
|
fe1bcd5c512785eac2412e63d47ab84a728d2820 | shishujuan/rsa-algrithm | /pow.py | 1,047 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from time import clock
import time
def pow_simple(a, e, n):
"""
朴素法模幂运算:a^e % n
"""
ret = 1
for _ in xrange(e):
ret *= a
return ret % n
def pow_simple_optimized(a, e, n):
"""
朴素法模幂运算优化:基于 a ≡ c(mod n) => ab ≡ bc(mod n),即 ab mod n = (b*(a mod n)) mod m
"""
ret = 1
c = a % n
for _ in xrange(e):
ret = (ret * c) % n
return ret
def pow_binary(a, e, n):
"""
right-to-left binary method:基于位运算模幂运算优化。
"""
number = 1
base = a
while e:
if e & 1:
number = number * base % n
e >>= 1
base = base * base % n
return number
if __name__ == '__main__':
a, e, n = 5, 102400, 13284
s = clock()
print pow_simple(a, e, n)
print clock() - s
s = clock()
print pow_simple_optimized(a, e, n)
print clock() - s
s = clock()
print pow_binary(a, e, n)
print clock() - s
|
586a16baab0ffcf457ac8198e1a116001d281a77 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/sum-root-to-leaf-numbers.py | 1,522 | 4.1875 | 4 | """
# SUM ROOT TO LEAF NUMBERS
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
1
- -
2 3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Input: [4,9,0,5,1]
4
- -
9 0
- -
5 1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.total = 0
def sumNumbers(self, root: TreeNode) -> int:
self.sums(root, 0)
return self.total
def sums(self, root, num):
if not root:
return
if not root.left and not root.right:
num = num * 10 + root.val
self.total += num
else:
self.sums(root.left, num * 10 + root.val)
self.sums(root.right, num * 10 + root.val)
|
bdedfe502202378b017639280cece219ee539e4f | JonathanVose/CMPT-120L-910-20F | /Assignments/Assignment 9/App_Calculator.py | 435 | 4 | 4 | import Calculator
x = int(input("Please enter a number: "))
y = int(input("Please enter another number: "))
functions = Calculator.Calculator()
print(functions.addition(x,y))
print(functions.subtraction(x,y))
print(functions.division(x,y))
print(functions.multiplication(x,y))
print(functions.exponent(x,y))
print(functions.square_root(x))
print(functions.square_root(y))
print(functions.negate(x))
print(functions.negate(y))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.