blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
3fa926780c7733d5db01d1222e1701a011b6d71d | yang4978/LeetCode | /Python3/0529. Minesweeper.py | 2,178 | 3.515625 | 4 | class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
# if board[click[0]][click[1]] == 'M':
# board[click[0]][click[1]] = 'X'
# return board
# directions = [(0,-1),(0,1),(-1,0),(1,0),(-1,-1),(-1,1),(1,-1),(1,1)]
# m = len(board)
# n = len(board[0])
# count = [[0]*n for _ in range(m)]
# for i in range(m):
# for j in range(n):
# if board[i][j] == 'M':
# count[i][j] = -1
# for dx,dy in directions:
# if 0<=i+dx<m and 0<=j+dy<n and count[i+dx][j+dy]!=-1:
# count[i+dx][j+dy] += 1
# block = [click]
# while block:
# x, y = block.pop(0)
# if board[x][y] == 'E':
# if count[x][y] != 0:
# board[x][y] = str(count[x][y])
# else:
# board[x][y] = 'B'
# for dx,dy in directions:
# if 0<=x+dx<m and 0<=y+dy<n:
# block.append([x+dx,y+dy])
# return board
if board[click[0]][click[1]] == 'M':
board[click[0]][click[1]] = 'X'
return board
directions = [(0,-1),(0,1),(-1,0),(1,0),(-1,-1),(-1,1),(1,-1),(1,1)]
m = len(board)
n = len(board[0])
used = [[0]*n for i in range(m)]
block = [click]
while block:
x, y = block.pop(0)
if board[x][y] == 'E':
count = 0
points = [[x+dx,y+dy] for dx,dy in directions if 0<=x+dx<m and 0<=y+dy<n]
for xx, yy in points:
count += 1 if board[xx][yy] == 'M' else 0
if count>0:
board[x][y] = str(count)
else:
board[x][y] = 'B'
for xx, yy in points:
if used[xx][yy] == 0:
block.append([xx,yy])
used[xx][yy] = 1
return board
|
71af4e58651e10faf5ff29fdc7cc48b45ed3471c | yang4978/LeetCode | /Python3/1302. Deepest Leaves Sum.py | 729 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def deepestLeavesSum(self, root: TreeNode) -> int:
sum_value = 0
temp = 0
stack = [(root,0)]
while stack:
node,layer = stack.pop(0)
if temp==layer:
sum_value += node.val
else:
temp = layer
sum_value = node.val
if node.left:
stack.append((node.left,layer+1))
if node.right:
stack.append((node.right,layer+1))
return sum_value
|
19f51a29cb79783ed9a0a9b5e5495fb16350a785 | yang4978/LeetCode | /Python3/0214. Shortest Palindrome.py | 1,082 | 3.515625 | 4 | class Solution:
# 中心扩散法 #
def shortestPalindrome(self, s: str) -> str:
if(s==""):
return s
l = len(s)
for i in range(l):
temp = s[l-1:l-i-1:-1] + s
l_temp = l+i
if(temp[:l_temp//2]==temp[l_temp-1:l_temp//2-1:-1] or temp[:l_temp//2]==temp[l_temp-1:l_temp//2:-1]):
return temp
# 马拉车 #
def shortestPalindrome(self, s: str) -> str:
index = 0
ss = '#'
for c in s:
ss += c + '#'
R = 0
C = 0
l = len(s)
p = [0]*(2*l+1)
for i in range(2*l+1):
mirror_i = 2*C - i
if i + p[mirror_i] < R:
p[i] = p[mirror_i]
else:
k = R - i + 1
while i-k >= 0 and i+k < 2*l+1 and ss[i-k]==ss[i+k]:
k += 1
p[i] = k-1
C = i
R = i + p[i]
if C == p[C]:
index = C
return ''.join(reversed(list(s[index:])))+s
|
6f3ecffda7c90d79322ab038fa9f178d3c0707c7 | yang4978/LeetCode | /Python3/0865. Smallest Subtree with all the Deepest Nodes.py | 714 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
def height(node):
if not node:
return 0
return max(height(node.left),height(node.right))+1
if not root:
return None
l = height(root.left)
r = height(root.right)
if l==r:
return root
if l>r:
return self.subtreeWithAllDeepest(root.left)
if l<r:
return self.subtreeWithAllDeepest(root.right)
|
57e06a6decb8ccf90e11ac7bf935ed3b0e37df65 | yang4978/LeetCode | /Python3/0234. Palindrome Linked List.py | 1,855 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
# res = []
# while head:
# res.append(head.val)
# head = head.next
# return res==res[::-1]
###先找中点,后翻转####
if not head:
return True
slow = head
fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
fast = slow.next
dummy = ListNode(-1)
while fast:
after = fast.next
fast.next = dummy.next
dummy.next = fast
fast = after
node = dummy.next
while head and node:
if head.val != node.val:
return False
head = head.next
node = node.next
return True
####一边找中点,一边翻转####
# if not head or not head.next:
# return True
# slow = head
# after = head
# fast = head
# dummy = ListNode(-1)
# while fast.next and fast.next.next:
# fast = fast.next.next
# after = slow.next
# slow.next = dummy.next
# dummy.next = slow
# slow = after
# last_half = after.next
# if fast.next:
# after = slow.next
# slow.next = dummy.next
# dummy.next = slow
# slow = after
# node = dummy.next
# while last_half and node:
# if last_half.val != node.val:
# return False
# last_half = last_half.next
# node = node.next
# return True
|
e9c538aa2c6735e5614f12c397bbde389c8b6ecb | yang4978/LeetCode | /Python3/0048. Rotate Image.py | 879 | 3.734375 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# n = len(matrix)
# k = 0
# while(k<n//2):
# for times in range(n-2*k-1):
# temp = matrix[k][k]
# for j in range(k,n-k-1):
# temp,matrix[k][j+1] = matrix[k][j+1],temp
# for i in range(k,n-k-1):
# temp,matrix[i+1][n-k-1] = matrix[i+1][n-k-1],temp
# for j in range(n-k-1,k,-1):
# temp,matrix[n-k-1][j-1] = matrix[n-k-1][j-1],temp
# for i in range(n-k-1,k,-1):
# temp,matrix[i-1][k] = matrix[i-1][k],temp
# k += 1
matrix[:] = map(list,zip(*matrix[::-1]))
|
11fba61b0bbdce9ce6b108067892a9b9a96d9499 | yang4978/LeetCode | /Python3/0101. Symmetric Tree.py | 1,047 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
queue = [root,root]
while queue:
r1 = queue.pop(0)
r2 = queue.pop(0)
if r1==None and r2==None:
continue
elif r1==None or r2==None or r1.val!=r2.val:
return False
else:
queue.append(r1.left)
queue.append(r2.right)
queue.append(r1.right)
queue.append(r2.left)
return True
# def isMirror(r1,r2):
# if r1==None and r2==None:
# return True
# elif r1==None or r2==None:
# return False
# else:
# return r1.val==r2.val and isMirror(r1.left,r2.right) and isMirror(r1.right,r2.left)
# return isMirror(root,root)
|
22327f478c167aa3e06ae39ee2aac76b4303507e | Bbenard/python-snippets | /Data_Search/json_files.py | 1,417 | 3.859375 | 4 | import json
from pprint import pprint
uid = input("Enter User ID: ")
class UserData(object):
"""
Class to check the JSON file of user data,
check if user id is an integer
Store the json file in a variable and loop through
use with filename as variable to load the json data and store in a variable
use this loaded data to loop through checking for user data
if the input is an integer, obtain user id
loop through each line
"""
@staticmethod
def obtain_id():
json_data = open("User_Data.json", "r")
with json_data as data_file:
data = json.load(data_file)
if isinstance(int(uid), int):
user_id = int(uid)
# pprint(data)
for x in data:
if x.get('id') == user_id:
print("---" * 10 + "\n" +
"User Found...\n" +
"---" * 10 + "\n" +
"ID: " + str(x.get('id')) + "\n" +
"First Name: " + x.get('first_name') + "\n" +
"Last Name: " + x.get("last_name") + "\n" +
"Gender: " + x.get('gender') + "\n" +
"Email: " + x.get('email') + "\n" +
"---" * 10
)
else:
print("Please enter a valid id")
UserData.obtain_id()
|
66c033aa71f59194e22a89054896197aa2c42757 | GowthamSingamsetti/Python-Practise | /rough10.py | 899 | 4.25 | 4 | # PYTHON program for bubble sort
print("PYTHON PROGRAM FOR BUBBLE SORT TECHNIQUE (Ascending Order)")
print("-"*70)
list = [12,4,45,67,98,34]
print("List before sorting" , list)
for i in range(0,6):
flag = 0
for j in range(0,5):
if(list[j]>list[j+1]):
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
flag = 1
if(flag == 0):
break;
print("\nList after sorting" , list)
print("PYTHON PROGRAM FOR BUBBLE SORT TECHNIQUE (Descending Order)")
print("-"*50)
list = [12,4,45,67,98,34]
print("List before sorting" , list)
for i in range(0,6):
flag = 0
for j in range(0,5):
if(list[j]<list[j+1]):
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
flag = 1
if(flag == 0):
break;
print("\nList after sorting" , list)
|
f74a74fccc367e053009c67054da8d290e087767 | GowthamSingamsetti/Python-Practise | /rough15.py | 662 | 3.921875 | 4 | graph = {'A': ['B','D','E'],
'B':['A','E','E'],
'C':['B','E','F','G'],
'D':['A','E'],
'E':['A','B','C','D','F'],
'F':['C','E','G'],
'G':['C','F']}
# visit all the nodes of the graph using BFS
def bfs_connected_component(graph,start):
explored = []
queue = [start]
while queue:
node = queue.pop(0) # pop shallowest node
if node not in explored:
explored.append(node)
neighbors = graph[node]
for neighbor in neighbors:
queue.append(neighbor)
return explored
print(bfs_connected_component(graph,'A')) |
aa7ad779bb0d4afdc34a8ed22909172c58518fb0 | GowthamSingamsetti/Python-Practise | /rough9.py | 1,220 | 3.96875 | 4 | def mean(numlist):
no_of_eles = len(numlist)
summ = sum(numlist)
avg = summ / no_of_eles
print("Mean for given set of numbers is : ", avg)
return
def median(numlist):
numlist.sort()
if (len(numlist) % 2 != 0):
i = len(numlist) // 2
print("Median for given set of numbers is : ", numlist[i])
else:
i = len(numlist) // 2
print("Median for given set of numbers is : ",
(numlist[i - 1] + numlist[i]) / 2)
return
def mode(numlist):
modedict = {}
mincount = 1
for ele in numlist:
maxcount = numlist.count(ele)
if (maxcount >= mincount):
mincount = maxcount
modedict[ele] = mincount
if (mincount == 1):
print("Mode for given set of numbers is : None")
else:
print("Mode for given set of numbers is : ", end='')
for ele in modedict:
if (modedict[ele] == mincount):
print(ele, end=' ')
return
numlist = []
n = int(input("Enter number of elements to be insert:"))
for i in range(n):
ele = int(input("Enter element:"))
numlist.append(ele)
mean(numlist)
median(numlist)
mode(numlist) |
cf58f71d2ac959c21a300c91828a09e9227db6e6 | GowthamSingamsetti/Python-Practise | /exp-18.py | 133 | 3.75 | 4 | numbers = [100, 20, 5, 15, 5]
uniques = []
for i in numbers:
if i not in uniques:
uniques.append(i)
print(uniques)
|
ea82fcdd3639fb35b94f608b1f27cca26304a4f4 | GowthamSingamsetti/Python-Practise | /exp-33.py | 364 | 3.671875 | 4 | class Mammal:
def __init__(self, name):
self.name = name
def walk(self):
print(f"{self.name} can walk")
class Dog(Mammal):
def bark(self):
print("It can bark.")
class Cat(Mammal):
pass
dog1 = Dog("Tommy")
dog1.walk()
dog1.bark()
cat1 = Cat("Sophie")
cat1.walk()
dog2 = Dog("")
dog2.walk()
|
b26f795f05c5456c662c07731a3501f80eddf294 | brand-clear/pywinscript | /winprint.py | 2,285 | 3.5 | 4 | """
pywinscript.winprint is a high-level win32print wrapper for physical printing.
"""
import win32api
import win32print
from config import printer_A, printer_B, printer_D
class Printer(object):
"""Represents a physical printer.
Parameters
----------
document : str
Absolute path to printable document.
papersize : {'A', 'B', 'D'}, optional
copies : int, optional
Attributes
----------
document
printer
papersize
copies
"""
_PROPERTIES = {
'A' : {
'constant' : 1,
'inches' : '8.5 X 11',
'printer': printer_A
},
'B' : {
'constant' : 17,
'inches' : '11 X 17',
'printer': printer_B
},
'D' : {
'constant' : 25,
'inches' : '24 X 36',
'printer': printer_D
},
}
# The amount of printer settings that are returned when calling
# win32print.GetPrinter().
_LEVEL = 2
def __init__(self, document, papersize='A', copies=1):
self._document = document
self._papersize = papersize
self._copies = copies
@property
def document(self):
"""str: The absolute path to a printable document."""
return self._document
@document.setter
def document(self, filepath):
self._document = filepath
@property
def printer(self):
"""str: The active printer."""
return self._PROPERTIES[self._papersize]['printer']
@property
def papersize(self):
"""str: The papersize to be printed."""
return self._PROPERTIES[self._papersize]['constant']
@papersize.setter
def papersize(self, size):
self._papersize = size
@property
def copies(self):
"""int: The number of copies to be printed."""
return self._copies
@copies.setter
def copies(self, copies):
self._copies = copies
def start(self):
"""Print a document on the active printer."""
# Set printer
win32print.SetDefaultPrinter(self.printer)
handle = win32print.OpenPrinter(self.printer, None)
# Get existing printer settings
settings = win32print.GetPrinter(handle, self._LEVEL)
settings['pDevMode'].PaperSize = self.papersize
settings['pDevMode'].Copies = self.copies
# Update printer settings
# Exceptions are raised, but changes are applied.
try:
win32print.SetPrinter(handle, self._LEVEL, settings, 0)
except:
pass
win32api.ShellExecute(0, 'print', self.document, None, '.', 0)
win32print.ClosePrinter(handle) |
79634513690698ec9a402274f09fef55a006075d | hudaoling/hudaoling_20200907 | /Python全栈_老男孩Alex/7 面向对象编程/继承_学校.py | 3,012 | 4.0625 | 4 | # Author:Winnie Hu
class Scholl(object):
members=0
def __init__(self,name,addr):
self.name=name
self.addr=addr
self.students=[]#初始化空列表,用于接收报名学生
self.staffs=[]#初始化空列表,用于接收教师
def enroll(self,stu_obj):#stu_obj某学生对象
print("为学员%s办理注册手续"%stu_obj.name)
self.students.append(stu_obj)
def hire(self,staff_obj):#staff_obj雇佣的教师
print("雇佣新员工%s"%staff_obj.name)
self.staffs.append(staff_obj)
class SchollMember(object):#父类,公有属性name,age,sex
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def tell(self):
# print("---info of %s"%st)
pass
class Teacher(SchollMember):#Teacher子类,重构自己的方法
def __init__(self, name, age, sex, salary,course):
super(Teacher,self).__init__(name,age,sex)
self.salary = salary#增加属性
self.course = course#增加属性
def tell(self):#增加方法:打印教师信息
print('''---info of Teacher:%s---
Name:%s
Age:%s
Sex: %s
Salary: %s
Course: %s'''%(self.name,self.name,self.age,self.sex,self.salary,self.course))
def teach(self):#老师在上课
print("%s is teaching coure [%s]"%(self.name,self.course))
class Student(SchollMember):#Student子类,重构自己的方法
def __init__(self, name, age, sex, stu_id, grade):
super(Student,self).__init__(name, age, sex)
self.stu_id = stu_id#增加属性
self.grade = grade#增加属性
def tell(self):#增加方法:打印学生信息
print('''---info of Teacher:%s---
Name:%s
Age:%s
Sex: %s
stu_id: %s
grade: %s''' % (self.name, self.name, self.age, self.sex, self.stu_id, self.grade))
def pay_tuition(self,amount):
print("%s had paid tution for $%s"%(self.name,amount))
sch1=Scholl("上海中学","闵行区") #实例化一个学校:上海中学
t1=Teacher("Alex",33,"男",10000,"英语")
t2=Teacher("Jack",38,"男",15000,"数学")
s1=Student("Annie",12,"男","s112","二年级")
s2=Student("Alas",12,"女","s112","三年级")
t1.tell()#打印教师alex的详细信息
s1.tell()#打印学员Annie的详细信息
sch1.hire(t1)#上海中学雇佣了t1:Alex
sch1.hire(t2)
print(sch1.staffs) #雇佣的教师存到Scholl的教师列表
print(sch1.staffs[0].salary)#可以查看教师alexde 工资,==t.salary
sch1.enroll(s1)#上海中学录取了s1:Annie
sch1.enroll(s2)
print(sch1.students[0].name) #可以查看学员的姓名等,==s1.name
print(sch1.members)
t1.teach() # sch1.staffs[0]=t1
sch1.staffs[0].teach()#相当于t1.teach()
s1.pay_tuition(3000)
s2.pay_tuition(3000)#相当于下面的for循环
for stu in sch1.students:
stu.pay_tuition(3000)
|
ec54e2569435a24201e346f5a2eae9b7db8021eb | hudaoling/hudaoling_20200907 | /Python全栈_老男孩Alex/5 生成器-迭代器-装饰器-内置方法/裴波那契.py | 1,795 | 3.625 | 4 | #裴波那契数列
# def fib(max):#形参max
# n,a,b=0,0,1#变量赋值
# while n<max:#100次循环内
# print(b)
# a,b=b,a+b# 初次赋值是a1=1(b0初始值),b1=0(a0初始值)+1(b0初始值)=1,二次赋值a2=1(b1),b2=(a1)+1(b1)=2
# n=n+1
# return 'done'
# fib(100) #这是一个函数
#函数式列表生成器,只要有yield就是一个生成器,已经不是函数了
def fib(max):#形参max
n,a,b=0,0,1#变量赋值
while n<max:#100次循环内
yield b#列表生成器,生成b
a,b=b,a+b# 初次赋值是a1=1(b0初始值),b1=0(a0初始值)+1(b0初始值)=1,二次赋值a2=1(b1),b2=(a1)+1(b1)=2
n=n+1
return 'done'
f=fib(10) #这是一个generator----生成器
print(f.__next__())#调用yield b,并返回值
print(f.__next__())
print(f.__next__())
print("--打印累了,干点别的活吧--")#函数可以随时跳出,进行别的操作
print(f.__next__())
print(f.__next__())
print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())#当next次数超过maxx=10时,抛异常:StopIteration: done
print("\n")
print("---for---")#next完成,进入到for循环,继续打印
for i in f:
print(i)
#如果想要拿到return返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中
def fib(max):#100
n,a,b=0,0,1
while n<max:#n<100
yield b
a,b=b,a+b
n=n+1
return 'done'#如果next执行超过范围时,会抛异常
g = fib(5)
while True:
try:#不停的尝试
x = next(g)
print('g:', x)
except StopIteration as e:#异常处理代码
print('Generator return value:', e.value)
break
|
cf8f65d4d28bdc98a8a7cc9cf2ce7d0453bfb980 | hudaoling/hudaoling_20200907 | /Python全栈_老男孩Alex/3-列表-字典-字符串-购物车/String_UseMethod.py | 2,733 | 4.21875 | 4 | # Author:Winnie Hu
name="My Name is {name},She is a worker and She is {year} old"
print(name.capitalize())#首字母
print(name.count("i"))
print(name.center(50,"-")) #打印50个字符,不够用-补齐,并摆放中间
print(name.endswith("ker")) #判断是否以什么结尾
print(name.expandtabs(tabsize=30))# \ 把这个键转换成多少个空格
print(name.find("is")) #取字符的索引位置,从0开始计算
print(name[name.find("is"):13])#返回索引的目的就是为了切片取字符串
print(name[name.find("is"):])#从is取数到最后
print(name.format(name='Winnie Hu',year=32))#给变量赋值
print(name.format_map({'name':'Winnie Hu','year':32}))#给变量赋值,不常用
#print(name.index())
print('ab23'.isalnum())#判断name变量,是不是阿拉伯数字
print('abcde'.isalpha())#判断是不是纯英文字母
print('2'.isdigit())#判断是不是十进制
print('100'.isdigit())#判断是不是整数
print('name_of_you'.isidentifier())#判断是不是一个合法的标识符(合法的变量名)
print('1name'.islower())#判断是不是小写
print('MY NAME '.isupper())#判断是不是大写
print('33'.isnumeric())#判断是不是一个数字
print(name.isspace())#判断是不是空格
print('My Name Is '.istitle())#判断是不是标题,单词首个字母大写是标题
print('My Name Is '.isprintable())#判断是不是能打印
print('+'.join(['1','2','3','4']))#把列表合并为字符串格式
print(name.ljust(100,'*'))#用*补全到指定的字符数量,字符串在左边
print(name.rjust(100,'-'))#用*补全到指定的字符数量,字符串在右边
print('\nWinnie Del\n'.strip())#\n代表换行,strip默认去掉两头的空格或回车
print('Winnie Del\n'.lstrip())#\n代表换行,lstrip去掉左边的空格或回车
print('Winnie Del\n'.rstrip())#\n代表换行,lstrip去掉右边的空格或回车
print('Winnie'.lower())#转换成小写
print('Winnie'.upper())#转换成大写
p = str.maketrans("abcdefli",'123$@456')#定义字符串与另一串字符串的对应关系
print("alex li".translate(p))#对alex li,根据上面的对应关系进行逐一替换,可用于密码加码等
print('alex li'.replace('l','L',1))#替换字符串
print('alex lil'.rfind('l'))#查找到从右边开始的某个字符串
print('al ex lil'.split())#按照指定的分割符拆分列,结果是list
print('al-ex-lil'.split('-'))#按照指定的分割符拆分列
print('1+2+3+4'.split('+'))#按照指定的分割符拆分列
print('1+2\n+3+4'.splitlines())#按空格或换行来拆分列
print('Alex Li'.swapcase())#大小写转换
print('alex li'.title())#变更为标题,首字母大写
print('alex li'.zfill(50))#字符串不够的时候,补0
name2='\[email protected]' #\n代表换行
|
a261a049f582f22e722ed10d5cffb44a2883e5b5 | hudaoling/hudaoling_20200907 | /Python全栈_老男孩Alex/2-For-While-Input-数据类型-变量/DataType_数据类型.py | 3,608 | 4.15625 | 4 | # Author:Winnie Hu
一、数字
2是一个整数的例子
3.23是浮点数的例子
type() #查看数据类型
1.int(整型)
在32位机器上,整数的位数为32位,取值范围-2**31~2*31-1
在64位机器上,整数的位数为64位,取值范围-2**63~2*63-1
2.long(长整型,大一些的整数)
长度没有指定宽度,如果整数发生溢出,python会自动将整数数据转换为长整型
3.float浮点数
浮点数用来处理实数,即带有小数的数字。
52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 *10**4
二、布尔值
真或假 1或0
三、string字符串
"hello world"
万恶的字符串拼接:python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的 + 号每出现一次就会在内从中重新开辟一块空间。
字符串格式化输出
name = "alex"
print
"i am %s " % name
'i am {}'.format(name)
# 输出: i am alex
PS: 字符串是 % s;整数 % d;浮点数 % f
字符串常用功能:移除空白;分割;长度;索引;切片
四、列表list[]---中括号表示,可变
列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作
names = ['Alex', "Tenglan", 'Eric']
创建列表:
name_list = ['alex', 'seven', 'eric']
或
name_list = list(['alex', 'seven', 'eric'])
基本操作:索引;切片;追加;删除;长度;循环;包含
五、元组 info()-----括号表示,不可变列表
创建元组:
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
语法
names = ("alex", "jack", "eric")
ages = (11, 22, 33, 44, 55)
或
ages = tuple((11, 22, 33, 44, 55))
六、字典 info{}-----大括号标识,是无序的
字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。
语法:
info = {
'stu1101': "TengLan Wu",
'stu1102': "LongZe Luola",
'stu1103': "XiaoZe Maliya",
}
字典的特性:
dict是无序的
key必须是唯一的,so 天生去重
person = {"name": "mr.wu", 'age': 18}
或
person = dict({"name": "mr.wu", 'age': 18})
常用操作:索引;新增;删除;键、值、键值对;循环;长度
七、数据运算
http://www.runoob.com/python/python-operators.html
算数运算:比较运算:赋值运算:赋值运算:成员运算:成员运算:位运算:运算符优先级:
八、bytes类型
二进制,01
八进制,01234567
十进制,0123456789
十六进制,0123456789
ABCDEF
二进制到16进制转换
http://jingyan.baidu.com/album/47a29f24292608c0142399cb.html?picindex=1
#python里面的byte类型,与字符串类型的转换
msg="我爱北京天安门"
print(msg)
print(msg.encode(encoding="utf-8"))#字符串编码称为二进制
print(msg.encode(encoding="utf-8").decode(encoding="utf-8")) #二进制解码成字符串
九、集合set(),是一个无序的,不重复的数据组合,
它的主要作用如下:
1、去重,把一个列表变成集合,就自动去重了
2、关系测试,测试两组数据之前的交集、差集、并集等关系
s = set([3, 5, 9, 10]) # 创建一个数值集合
t = set("Hello") # 创建一个唯一字符的集合
a = t | s # t 和 s的并集
b = t & s # t 和 s的交集
c = t – s # 求差集(项在t中,但不在s中)
d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中)
|
29e7e1d222edafc4c2a4c229949848a004ae4285 | hudaoling/hudaoling_20200907 | /Python全栈_老男孩Alex/7 面向对象编程/静态方法-类方法-属性方法.py | 2,048 | 4.21875 | 4 | # Author:Winnie Hu
#动态方法
class Dog(object):
def __init__(self,name):
self.name=name
def eat(self,food):
print("动态方法self.:","%s is eating %s"%(self.name,food))
d=Dog("jinmao")
d.eat("baozi")
#静态方法
class Dog(object):
def __init__(self,name):
self.name=name
# 静态方法,实际上跟类没什么关系了,就可理解为类下面的一个普通函数
@staticmethod#只装饰某一方法,不影响下面其它方法
def eat(name,food):
print("静态方法@staticmethod:","%s is eating %s"%(name,food))
def talk(self):
print("不受影响", "%s is talking" % (self.name))
d=Dog("jinmao")
d.eat("jinmao","baozi")
d.talk()
#类方法,作用在类变量
class Dog(object):
name="huabao"#类变量
def __init__(self,name):
self.name=name
#类方法,只能访问类变量,不能访问实例变量。无法访问实例里面的变量。
#一般用于强制该方法只能调用类变量。
@classmethod
def eat(self,food):
print("类方法@classmethod:","%s is eating %s"%(self.name,food))
d=Dog("jinmao")
d.eat("baozi")
#属性方法
class Dog(object):
def __init__(self,name):
self.name=name
self.__food=None
#属性方法,把一个方法变成一个静态属性。
@property
def eat(self):
print("属性方法@property:","%s is eating %s"%(self.name,self.__food))
#如果要给eat赋值时,可以采用以下方法
@eat.setter
def eat(self,food):
print("set to food:",food)
self.__food=food#给私有属性self.__food赋值food
d=Dog("jinmao")
d.eat #d.eat变成了一个属性(既变量)。属性方法不用括号,不用传参,只能用常量值(例如"baozi")
d.eat="niurou" #赋值后,d.eat也会跟着变为“niurou”
d.eat
#del d.name #属性既变量,可以删除
#print(d.name)
del d.eat #属性方法默认无法删除
@eat.deleter
def eat(self):
del self.__food
print("删完了")
|
11678f2bb9982e7b7bbb61bf326a3c94c04878dc | einelson/hand-detection | /example code/camera capture.py | 5,058 | 3.53125 | 4 | """
File: teach1.py (week 05)
Tasks
- Convert video stream to be grayscale
- Create a circle mask and apply it to the video stream
- Apply a mask file to the video stream
usa-mask.jpg
byui-logo.png
- create a vide stream of differences from the camera
- use gray scale
- use absdiff() function
"""
"""
Use this code for any of the tasks for the team activity
cap = cv2.VideoCapture(0) # Notice the '0' instead of a filename
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('frame', frame)
# Wait for 'q' to quit the program
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
"""
import numpy as np
from cv2 import cv2
def task0():
""" Live capture your laptop camera """
cap = cv2.VideoCapture(0) # Notice the '0' instead of a filename
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('frame', frame)
# Wait for 'q' to quit the program
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def task1():
""" Convert video stream to be grayscale and display the live video stream """
cap = cv2.VideoCapture(0) # Notice the '0' instead of a filename
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
# Wait for 'q' to quit the program
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def task2():
""" Create a circle mask and apply it to the live video stream """
cap = cv2.VideoCapture(0) # Notice the '0' instead of a filename
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# make a mask
rows, cols, _ = frame.shape
mask = np.zeros((rows, cols), dtype=np.uint8)
cv2.circle(mask, (cols // 2, rows // 2), 200, (255, 255, 255), -1)
# Display the resulting frame
foreground = cv2.bitwise_or(frame, frame, mask = mask)
cv2.imshow('frame', foreground)
# Wait for 'q' to quit the program
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def task3():
""" Apply a mask file 'usa-flag.jpg' to the live video stream """
cap = cv2.VideoCapture(0)# , cv2.CAP_DSHOW) # Notice the '0' instead of a filename
ret, frame = cap.read()
rows, cols, _ = frame.shape
mask = cv2.imread('usa-mask.jpg')
mask = cv2.resize(mask, (cols,rows))
row, col, _ = mask.shape
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
for i in range(row):
for y in range(col):
if mask[i, y] < 150:
mask[i, y] = 0
elif mask[i, y] > 150:
mask[i,y] = 255
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
foreground = cv2.bitwise_or(frame, frame, mask = mask)
cv2.imshow('frame', foreground)
# Wait for 'q' to quit the program
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def task4():
""" Apply a mask file 'byui-logo.jpg' to the live video stream """
cap = cv2.VideoCapture(0)# , cv2.CAP_DSHOW) # Notice the '0' instead of a filename
ret, frame = cap.read()
rows, cols, _ = frame.shape
mask = cv2.imread('byui-logo.png')
mask = cv2.resize(mask, (cols,rows))
row, col, _ = mask.shape
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
for i in range(row):
for y in range(col):
if mask[i, y] < 200:
mask[i, y] = 0
elif mask[i, y] > 200:
mask[i,y] = 255
cv2.imshow('mask', mask)
cv2.waitKey(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
foreground = cv2.bitwise_or(frame, frame, mask = mask)
cv2.imshow('frame', foreground)
# Wait for 'q' to quit the program
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def task5():
"""
create a vide stream of differences from the camera
- use gray scale images
- use the OpenCV function absdiff()
- Questions: are the any methods/techniques to make this work better?
"""
pass
# ===========================================================
# task0()
# task1()
# task2()
task3()
task4()
task5()
|
5a87994d884876f9e909d0549e8bc7efc5e64b9f | hengrumay/100-women-flask-app | /helpers/makeDFfromJson.py | 1,300 | 3.59375 | 4 |
def makeDFfromJson(ibm_out):
"""
Reformat Json output from IBM API call via Speech Recognition with relevant parameters as a pandaDataFrame
---------------------------------------------------------------------------
## Example use:
# from makeDFfromJson import makeDFfromJson
# DF0 = makeDFfromJson(ibm_out)
---------------------------------------------------------------------------
h-rm.tan 2-3oct2017
"""
import pandas as pd
import numpy as np
DFtmp_spkInfo = pd.DataFrame.from_dict(ibm_out['speaker_labels'])
DFtmp_spkInfo = DFtmp_spkInfo.rename(columns = {'confidence':'SpkConf'})
r_list=[]
Wd_list=[]
Sconf_list=[]
for i,r in enumerate (ibm_out['results']):
Wd_list.extend(r['alternatives'][0]['transcript'].split())
n_wds = len(r['alternatives'][0]['transcript'].split())
Sconf_list.extend( np.repeat(r['alternatives'][0]['confidence'],n_wds) )
r_list.extend( np.repeat(i,n_wds) )
DFtmp_wdSconf = pd.DataFrame([r_list, Wd_list,Sconf_list], index=['resultIDX','Wd_list','SentConf']).T
DF = pd.concat([DFtmp_wdSconf, DFtmp_spkInfo], axis=1)
DF.dropna(inplace=True) # doesn't get returned | also tried saving as another DF no joy
return DF
|
6ccdbdcc90fffe223051131e8b7cc1b2c5bb9341 | vlytvynenko/lp | /lp_hw/ex8.py | 780 | 4.28125 | 4 | formatter = "{} {} {} {}" #Defined structure of formatter variable
#Creating new string based on formatter structure with a new data
print(formatter.format(1, 2, 3, 4))
#Creating new string based on formatter structure with a new data
print(formatter.format('one', 'two', 'three', 'four'))
#Creating new string based on formatter structure with a new data
print(formatter.format(True, False, False, True))
#Creating new string based on formatter structure with a formatter variable
print(formatter.format(formatter, formatter, formatter, formatter))
#New structure for the last string
formatter2 = "{}; {}; {}; {}!"
#printed new string based on formatter2 structure
print(formatter2.format(
"Lya, lya, lya",
"Zhu, Zhu, zhu",
"Ti podprignizh",
"Ya vsazhu"
))
|
da151fb58a835d22b3409332d68d72a430198604 | sheffieldjordan/binarySearchTree | /BST.py | 3,378 | 4.59375 | 5 | #---------------------------------------------------------
# Morgan Jordan
# [email protected]
# Homework #3
# September 20, 2016
# BST.py
# BST
# ---------------------------------------------------------
class Node:
#Constructor Node() creates node
def __init__(self,word):
self.word = word #to create an instance object of a Node class,
#you need to tell the Node what word it is. Word will then be associated
# with the particular instance you create.
self.right = None
self.left = None
self.count = 1
class BSTree:
#Constructor BSTree() creates empty tree
def __init__(self, root=None):
self.root = root # to create an instance object of the BSTree class,
# you need to tell the tree what it's root is. The default root is empty.
#These are "external functions" that will be called by your main program - I have given these to you
#Find word in tree
def find(self, word):
return _find(self.root, word)
# a = _find(self.root, word)
# print('in find() a = ', a)
# return a
#Add node to tree with word
def add(self, word):
if not self.root:
self.root = Node(word)
return
_add(self.root, word)
#Print in order entire tree
def in_order_print(self):
_in_order_print(self.root)
def size(self):
return _size(self.root)
def height(self):
return _height(self.root)
#These are "internal functions" in the BSTree class - You need to create these!!!
#Function to add node with word as word attribute
def _add(root, word):
if root.word == word: #if 50 == 38
root.count +=1
return #root.count
if root.word > word:
if root.left == None:
root.left = Node(word)
else:
_add(root.left, word)
else:
if root.right == None:
root.right = Node(word) #instatiating a new Node class >> a new node that contains whatever the word
else:
_add(root.right, word)
#Function to find word in tree
def _find(root, word):
"""this performs a binary search to see if the word is in
the tree, if so, returns the number of times the word appears
in the input text file; find(word) is fully recursive """
if root.word == word:
# print('found the word, count is', root.count)
return root.count
if root.word > word:
return _find(root.left, word)
if root.word < word:
return _find(root.right, word)
#Get number of nodes in tree
def _size(root):
if root is None:
return 0
if root is not None:
return 1 + _size(root.left) + _size(root.right)
#Get height of tree
def _height(root):
if root is None:
return 0 ;
else:
left_height = _height(root.left)
right_height = _height(root.right)
if left_height > right_height:
return left_height + 1
else:
return right_height + 1
#Function to print tree in order
def _in_order_print(root):
if not root: #if root == None # if root is None
return #closes out of the very last function call and continues with the next to last one, skips to root.word
_in_order_print(root.left)
print(root.word)
print(root.count) #assume this is 1
_in_order_print(root.right)
|
738774b4756d730e942bcb8c88ec3801afe4b54c | legitalpha/Spartan | /Day_9_ques1_Russian_peasant_algo.py | 285 | 4.125 | 4 | a = int(input("Enter first number : "))
b = int(input("Enter second number : "))
count = 0
while a!=0:
if a%2==1:
count +=b
b=b<<1
a=a>>1
if a%2==0:
b=b<<1
a=a>>1
print("The product of first and second number is ",count) |
1401557e5c71df2c239cf25bf9bcafa814ebd2d1 | magik2art/DZ_10_Pavel_Mamaev | /task1.py | 700 | 3.546875 | 4 | from random import randint
class Matrix:
def __init__(self, my_list):
self.my_list = my_list
def __str__(self):
for row in self.my_list:
for i in row:
print(f"{i:4}", end="")
print("")
return ''
def __add__(self, other):
for i in range(len(self.my_list)):
for i_2 in range(len(other.my_list[i])):
self.my_list[i][i_2] = self.my_list[i][i_2] + other.my_list[i][i_2]
return Matrix.__str__(self)
def run():
x = ([randint(0, 1) for num in range(0, 3)])
return x
m = Matrix([run(), run(), run()])
print(m)
new_m = Matrix([run(), run(), run()])
print(m.__add__(new_m))
|
029694ef897dc8242bfa416216994ade3f99df53 | hilariusperdana/praxis-academy | /novice/01-04/soal1.py | 267 | 3.640625 | 4 | #soal no 1
a=2
b=5
print(int(a/b))
print(float(a/b))
#soal no 2
firstname='hilarius'
lastname='perdana'
print('Hello Praxis, saya',firstname,lastname,'! saya siap belajar enterprise python developer.')
#soal no 3
p = 9.99999
q = 'the number: '
print('jawaban',q,p) |
5753fc612bf24b08b9224b391385c9534fa4700c | hilariusperdana/praxis-academy | /novice/01-01/latihan/quicksort.py | 505 | 3.640625 | 4 | def QuickSort(A,mulai,akhir):
if mulai<akhir:
pindex=partition(A,mulai,akhir)
QuickSort(A,mulai,pindex-1)
QuickSort(A,pindex+1,akhir)
def partition(A,mulai,akhir):
pivot = A[akhir]
pindex = mulai
for i in range(mulai,akhir):
if (A[i] <= pivot):
A[i],A[pindex]=A[pindex],A[i]
pindex += 1
A[pindex],A[akhir] = A[akhir],A[pindex]
return pindex
A = [34,21,45,32,12,31,19,23,54,31,25,27]
QuickSort(A,0,len(A)-1)
print("hasil",A) |
1612c998d40aa89fa5cccdaf868496a84d139ec5 | TangTT-xbb/python1116 | /test_SSH/09-多线程.py | 556 | 3.640625 | 4 | import time
from threading import Thread
# 创建线程
def work():
print("当前线程")
def sing(i):
for x in range(i):
print(f"当前进程号:{t1.name} 正在唱歌")
time.sleep(1)
def dance():
for x in range(5):
print(f"当前进程号:{t2.name} 正在跳舞")
time.sleep(1)
t1 = Thread(target=sing, args=(4,))
t2 = Thread(target=dance)
# 启动线程
time_start = time.time()
t1.start()
t2.start()
t1.join()
t2.join()
time_end = time.time()
print("运行时间:",time_end-time_start)
|
7a45b823413cface7baea747a93611b71bae81eb | Valken32/Card-Games | /21cardgame.py | 3,701 | 4.03125 | 4 | import random
ace = 1
jack = 11
queen = 12
king = 13
totalScore = 0
botTotalScore = 0
def cardConditions():
if cardNum or botCardNum == 1:
print("ace")
elif cardNum or botCardNum == 11:
print("jack")
elif cardNum or botCardNum == 12:
print("queen")
elif cardNum or botCardNum == 13:
print("king")
else:
print(cardNum)
def keepTrack():
print("Bot's score is", botTotalScore)
print("Your score is", totalScore)
while True:
cardDeck = [ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king]
answer = input("Draw a card? y/n")
if answer.lower().strip() == "y":
cardNum = random.choice(cardDeck)
botCardNum = random.choice(cardDeck)
cardConditions()
totalScore = totalScore + cardNum
botTotalScore = botTotalScore + botCardNum
if totalScore and botTotalScore == 21:
keepTrack()
pa = input("Tie! Want to play again? Y/N")
if pa.lower().strip() == "y":
totalScore = 0
botTotalScore = 0
continue
else:
totalScore = 0
botTotalScore = 0
break
elif totalScore >= 22:
keepTrack()
pa = input("You lose! Want to play again? Y/N")
if pa.lower().strip() == "y":
totalScore = 0
botTotalScore = 0
continue
else:
totalScore = 0
botTotalScore = 0
break
elif botTotalScore >= 22:
keepTrack()
pa = input("You win! Want to play again? Y/N")
if pa.lower().strip() == "y":
totalScore = 0
botTotalScore = 0
continue
else:
totalScore = 0
botTotalScore = 0
break
elif totalScore <= 20:
keepTrack()
continue
elif botTotalScore == 21:
keepTrack()
pa = input("You lose! Want to play again? Y/N")
if pa.lower().strip() == "y":
totalScore = 0
botTotalScore = 0
continue
else:
totalScore = 0
botTotalScore = 0
break
else:
keepTrack()
pa = input("You win! Want to play again? Y/N")
if pa.lower().strip() == "y":
totalScore = 0
botTotalScore = 0
continue
else:
totalScore = 0
botTotalScore = 0
break
elif answer.lower().strip() == "n":
cardNum = 0
botCardNum = random.choice(cardDeck)
cardConditions()
botTotalScore = botTotalScore + botCardNum
if totalScore > botTotalScore:
keepTrack()
pa = input("You win! Want to play again? Y/N")
if pa.lower().strip() == "y":
totalScore = 0
botTotalScore = 0
continue
else:
totalScore = 0
botTotalScore = 0
break
else:
keepTrack()
pa = input("You lose! Want to play again? Y/N")
if pa.lower().strip() == "y":
totalScore = 0
botTotalScore = 0
continue
else:
totalScore = 0
botTotalScore = 0
break
else:
break |
dc9666f2fa8bdd71a080e160d153a0d317c497ab | dgquintero/holbertonschool-machine_learning | /math/0x00-linear_algebra/3-flip_me_over.py | 257 | 3.96875 | 4 | #!/usr/bin/env python3
"""function that transpose a matrix"""
def matrix_transpose(matrix):
"""matrix transpose function"""
r = [[0, 0, 0], [0, 0, 0]]
m = matrix
r = [[m[j][i] for j in range(len(m))]for i in range(len(m[0]))]
return r
|
86d2c53c8f8c2444a71a561526384c909ecae90c | dgquintero/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/1-normalize.py | 427 | 3.921875 | 4 | #!/usr/bin/env python3
"""normalize function"""
def normalize(X, m, s):
"""
normalizes (standardizes) a matrix
Arguments:
X: input to normalize shape(d, nx)
d: number of data points
nx: number of features
m: the mean of all features of X shape(nx,)
s: standard deviation of all features of X shape(nx,)
Returns: matrix normalized
"""
return (X - m) / s
|
edbbed7b9a0ebeae3e1478b4988008deed3cee2e | dgquintero/holbertonschool-machine_learning | /math/0x03-probability/binomial.py | 1,951 | 4.125 | 4 | #!/usr/bin/env python3
"""class Binomial that represents a Binomial distribution"""
class Binomial():
""" Class Binomial that calls methos CDF PDF """
def __init__(self, data=None, n=1, p=0.5):
""" Class Binomial that calls methos CDF PDF """
self.n = int(n)
self.p = float(p)
if data is None:
if self.n <= 0:
raise ValueError("n must be a positive value")
elif self.p <= 0 or self.p >= 1:
raise ValueError("p must be greater than 0 and less than 1")
else:
if type(data) is not list:
raise TypeError("data must be a list")
elif len(data) < 2:
raise ValueError("data must contain multiple values")
else:
mean = sum(data) / len(data)
v = 0
for i in range(len(data)):
v += ((data[i] - mean) ** 2)
variance = v / len(data)
self.p = 1 - (variance / mean)
self.n = int(round(mean / self.p))
self.p = mean / self.n
def pmf(self, k):
"""Method that returns the pmf"""
k = int(k)
if k > self.n or k < 0:
return 0
factor_k = 1
factor_n = 1
factor_nk = 1
for i in range(1, k + 1):
factor_k *= i
for i in range(1, self.n + 1):
factor_n *= i
for f in range(1, (self.n - k) + 1):
factor_nk *= f
comb = factor_n / (factor_nk * factor_k)
prob = (self.p ** k) * ((1 - self.p) ** (self.n - k))
pmf = comb * prob
return pmf
def cdf(self, k):
""" Method that returns the Cumulative Distribution Function"""
k = int(k)
if k < 0:
return 0
else:
cdf = 0
for i in range(k + 1):
cdf += self.pmf(i)
return cdf
|
61829caf238855994467336de51105891f86389e | dgquintero/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/10-Adam.py | 784 | 3.625 | 4 | #!/usr/bin/env python3
"""create_Adam_op function"""
import tensorflow as tf
def create_Adam_op(loss, alpha, beta1, beta2, epsilon):
"""
that training operation for a neural network in tensorflow
using the Adam optimization algorithm
Arguments:
loss: is the loss of the network
alpha: is the learning rate
beta1: is the weight used for the first moment
beta2: is the weight used for the second moment
epsilon: is a small number to avoid division by zero
Returns: Adam optimization operation
"""
optimizer = tf.train.AdamOptimizer(alpha,
beta1,
beta2,
epsilon).minimize(loss)
return optimizer
|
5f078110c9b78997fbcaf7fd50dd4452bf6911a5 | dgquintero/holbertonschool-machine_learning | /supervised_learning/0x05-regularization/1-l2_reg_gradient_descent.py | 1,218 | 3.953125 | 4 | #!/usr/bin/env python3
""" l2_reg_gradient_descent function"""
import numpy as np
def l2_reg_gradient_descent(Y, weights, cache, alpha, lambtha, L):
"""
calculates the cost of a neural network with L2 regularization
Arguments:
Y: Correct labels for the data shape(classes, m)
cache: dictionary of the outputs of each layer of the NN
alpha: the learning rate
lambtha: the regularization parameter
weights: a dictionary of the weights and biases of the neural network
L: is the number of layers in the neural network
m: is the number of data points used
Returns: the cost of the network accounting for L2 regularization
"""
m = Y.shape[1]
dz = cache['A'+str(L)] - Y
for i in range(L, 0, -1):
cost_L2 = (lambtha / m) * weights['W'+str(i)]
db = (1 / m) * np.sum(dz, axis=1, keepdims=True)
dW = ((1 / m) * np.matmul(dz, cache['A'+str(i-1)].T)) + cost_L2
dz = np.matmul(weights['W'+str(i)].T, dz) *\
((1 - cache['A'+str(i-1)] ** 2))
weights['W'+str(i)] = weights['W'+str(i)] -\
(alpha * dW)
weights['b'+str(i)] = weights['b'+str(i)] -\
(alpha * db)
|
32178b1696d71175cfc45a73e0e0f78c3a62d5b2 | dgquintero/holbertonschool-machine_learning | /math/0x04-convolutions_and_pooling/4-convolve_channels.py | 1,824 | 3.65625 | 4 | #!/usr/bin/env python3
""" convolve_grayscale function"""
import numpy as np
def convolve_channels(images, kernel, padding='same', stride=(1, 1)):
"""that performs a convolution on images with channels
Arguments:
images: shape (m, h, w) containing multiple grayscale images
m: the number of images
h: the height in pixels of the images
w: the width in pixels of the images
kernel: shape (kh, kw) containing the kernel for the convolution
kh: the height of the kernel
kw: the width of the kernel
padding: is a tuple of (ph, pw)
ph: padding for the height of the image
pw: padding for the width of the image
stride:
sh: stride for the height of the image
sw: stride for the width of the image
Returns: ndarray containing the convolved images
"""
m = images.shape[0]
h = images.shape[1]
w = images.shape[2]
kh = kernel.shape[0]
kw = kernel.shape[1]
padh = 0
padw = 0
sh = stride[0]
sw = stride[1]
if padding == 'same':
padh = int((((h - 1) * sh + kh - h) / 2) + 1)
padw = int((((w - 1) * sw + kw - w) / 2) + 1)
if type(padding) == tuple:
padh = padding[0]
padw = padding[1]
pad = ((0, 0), (padh, padh), (padw, padw), (0, 0))
new_h = int(((h + (2 * padh) - kh) / sh) + 1)
new_w = int(((w + (2 * padw) - kh) / sw) + 1)
image_p = np.pad(images, pad_width=pad, mode='constant')
output_c = np.zeros((m, new_h, new_w))
for i in range(new_h):
for j in range(new_w):
x = i * sh
y = j * sw
image = image_p[:, x:x+kh, y:y+kw, :]
output_c[:, i, j] = np.multiply(image, kernel).sum(axis=(1, 2, 3))
return output_c
|
e682a01f28a43fa2e12ea8bede1518dc68de528c | Coder-Liuu/Lesson_design_for_Freshmen | /Python/Python-枚举法/main.py | 1,215 | 3.671875 | 4 | import math
def car():
print("罪犯的车牌号为:",end="")
for a1 in range(0,10):
for a2 in range(0,10):
if(a1==a2):
for a3 in range(0,10):
for a4 in range(0,10):
if(a3==a4 and a1!=a3):
a = a1*1000+a2*100+a3*10+a4
for i in range(100):
if(a == i * i):
print(a1,a2,a3,a4)
def Tricolore():
s = 0
for i in range(4): # 红球
for j in range(4): #黄球
k = 8 - i - j #绿球
if k <= 6:
s += 1
print("三色球问题共有",s,"种不同的颜色搭配.")
if __name__ == "__main__":
while(True):
print("\n\n------------------------")
print("1.帮助警察破案")
print("2.三色球问题")
print("3.退出系统")
choose = int(input("请选择你要求解的问题:"))
if(choose ==1 ):
car()
elif(choose == 2):
Tricolore()
elif(choose == 3):
break
else:
print("输入错误!")
|
7bfc92f730e822a2c639b4605c8d330593184ebd | buzsb/junior_test | /max_sum_sub_list.py | 579 | 3.578125 | 4 | def max_sum_sub_list(array):
if array == []:
raise ValueError
temporary_sum = max_sum = array[0]
i = 0
start = finish = 0
for j in range(1, len(array)):
if array[j] > (temporary_sum + array[j]):
temporary_sum = array[j]
i = j
else:
temporary_sum += array[j]
if temporary_sum > max_sum:
max_sum = temporary_sum
start = i
finish = j
return array[start:finish + 1]
print max_sum_sub_list([1, -2, 3, -1, 5, -6])
print max_sum_sub_list([-3, 2, 6, -4])
|
d5491b784640d17450cbf52b9ecd8019f5b630a7 | kvanishree/AIML-LetsUpgrade | /Day4.py | 1,393 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
#Q1
print("enter the operation to perform")
a=input()
if(a=='+'):
c=(3+2j)+(5+4j)
print(c)
elif(a=='-'):
c=(3+2j)-(5+4j)
print(c)
elif(a=='*'):
c=(3+2j)*(5+4j)
print(c)
elif(a=='/'):
c=(3+2j)/(5+4j)
print(c)
elif(a=='//'):
print("floor division of two number is not possible\n")
elif(a=='%'):
print("module is not possible to do in complex numbers\n")
else:
print("enter correct operation")
# #Q2
# range()
# range(start,stop,step)
# start:it is not compulsory but if we want we can mention this for where to start..
# stop:it is required and compulsory to mention , this for where to stop..
# step: it is not compulsory to mention , but if we requird to print one step forward number of every number..
#
# In[21]:
#ex
for i in range(5):
print(i)
print("---------------")
list=[1,2,3,4,5,6,7]
for list in range(1,5,2):
print(list)
# In[23]:
#Q3
a=int(input(print("enter the num1\n")))
b=int(input(print("enter the num1\n")))
c=a-b
if(c>25):
print("multiplication is = ",a*b)
else:
print("division is = ",a/b)
# In[2]:
#Q4
l=[1,2,3,4,5,6]
for i in range(len(l)):
if(l[i]%2==0):
print("square of the number minus 2\n")
# In[3]:
#Q5
l2=[12,14,16,17,8]
for i in range(len(l2)):
if (l2[i]/2)>7:
print(l2[i],end=" ")
# In[ ]:
|
cafa13ec431741821f02757d8afca267a49c5aa3 | sidrap1234/lab3 | /cal01.py | 88 | 3.75 | 4 | # calculator in python v01
def add(num1,num2):
return num1 + num2
#main
print(add(5,3)) |
1326c22ba6a7b4e403fc6f130b089ec7cdacd472 | nk4456542/Password-Checker | /Password Checker.py | 4,298 | 4.03125 | 4 | '''
Author : Zaheer Abbas
Description : This python script checks if your password has been pwned or not
This file contains three main functions.
1. main_file(filename)
-> Run this function if you have a lot of passwords stored in a file. You should give the filename as command line argument and also the file must be present in the same directory as you are currently running this python script on.
2. main_user_input()
-> Run this function if you want to manually provide the input. Note that this function has an infinite loop. To break out of this you must enter "-1"(without quotes).
3. main_command_line(args)
-> Run this function if you have a small number of passwords. You should give all the passwords that you want to check as command line arguments .
Uncomment any one of the function call(you can find those below at the bottom of the file) that you want to run and check if your password has been pwned or not securely
'''
import sys
import requests
import hashlib
import os
def request_api_data(first_5_char_hashed_password):
'''requesting the data from the api'''
url = "https://api.pwnedpasswords.com/range/" + first_5_char_hashed_password
response = requests.get(url)
if response.status_code != 200:
raise RuntimeError(
f"Error fetching the data, Response code : {response.status_code}. Check the api and try again later")
return response
def check_my_password_pwned_count(response_from_api, our_hashed_password_suffix):
'''Cheking if password has ever been pwned or hacked and returning the count'''
password_tuple = (line.split(":")
for line in response_from_api.text.splitlines())
for suffix, count in password_tuple:
if suffix == our_hashed_password_suffix:
return count
return 0
def check_my_password(password):
'''hashes the password and checks if the password is present in the api reponse'''
sha1_hashed_password = hashlib.sha1(
password.encode('utf-8')).hexdigest().upper()
first_5_char = sha1_hashed_password[:5]
suffix = sha1_hashed_password[5:]
response = request_api_data(first_5_char)
return check_my_password_pwned_count(response, suffix)
def main_file(filename):
'''If you want to give file as input then call this function with the filename as command line argument. Note that the input file must be present in the same directory that you are currently running this script from'''
absolute_path = os.path.abspath(filename)
with open(absolute_path) as file:
for password in file:
password = password.strip()
count = check_my_password(password)
if count:
print(
f"The password {password} has been seen {count} times... You should probably change your password!")
else:
print(
f"The password {password} has not been seen before... You can choose this password ")
return "Done!"
def main_user_input():
'''Call this function if you want to manually give the password as input'''
while(True):
print("Enter to \"-1\" Exit")
print("Enter the password you want to check")
try:
password = input().strip()
except:
print("You must enter a string")
continue
if(password == "-1"):
break
count = check_my_password(password)
if count:
print(
f"The password {password} has been seen {count} times... You should probably change your password!")
else:
print(
f"The password {password} has not been seen before... You can choose this password ")
return "Done!"
def main_command_line(args):
''' Call this function by giving multiple command line arguments'''
for password in args:
count = check_my_password(password)
if count:
print(
f"The password {password} has been seen {count} times... You should probably change your password!")
else:
print(
f"The password {password} has not been seen before... You can choose this password ")
return "Done"
# main_file(sys.argv[1])
# main_user_input()
# main_command_line(sys.argv[1:])
|
95704790c99c31725d89bb8f3ad607bc14647c10 | liar666/RedDigits | /PyDigits/reddigits/DigitModel.py | 2,795 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Class encapsulating Digits
"""
import matplotlib.pyplot as plt # for displaying images
import numpy as np # ªor arrays
from PIL import Image # To tag the images
from PIL import ImageDraw
from Utils import Utils
class DigitModel:
RIGHT = "RIGHT"
LEFT = "LEFT"
TOP = "TOP"
BOTTOM = "BOTTOM"
"""Models a single digit with its position in the larger image and its subImage"""
def die(self):
print("DigitModel destroyed")
def __init__(self, originalImageShape, subImage, minRow, minCol, maxRow, maxCol):
"""Initialize the position of the digit and its subImage"""
self.subImage = subImage
self.bbox = { 'tl':(minCol, minRow), 'br':(maxCol, maxRow) }
self.center = (minCol+(maxCol-minCol)/2, minRow+(maxRow-minRow)/2)
self.fuzzyPosition = DigitModel.computeFuzzyPosition(originalImageShape, self.center)
self.guessedValue = None
def __str__(self):
self.display()
print("bbox = (" + str(self.bbox.tl) + ") -> (" + str(self.bbox.br) + ")")
print("center = (" + str(self.center) + ")")
print("fuzzyPos=" + self.fuzzyPosition)
print("value=" + self.guessedValue)
@staticmethod
def tagImage(imgNP, tag, position, color=(255,255,255)):
imgNP = np.uint8(imgNP*255)
imgPIL = Image.fromarray(imgNP)
draw = ImageDraw.Draw(imgPIL)
draw.text(position, tag, color)
return(np.array(imgPIL))
@staticmethod
def computeFuzzyPosition(originalImageShape, center):
"""Position relative to the big picture : (Top/Bottom, Left/Right)"""
fPos = "NO FUZZY POSITION"
originalImageWidth = originalImageShape[1]
originalImageHeight = originalImageShape[0]
xCenter = center[0]
yCenter = center[1]
if yCenter > originalImageHeight/2:
fPos = DigitModel.BOTTOM
else:
fPos = DigitModel.TOP
if xCenter > originalImageWidth/2:
fPos += " " + DigitModel.RIGHT
else:
fPos += " " + DigitModel.LEFT
return fPos
def getTaggedImage(self):
img = self.subImage
if self.guessedValue != None:
img = DigitModel.tagImage(img, str(self.guessedValue), (self.subImage.shape[1]/2, 0))
return(img)
def display(self):
plt.imshow(self.getTaggedImage())
plt.show()
if __name__ == "__main__":
HOME = "/home/guigui/GMCodes/RedDigits/"
DIGIT_IMAGE_DIR = HOME + "/images/numbers_cleaned/"
img = Utils.readImage(DIGIT_IMAGE_DIR + "0.png")
digit = DigitModel((200,200), img, 10, 20 , 10+img.shape[1], 20+img.shape[0])
digit.guessedValue = 0
digit.display()
plt.show() |
c217f28848327a1770a64a26a16d89c685a9f59a | tsubhadarshy/TrainingSDET | /Python/Activity8.py | 474 | 4.0625 | 4 | # Input list of numbers
numList = list(input("Enter a sequence of comma separated values: ").split(","))
print("Input list is ", numList)
# Get first element in list
firstElement = numList[0]
# Get last element in list
lastElement = numList[-1]
# Check if first and last element are equal
if (firstElement == lastElement):
print("Are first and last numbers of the list same?: True")
else:
print("Are first and last numbers of the list same?: False")
|
2f84d2a9e6ca9f3c850c1b523538d83bb772a5fe | gaurab123/DataQuest | /02_DataAnalysis&Visualization/04_DataCleaning/05_ChallengeCleaningData/05_ConsolidatingDeaths_Cheet.py | 1,075 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 20 11:41:51 2017
@author: kkite
"""
import pandas as pd
import matplotlib.pyplot as plt
pd.options.mode.chained_assignment = None # default='warn'
def clean_deaths(row):
num_deaths = 0
columns = ['Death1', 'Death2', 'Death3', 'Death4', 'Death5']
for c in columns:
death = row[c]
if pd.isnull(death) or death == 'NO':
continue
elif death == 'YES':
num_deaths += 1
return num_deaths
true_avengers['Deaths'] = true_avengers.apply(clean_deaths, axis=1)
avengers = pd.read_csv("avengers.csv", encoding='latin-1')
avengers['Year'].hist()
plt.show()
print("The avengers were created in the 1960's therefore no data prior to that data will be consitered in this investigation.")
true_avengers = avengers[avengers['Year'] >= 1960]
print('\n\n\nThe number of deaths is spread over several columns, "Deathn"...\nConvert that information into a single column "Deaths"')
true_avengers['Deaths'] = true_avengers.apply(clean_deaths, axis=1)
|
0aa7e42198c23433e721727e0828c14873a812cf | gaurab123/DataQuest | /06_MachineLearning/03_LinearAlgebraForMachineLearning/04_SolutionSets/02_InconsistentSystems.py | 338 | 3.53125 | 4 | # page 29 in the hand written notes for context
import numpy as np
import matplotlib.pyplot as plt
import sympy
fig = plt.figure()
X,y1,y2 = sympy.symbols('X y1 y2')
X = np.linspace(0, 20, 1000)
y1= -2*X+(5/4)
plt.plot(X,y1,label='y=-2x+5/4')
y2= -2*X+(5/2)
plt.plot(X,y2,label='y=-2x+5/2')
plt.legend()
plt.show() |
2c87cbf2ca1d5a451ca5cfa7ed8866e1cedcba6f | gaurab123/DataQuest | /04_WorkingWithDataSources/01_APIsAndWebScraping/03_Challenge_WorkingWithTheRedditAPI/05_GettingTheMostUpvotedComment.py | 1,846 | 3.578125 | 4 | import requests
import pandas as pd
import pprint
pp = pprint.PrettyPrinter(indent=4,width=80,depth=20)
# make get request to get pythons top comments from the reddit API
headers = {"Authorization": "bearer 13426216-4U1ckno9J5AiK72VRbpEeBaMSKk", "User-Agent": "Dataquest/1.0"}
params = {"t": "day"}
response = requests.get("https://oauth.reddit.com/r/python/top", headers=headers, params=params)
# Convert the json formatted data into a python data structure
python_top = response.json()
# Extract the list containing all of the posts
python_top_articles = python_top['data']['children']
# Put this data into a pandas DataFrame so that it can be more easily worked with
data_lst = []
for post_dict in python_top_articles:
# this creates a list of dictionaries each with the same keys
data_lst.append(post_dict['data'])
postdf = pd.DataFrame(data_lst)
# Sort the DataFrame by upvotes
postdf.sort_values(by=['ups'], inplace=True, ascending=False)
# Grab the most upvoted article id
most_upvoted = postdf.iloc[0]['id']
url = "https://oauth.reddit.com/r/python/comments/{}".format(most_upvoted)
response2 = requests.get(url, headers=headers)
comments = response2.json()
# comments is a list
# the 0th element has the data from the article it self
# the 1st element contains a dictionary which contains all the comments
comments_list = comments[1]['data']['children']
# Put the call the top level comments into a dataframe
data_lst = []
for comment_dict in comments_list:
data_lst.append(comment_dict['data'])
commentdf = pd.DataFrame(data_lst)
# Sort the comment data list by upvotes
# The grab the first id which will correspond to the most upvoted comment
commentdf.sort_values(by=['ups'], inplace=True, ascending=False)
most_upvoted_comment = commentdf.iloc[0]['id'] |
fa50891b13199682b4f1bc690c28d8a4e567c771 | gaurab123/DataQuest | /06_MachineLearning/02_CalculusForML/02_UnderstandingLimits/07_UndefinedLimitToDefinedLimit.py | 260 | 3.53125 | 4 | # See page 3 from math refresher notebook for hand done math steps
# There we use direct substitution to arrive at the answer of -3
import sympy as s
x2,y = s.symbols('x2 y')
y = -x2
limit_four = s.limit(y, x2, 3)
print('limit_four:', limit_four) |
dcbe69d5095815419df2130635fca147b87a0c74 | gaurab123/DataQuest | /02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/05_WorkingWithMissingData/11_UsingColumnIndexes.py | 1,692 | 4.15625 | 4 | import pandas as pd
titanic_survival = pd.read_csv('titanic_survival.csv')
# Drop all columns in titanic_survival that have missing values and assign the result to drop_na_columns.
drop_na_columns = titanic_survival.dropna(axis=1, how='any')
# Drop all rows in titanic_survival where the columns "age" or "sex"
# have missing values and assign the result to new_titanic_survival.
new_titanic_survival = titanic_survival.dropna(axis=0, subset=['age', 'sex'], how='any')
# Sort the new_titanic_survival DataForm by age
new_titanic_survival = new_titanic_survival.sort_values('age', ascending=False)
# Assign the first ten rows from new_titanic_survival to first_ten_rows
first_ten_rows = new_titanic_survival.iloc[0:10]
# Assign the fifth row from new_titanic_survival to row_position_fifth
row_position_fifth = new_titanic_survival.iloc[4]
# Assign the row with index label 25 from new_titanic_survivalto row_index_25
row_index_25 = new_titanic_survival.loc[25]
# Assign the value at row index label 1100, column index label
# "age" from new_titanic_survival to row_index_1100_age.
row_index_1100_age = new_titanic_survival.loc[1100,'age']
print(row_index_1100_age)
raw_input("Press Enter To Continue")
# Assign the value at row index label 25, column index label
# "survived" from new_titanic_survival to row_index_25_survived.
row_index_25_survived = new_titanic_survival.loc[25, 'survived']
print(row_index_25_survived)
raw_input("Press Enter To Continue")
# Assign the first 5 rows and first three columns from new_titanic_survival to five_rows_three_cols
five_rows_three_cols = new_titanic_survival.iloc[0:5,0:3]
print(five_rows_three_cols) |
d989a7155779e0da90d703c9958f78fa3c2c19dc | gaurab123/DataQuest | /02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/05_WorkingWithMissingData/15_CalculatingSurvivalPercentageByAgeGroup.py | 1,177 | 3.953125 | 4 | import pandas as pd
import numpy as np
# Create a function that returns the string "minor" if
# someone is under 18, "adult" if they are equal to or
# over 18, and "unknown" if their age is null
def age_type(row):
age = row['age']
if pd.isnull(age):
return 'unknown'
elif age < 18:
return 'minor'
else:
return 'adult'
titanic_survival = pd.read_csv('titanic_survival.csv')
# Iterates through each row and deterines the age type of each passenger
# Then, use the function along with .apply() to find the correct
# label for everyone in the titanic_survival dataframe
# Assign the result to age_labels
age_labels = titanic_survival.apply(age_type, axis=1)
# Add the age_labels series as a column called 'age_labels' to the titanic_survival dataframe
titanic_survival['age_labels'] = age_labels
# Create a pivot table that calculates the mean survival
# chance("survived") for each age group ("age_labels") of the dataframe titanic_survival
# Assign the resulting Series object to age_group_survival
age_group_survival = titanic_survival.pivot_table(index='age_labels', values='survived', aggfunc=np.mean)
print(age_group_survival) |
e8c2296b901945df30295f140fb33be93f1f37d3 | gaurab123/DataQuest | /02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/08_PandasInternalsDataframes/03_UsingCustomIndexes.py | 681 | 3.765625 | 4 | import pandas as pd
fandango = pd.read_csv('fandango_score_comparison.csv')
# Use the pandas dataframe method set_index to assign the FILM
# column as the custom index for the dataframe. Also, specify
# that we don't want to drop the FILM column from the dataframe.
# We want to keep the original dataframe, so assign the new one to fandango_films.
fandango_films = fandango.set_index('FILM', drop=False)
# Display the index for fandango_films using the index attribute and the print function
print(fandango_films.index.values)
# To verify that the drop = False thing worked print the columns
print('\nNow lets see the columns\n')
print(fandango_films.columns) |
d7955c8a4e0491be0ee67c15c2ab14dd4c423fef | gaurab123/DataQuest | /02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/05_WorkingWithMissingData/12_ReindexingRows.py | 1,166 | 4.09375 | 4 | import pandas as pd
titanic_survival = pd.read_csv('titanic_survival.csv')
# Drop all columns in titanic_survival that have missing values and assign the result to drop_na_columns.
drop_na_columns = titanic_survival.dropna(axis=1, how='any')
# Drop all rows in titanic_survival where the columns "age" or "sex"
# have missing values and assign the result to new_titanic_survival.
new_titanic_survival = titanic_survival.dropna(axis=0, subset=['age', 'sex'], how='any')
# Sort the new_titanic_survival DataForm by age
new_titanic_survival = new_titanic_survival.sort_values('age', ascending=False)
# Assign the first 5 rows and first three columns from new_titanic_survival to five_rows_three_cols
five_rows_three_cols = new_titanic_survival.iloc[0:5,0:3]
print(five_rows_three_cols)
# Reindex the new_titanic_survival dataframe so the row indexes start from 0, and the old index is dropped.
new_titanic_survival.reset_index(drop=True)
# Assign the final result to titanic_reindexed.
titanic_reindexed = new_titanic_survival
# Print the first 5 rows and the first 3 columns of titanic_reindexed
print(titanic_reindexed.iloc[0:5,0:3]) |
5f0efffc670b59f265f4f116296eeacb7357e0ec | gaurab123/DataQuest | /06_MachineLearning/04_LinearRegressionForMachineLearning/02_FeatureSelection/01_MissingValues.py | 960 | 3.625 | 4 | import pandas as pd
data = pd.read_csv('AmesHousing.txt', delimiter='\t')
train = data.iloc[:1460]
test = data.iloc[1460:]
target = 'SalePrice'
# Selects/excludes columns based upon their dtypes. Super handy, I did this manually in the last chapter :(
numerical_train = train.select_dtypes(include=['int64', 'float64'])
# Drop the following columns that either have any missing values or need to be transformed to be useful
cols_to_drop = ['PID','Year Built','Year Remod/Add','Garage Yr Blt','Mo Sold','Yr Sold']
numerical_train = numerical_train.drop(cols_to_drop, axis=1)
# Create a Series object where the index is made up of column names and the associated values are the number of missing values
null_series = pd.Series(numerical_train.isnull().sum())
# keep only the columns with no missing values, and assign the resulting Series object to full_cols_series
full_cols_series = null_series[null_series==0]
print(full_cols_series)
|
d68f1dc1a7b8f16102579df40bc60c44fe2a0e7c | gaurab123/DataQuest | /02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/08_PandasInternalsDataframes/01_SharedIndexes.py | 524 | 3.640625 | 4 | import pandas as pd
fandango = pd.read_csv('fandango_score_comparison.csv')
# Use the head method to return the first two rows in the dataframe, then display them with the print function.
print('\nPeak at 1st 2 rows using head\n')
print(fandango.head(2))
# Use the index attribute to return the index of the dataframe, and display it with the print function.
print('\nHere\'s fandano\'s Indexes\n')
print(fandango.index.values)
print('\nHere\'s fandango\'s Indexes as a list\n')
print(fandango.index.tolist()) |
f994742fb7c6f439cd6d42563855fc7d0fc14f18 | gaurab123/DataQuest | /04_WorkingWithDataSources/01_APIsAndWebScraping/04_WebScraping/05_ElementIDs.py | 720 | 3.578125 | 4 | import requests
from bs4 import BeautifulSoup
# Get the page content and set up a new parser.
response = requests.get("http://dataquestio.github.io/web-scraping-pages/simple_ids.html")
content = response.content
parser = BeautifulSoup(content, 'html.parser')
# Pass in the ID attribute to only get the element with that specific ID.
first_paragraph = parser.find_all("p", id="first")[0]
print(first_paragraph.text)
second_paragraph = parser.find_all('p', id="second")[0]
second_paragraph_text = second_paragraph.text
print(second_paragraph_text)
paragraphs = parser.find_all("p",)
# You can also iterate over the tabs to get the id
for paragraph in paragraphs:
print(paragraph['id'])
|
47632d2e510e7a9770fc0eb3ec464987425b48b3 | gaurab123/DataQuest | /04_WorkingWithDataSources/01_APIsAndWebScraping/03_Challenge_WorkingWithTheRedditAPI/04_GettingPostComments.py | 1,091 | 3.578125 | 4 | import requests
import pandas as pd
# make get request to get pythons top comments from the reddit API
headers = {"Authorization": "bearer 13426216-4U1ckno9J5AiK72VRbpEeBaMSKk", "User-Agent": "Dataquest/1.0"}
params = {"t": "day"}
response = requests.get("https://oauth.reddit.com/r/python/top", headers=headers, params=params)
# Convert the json formatted data into a python data structure
python_top = response.json()
# Extract the list containing all of the posts
python_top_articles = python_top['data']['children']
# Put this data into a pandas DataFrame so that it can be more easily worked with
data_lst = []
for post_dict in python_top_articles:
data_lst.append(post_dict['data'])
postdf = pd.DataFrame(data_lst)
# Sort the DataFrame by upvotes
postdf.sort_values(by=['ups'], inplace=True, ascending=False)
# Grab the most upvoted article id
most_upvoted = postdf.iloc[0]['id']
url = "https://oauth.reddit.com/r/python/comments/{}".format(most_upvoted)
response = requests.get(url, headers=headers)
comments = response.json()
print(comments) |
87dd7e960b690e4048727b878a29d140b00e22ce | gaurab123/DataQuest | /04_WorkingWithDataSources/04_SQLAndDatabases_Advanced/01_IntroductionToIndexing/09_AllTogetherNow.py | 822 | 3.546875 | 4 | import sqlite3
conn = sqlite3.connect("factbook.db")
q5 = 'EXPLAIN QUERY PLAN SELECT * FROM facts WHERE population > 10000;'
query_plan_five = conn.execute(q5).fetchall()
print('query plan 5')
print(query_plan_five)
conn.execute("CREATE INDEX IF NOT EXISTS population_idx ON facts(population);")
print("\nCREATE INDEX IF NOT EXISTS population_idx ON facts(population);")
q7 = "EXPLAIN QUERY PLAN SELECT * FROM facts WHERE population > 10000"
query_plan_seven = conn.execute(q7).fetchall()
print('\nquery plan 7')
print(query_plan_seven)
# Outputs:
# query plan 5
# [(0, 0, 0, 'SCAN TABLE facts')]
#
# CREATE INDEX IF NOT EXISTS population_idx ON facts(population);
#
# query plan 7
# [(0, 0, 0, 'SEARCH TABLE facts USING INDEX population_idx (population>?)')]
|
0e770842ddb7c22a02abb4b942a7c8f6e4aac72e | gaurab123/DataQuest | /02_DataAnalysis&Visualization/03_StorytellingThroughDataVisualization/01_ImporvingPlotAesthetics/04_VisualizingTheGenderGap.py | 735 | 3.671875 | 4 | # Generate 2 line charts on the same figure:
# 1) Visualizes the percentages of Biology degrees awarded to women over time
# 2) Visualizes the percentages of Biology degrees awarded to men over time.
import pandas as pd
import matplotlib.pyplot as plt
women_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')
fig, ax = plt.subplots()
ax.plot(women_degrees['Year'], women_degrees['Biology'], color='blue', label='Women')
ax.plot(women_degrees['Year'], 100 - women_degrees['Biology'], color='green', label='Men')
ax.legend(['Women', 'Men'], loc="upper right")
ax.set_title("Percentage of Biology Degrees Awarded By Gender")
# ax.set_xlabel("Year")
# ax.set_ylabel("Percentage")
plt.show() |
5e51c93b37a493cd0b97bcfde597f4e4eee9d313 | gaurab123/DataQuest | /06_MachineLearning/04_LinearRegressionForMachineLearning/01_TheLinearRegressionModel/03_SimpleLinearRegression.py | 1,577 | 3.765625 | 4 | # Generate 3 scatter plots in the same column:
# The first plot should plot the Garage Area column on the X-axis against the SalePrice column on the y-axis.
# The second one should plot the Gr Liv Area column on the X-axis against the SalePrice column on the y-axis.
# The third one should plot the Overall Cond column on the X-axis against the SalePrice column on the y-axis.
# Read more about these 3 columns in the data documentation.
import pandas as pd
import matplotlib.pyplot as plt
# For prettier plots.
import seaborn
# Gr Liv Area (Continuous): Above grade (ground) living area square feet
# Garage Area (Continuous): Size of garage in square feet
# Overall Cond (Ordinal): Rates the overall condition of the house: Rated 10 - 1, 10 being the best
data = pd.read_csv('AmesHousing.txt', delimiter='\t')
train = data.iloc[:1460]
test = data.iloc[1460:]
# Show the Pearson's correlation for each of the training features
print('Garage Area Pearson correlation:', train['Garage Area'].corr(train['SalePrice']))
print('Gr Liv Area Pearson correlation:', train['Gr Liv Area'].corr(train['SalePrice']))
print('Overall Cond Pearson correlation:', train['Overall Cond'].corr(train['SalePrice']))
fig = plt.figure(figsize=(7,15))
ax1 = fig.add_subplot(3, 1, 1)
ax2 = fig.add_subplot(3, 1, 2)
ax3 = fig.add_subplot(3, 1, 3)
train.plot(X="Garage Area", y="SalePrice", ax=ax1, kind="scatter")
train.plot(X="Gr Liv Area", y="SalePrice", ax=ax2, kind="scatter")
train.plot(X="Overall Cond", y="SalePrice", ax=ax3, kind="scatter")
plt.show() |
1004cc41fa3aa46f4e9b58acf9f5dee1579dfd7e | gaurab123/DataQuest | /06_MachineLearning/02_CalculusForML/03_FindingExtremePoints/08_PracticingFindingExtremeValues.py | 752 | 3.78125 | 4 | # See page 8 from math refresher notebook for hand done math steps
import sympy
rel_min = []
rel_max = []
X,y = sympy.symbols('X y')
extreme_one = 0
extreme_two = 2/3
print('extreme_one:', extreme_one)
X = extreme_one - 0.001
start_slope = 3*X**2 - 2*X
print('start_slope:', start_slope)
X = extreme_one + 0.001
end_slope = 3*X**2 - 2*X
print('end_slope:', end_slope)
rel_max.append(extreme_one)
print('\nextreme_two:', extreme_two)
X = extreme_two - 0.001
start_slope = 3*X**2 - 2*X
print('start_slope:', start_slope)
X = extreme_two + 0.001
end_slope = 3*X**2 - 2*X
print('end_slope:', end_slope)
rel_min.append(extreme_two)
print('\n\nResults')
print('rel_max:', rel_max)
print('rel_min:', rel_min) |
3ceaa37847341f9d3cf7e527dd1d7b98cdd7abeb | approximata/edx_mit_cs | /week_01/findabc.py | 597 | 3.796875 | 4 | s = 'abcdefghijklmnopqrstuvwxyz'
longest_abc_words = []
current_word = ''
for i in range(len(s)-1):
if s[i] <= s[i+1]:
current_word += s[i]
if i == len(s)-2 and s[-1] >= s[i]:
current_word += s[-1]
else:
current_word += s[i]
longest_abc_words.append(current_word)
current_word = ''
longestword = ''
if len(longest_abc_words) == 0:
longestword = current_word
else:
for n in range(len(longest_abc_words)):
if len(longestword) < len(longest_abc_words[n]):
longestword = longest_abc_words[n]
print(longestword)
|
a2d5f9a89b7789c168118e88658a3c6f2b8f73ae | approximata/edx_mit_cs | /final/longest_nunmber.py | 2,075 | 4.0625 | 4 |
def longest_run(L):
"""
Assumes L is a list of integers containing at least 2 elements.
Finds the longest run of numbers in L, where the longest run can
either be monotonically increasing or monotonically decreasing.
In case of a tie for the longest run, choose the longest run
that occurs first.
Does not modify the list.
Returns the sum of the longest run.
"""
temp_increasing = []
temp_decreasing = []
increaseing = []
decreaseing = []
first_increased = 0
first_decreased = 0
final_increased = 0
final_decreased = 0
i = 0
while i < len(L)-1:
while i < len(L)-1 and L[i+1] <= L[i]:
temp_increasing.append(L[i])
i += 1
else:
temp_increasing.append(L[i])
first_increased = i
if len(temp_increasing) > len(increaseing):
increaseing = temp_increasing[:]
final_increased = first_increased
temp_increasing = []
i += 1
i = 0
while i < len(L)-1:
while i < len(L)-1 and L[i+1] >= L[i]:
temp_decreasing.append(L[i])
i += 1
else:
temp_decreasing.append(L[i])
first_decreased = i
if len(temp_decreasing) > len(decreaseing):
decreaseing = temp_decreasing[:]
final_decreased = first_decreased
temp_decreasing = []
i += 1
if len(decreaseing) > len(increaseing):
print(decreaseing, 'simadec')
return sum(decreaseing)
elif len(decreaseing) < len(increaseing):
print(increaseing, 'simainc')
return sum(increaseing)
else:
if final_decreased > final_increased:
print(increaseing, 'egyeninc')
return sum(increaseing)
else:
print(decreaseing, 'egyendec')
return sum(decreaseing)
cucc = [10, 4, 3, 8, 3, 4, 5, 7, 7, 2]
cucc2 = [5, 4, 10]
cucc3 = [1, 2, 3, 4, 5, 0, 10, 1, 2, 3, 4, 5]
cucc4 = [1, 2, 3, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(longest_run(cucc4))
|
4ffcdeb951858c1f1981ef40812b078d2f58ec6f | approximata/edx_mit_cs | /week_02/problem_set2/problem2.py | 662 | 3.515625 | 4 | #!/usr/bin/python3
def pay_debt_off_pr(balance, annualInterestRate):
monthly_intrest = annualInterestRate / 12
fixed_monthly_pay = 0
original_balance = balance
while balance > 0:
month = 0
fixed_monthly_pay += 10
balance = original_balance
print(fixed_monthly_pay, 'fixed')
while month < 12:
unpaid_balance = balance - fixed_monthly_pay
intrest = unpaid_balance * monthly_intrest
balance = unpaid_balance + intrest
print(round(balance, 2))
month += 1
round(balance, 2)
return fixed_monthly_pay
print(pay_debt_off_pr(4773, 0.2))
|
62074620f90873e8577b48af2422c12b6e87c040 | approximata/edx_mit_cs | /midtermexam/problem7.py | 484 | 3.765625 | 4 | #!/usr/bin/python3
def f(a, b):
return a + b
def dict_interdiff(d1, d2):
intersect = {}
difference = {}
for key1 in d1:
if key1 in d2:
intersect[key1] = f(d1[key1], d2[key1])
del d2[key1]
else:
difference[key1] = d1[key1]
for key2 in d2:
difference[key2] = d2[key2]
return (intersect, difference)
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
print(dict_interdiff(d1, d2))
|
5a29550eb1b08000b460873abfbc9bf3b5b7ed3d | alwinsheejoy/College | /SNIPPETS/Python/strings/strings.py | 381 | 4.1875 | 4 | str_name = 'Python for Beginners'
#012356789
print(str_name[0]) # P
print(str_name[-1]) # s
print(str_name[0:3]) # 0 to 2 Pyt
print(str_name[0:]) # 0 to end(full) Python for Beginners
print(str_name[:5]) # 0 to 4 Pytho
print(str_name[:]) # [0:end] (full) - copy/clone a string.
copied_str = str_name[:] # copy
print(str_name[1:-1]) # 1 to end-1 ython for Beginner |
1ef5160d59ad6ee3ea50b67b663decafabe66441 | gowshalinirajalingam/Churn-Prediction | /Churn prediction classification.py | 13,600 | 3.8125 | 4 | #
# We aim to accomplist the following for this study:
#
# 1.Identify and visualize which factors contribute to customer churn:
#
# 2.Build a prediction model that will perform the following:
#
# =>Classify if a customer is going to churn or not
# =>Preferably and based on model performance, choose a model that will attach a probability to the churn to make it easier for customer service to target low hanging fruits in their efforts to prevent churn
#
# https://www.kaggle.com/nasirislamsujan/bank-customer-churn-prediction
#For data wragling
import numpy as np # For data manipulation
import pandas as pd # For data representation# For data representation
#For data visualization
import matplotlib.pyplot as plt # For basic visualization
import seaborn as sns # For synthetic visualization
# from sklearn.cross_validation import train_test_split # For splitting the data into training and testing
# from sklearn.cross_validation import train_test_split
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier # K neighbors classification model
from sklearn.naive_bayes import GaussianNB # Gaussian Naive bayes classification model
from sklearn.svm import SVC # Support Vector Classifier model
from sklearn.tree import DecisionTreeClassifier # Decision Tree Classifier model
from sklearn.linear_model import LogisticRegression # Logistic Regression model
from sklearn.ensemble import RandomForestClassifier # Random Forest Classifier model
from sklearn.metrics import accuracy_score, precision_score, recall_score, \
f1_score, average_precision_score, confusion_matrix, roc_curve, \
roc_auc_score # For checking the accuracy of the model
from sklearn.preprocessing import LabelEncoder, MinMaxScaler, StandardScaler
from xgboost import XGBClassifier, plot_importance
from imblearn.over_sampling import SMOTE
#Read the DataFrame
df=pd.read_csv('Churn_Modelling.csv')
print(df.info())
print(df.head())
print(df.shape)
print(df.isnull().sum()) # Check columns list and missing values
print(df.describe())
print(df.dtypes)
print(df.nunique()) # Get unique count for each variable
#drop unnecessary columns
df = df.drop(["RowNumber", "CustomerId", "Surname"], axis = 1)
# Exploratory data analysis
#
# # count distribution of a categorical variable
# df["Age"].value_counts().plot.bar(figsize=(20,6))
#
#
# #count distribution of a continuous variable
# facet = sns.FacetGrid(df, hue="Exited",aspect=3)
# facet.map(sns.kdeplot,"Age",shade= True)
# facet.set(xlim=(0, df["Age"].max()))
# facet.add_legend()
#
# plt.show()
#
#
# #Pie chart. Proportion of customer churned and retained
# labels = 'Exited', 'Retained'
# sizes = [df.Exited[df['Exited']==1].count(), df.Exited[df['Exited']==0].count()]
# explode = (0, 0.1)
# fig1, ax1 = plt.subplots(figsize=(10, 8))
# ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
# shadow=True, startangle=90)
# ax1.axis('equal')
# plt.title("Proportion of customer churned and retained", size = 20)
# plt.show()
# #Output: 20.4% Exited and 79.6% Retained. This means unbalanced data
#
#
#
# #Bar chart. Frequency distribution of Exited column by Geography,Gender,HasCrCard,IsActiveMember
# fig, axarr = plt.subplots(2, 2, figsize=(20, 12))
# sns.countplot(x='Geography', hue='Exited', data=df, ax=axarr[0][0])
# sns.countplot(x='Gender', hue='Exited', data=df, ax=axarr[0][1])
# sns.countplot(x='HasCrCard', hue='Exited', data=df, ax=axarr[1][0])
# sns.countplot(x='IsActiveMember', hue='Exited', data=df, ax=axarr[1][1])
# plt.show()
#
#
#
# # Box-plot. Relations based on the continuous data attributes
# fig, axarr = plt.subplots(3, 2, figsize=(20, 12))
# sns.boxplot(y='CreditScore',x = 'Exited', hue = 'Exited',data = df, ax=axarr[0][0])
# sns.boxplot(y='Age',x = 'Exited', hue = 'Exited',data = df , ax=axarr[0][1])
# sns.boxplot(y='Tenure',x = 'Exited', hue = 'Exited',data = df, ax=axarr[1][0])
# sns.boxplot(y='Balance',x = 'Exited', hue = 'Exited',data = df, ax=axarr[1][1])
# sns.boxplot(y='NumOfProducts',x = 'Exited', hue = 'Exited',data = df, ax=axarr[2][0])
# sns.boxplot(y='EstimatedSalary',x = 'Exited', hue = 'Exited',data = df, ax=axarr[2][1])
# plt.show()
#
#
# # Creating a pivot table demonstrating the percentile Of different genders and geographical regions in exiting the bank
# visualization_1 = df.pivot_table("Exited", index="Gender", columns="Geography")
# print(visualization_1)
#
# #
# # #Customer with 3 or 4 products are higher chances to Churn.Analysed through swarmplot
# # fig, axarr = plt.subplots(3, 2, figsize=(20, 12))
# # # plt.subplots_adjust(wspace=0.3)
# # sns.swarmplot(x = "NumOfProducts", y = "Age", hue="Exited", data = df, ax= axarr[0][0])
# # sns.swarmplot(x = "HasCrCard", y = "Age", data = df, hue="Exited", ax = axarr[0][1])
# # sns.swarmplot(x = "IsActiveMember", y = "Age", hue="Exited", data = df, ax = axarr[1][0])
# # plt.show()
#
#
# #Scatter-plot. categorical vs continuous variable distribution
# _, ax = plt.subplots(1, 2, figsize=(15, 7))
# cmap = sns.cubehelix_palette(light=1, as_cmap=True)
# sns.scatterplot(x = "Age", y = "Balance", hue = "Exited", cmap = cmap, sizes = (10, 200), data = df, ax=ax[0])
# sns.scatterplot(x = "Age", y = "CreditScore", hue = "Exited", cmap = cmap, sizes = (10, 200), data = df, ax=ax[1])
# plt.show()
# #interpertation:
# # 1.40 to 70 years old customers are higher chances to churn
# # 2.Customer with CreditScore less then 400 are higher chances to churn
#
#
# #swarmplot. descrete vs descrete variable
# plt.figure(figsize=(8, 8))
# sns.swarmplot(x = "HasCrCard", y = "Age", data = df, hue="Exited")
# plt.show()
#
#
# #Detecting outliers using boxplot
# plt.figure(figsize=(12,6))
# bplot = df.boxplot(patch_artist=True)
# plt.xticks(rotation=90)
# plt.show()
#
# #checking correlation
# plt.subplots(figsize=(11,8))
# sns.heatmap(df.corr(), annot=True, cmap="RdYlBu")
# plt.show()
#Predictive model building
# Shuffling the dataset
churn_dataset = df.reindex(np.random.permutation(df.index))
# Splitting feature data from the target
data = churn_dataset.drop("Exited", axis=1)
target = churn_dataset["Exited"]
#Scale contiuous variables
scaler = MinMaxScaler()
bumpy_features = ["CreditScore", "Age", "Balance",'EstimatedSalary']
df_scaled = pd.DataFrame(data = data)
df_scaled[bumpy_features] = scaler.fit_transform(data[bumpy_features])
df_scaled.head()
X = df_scaled
# X=data
# code categorical variable values into numerical values.solves ValueError: could not convert string to float: 'Spain'
encoder = LabelEncoder()
X["Geography"] = encoder.fit_transform(X["Geography"])
X["Gender"] = encoder.fit_transform(X["Gender"])
#else u can use one-hot encoding
# list_cat = ['geography', 'gender']
# training_data = pd.get_dummies(training_data, columns = list_cat, prefix = list_cat)
# Splitting feature data and target into training and testing
X_train, X_test, y_train, y_test = train_test_split(X, target, test_size=0.2, random_state=0)
# Creating a python list containing all defined models
model = [GaussianNB(), KNeighborsClassifier(), SVC(), DecisionTreeClassifier(), RandomForestClassifier(n_estimators=5, random_state=0), LogisticRegression()]
model_names = ["Gaussian Naive bayes", "K-nearest neighbors", "Support vector classifier", "Decision tree classifier", "Random Forest", "Logistic Regression",]
for i in range(0, 6):
y_pred =model[i].fit(X_train, y_train).predict(X_test)
accuracy = accuracy_score(y_pred, y_test)*100
print(model_names[i], ":", accuracy, "%")
# Working with the selected model
model = RandomForestClassifier(n_estimators = 100, random_state = 0)
y_pred = model.fit(X_train, y_train).predict(X_test)
print("Our accuracy is:", accuracy_score(y_pred, y_test)*100, "%")
clf = XGBClassifier(max_depth = 10,random_state = 10, n_estimators=220, eval_metric = 'auc', min_child_weight = 3,
colsample_bytree = 0.75, subsample= 0.9)
clf.fit(X_train, y_train)
pred = clf.predict(X_test)
accuracy_score(pred, y_test)
#Working with unbalanced data - Over Sampling
sm = SMOTE(random_state=42)
X_res, y_res = sm.fit_sample(X, target)
X_train, X_test, y_train, y_test = train_test_split(X_res, y_res, test_size= 0.2, random_state=7)
clf = XGBClassifier(max_depth = 12,random_state=7, n_estimators=100, eval_metric = 'auc', min_child_weight = 3,
colsample_bytree = 0.75, subsample= 0.8)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(y_test, y_pred))
print("Recall:", recall_score(y_test, y_pred))
print("F1:", f1_score(y_test, y_pred))
print("Area under precision (AUC) Recall:", average_precision_score(y_test, y_pred))
#confusion matrix (true positive,true negative,false positive,false negative count)
print(confusion_matrix(y_test, y_pred))
# https://machinelearningmastery.com/how-to-score-probability-predictions-in-python/
# three scoring methods that you can use to evaluate the predicted probabilities on your classification predictive modeling problem.
# log loss score - heavily penalizes predicted probabilities far away from their expected value.
# Brier score - penalizes proportional to the distance from the expected value.
# area under ROC curve - summarizes the likelihood of the model predicting a higher probability for true positive cases than true negative cases
#
# Log Loss
# ---------
# Log loss, also called “logistic loss,” “logarithmic loss,” or “cross entropy” can be used as a measure for evaluating predicted probabilities.
# Each predicted probability is compared to the actual class output value (0 or 1) and a score is calculated that penalizes the probability based on the distance from the expected value.
# The penalty is logarithmic, offering a small score for small differences (0.1 or 0.2) and enormous score for a large difference (0.9 or 1.0).
# A model with perfect skill has a log loss score of 0.0.
# In order to summarize the skill of a model using log loss, the log loss is calculated for each predicted probability, and the average loss is reported.
from sklearn.metrics import log_loss
model=clf
# predict probabilities
probs = model.predict_proba(X_test)
# keep the predictions for class 1 only
probs = probs[:, 1]
# calculate log loss
loss = log_loss(y_test, probs)
print ("Log Loss Score: ",loss)
#do the rest..........
model = [GaussianNB(), KNeighborsClassifier(), SVC(probability=True), DecisionTreeClassifier(), RandomForestClassifier(n_estimators=5, random_state=0), LogisticRegression()]
test_labels1 = model[1].fit(X_train, y_train).predict_proba(X_test)[:, 1]
test_labels2 = model[2].fit(X_train, y_train).predict_proba(X_test)[:, 1]
test_labels3 = model[3].fit(X_train, y_train).predict_proba(X_test)[:, 1]
test_labels4 = model[4].fit(X_train, y_train).predict_proba(X_test)[:, 1]
test_labels5 = model[5].fit(X_train, y_train).predict_proba(X_test)[:, 1]
fpr_gau, tpr_gau, _ = roc_curve(y_test, test_labels1)
fpr_knn, tpr_knn, _ = roc_curve(y_test, test_labels2)
fpr_svc, tpr_svc, _ = roc_curve(y_test, test_labels3)
fpr_dt, tpr_dt, _ = roc_curve(y_test, test_labels4)
fpr_rf, tpr_rf, _ = roc_curve(y_test, test_labels5)
# ROC curve
gau_roc_auc = roc_auc_score(y_test, test_labels1, average='macro', sample_weight=None)
knn_roc_auc = roc_auc_score(y_test, test_labels2, average='macro', sample_weight=None)
svc_roc_auc = roc_auc_score(y_test, test_labels3, average='macro', sample_weight=None)
dt_roc_auc = roc_auc_score(y_test, test_labels4, average='macro', sample_weight=None)
rf_roc_auc = roc_auc_score(y_test, test_labels5, average='macro', sample_weight=None)
plt.figure(figsize=(12, 6), linewidth=1)
plt.plot(fpr_gau, tpr_gau, label='GaussianNB Score: ' + str(round(gau_roc_auc, 5)))
plt.plot(fpr_knn, tpr_knn, label='KNN Score: ' + str(round(knn_roc_auc, 5)))
plt.plot(fpr_svc, tpr_svc, label='SVC Score: ' + str(round(svc_roc_auc, 5)))
plt.plot(fpr_dt, tpr_dt, label='DecisionTreeClassifier Score: ' + str(round(dt_roc_auc, 5)))
plt.plot(fpr_rf, tpr_rf, label='RandomForestClassifier Score: ' + str(round(rf_roc_auc, 5)))
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC Curve ')
plt.legend(loc='best')
plt.show()
#High ROC score is good
#Optimization
#1. Cross-validation
#2. Hyperparameter tuning
# Implementing a cross-validation based approach¶
# Import the cross-validation module
from sklearn.model_selection import cross_val_score
# Function that will track the mean value and the standard deviation of the accuracy
def cvDictGen(functions, scr, X_train=X_train, y_train=y_train, cv=5):
cvDict = {}
for func in functions:
cvScore = cross_val_score(func, X_train, y_train, cv=cv, scoring=scr)
cvDict[str(func).split('(')[0]] = [cvScore.mean(), cvScore.std()]
return cvDict
cvD = cvDictGen(model, scr = 'roc_auc')
print(cvD)
# if both mean and std are high that is good model
#Implementing hyperparameter tuning¶
# Import methods
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
#do the rest
# https://www.kaggle.com/bandiang2/prediction-of-customer-churn-at-a-bank |
934b6d7380894f97cd0c7420c7edf31a1767ce0e | ghawk0/ai-final-proj | /schedule.py | 660 | 3.96875 | 4 | # round robin algorithm for getting pairings of teams
def robin(teams, matchups=None):
if len(teams) % 2:
teams.append(None)
count = len(teams)
matchups = matchups or (count-1)
half = count/2
schedule = []
for round in range(matchups):
pairs = []
for i in range(half):
if (teams[i] is None) or (teams[count-i-1] is None):
none = True
else:
pairs.append(teams[i], teams[count-i-1])
teams.insert(1,teams.pop())
schedule.append(pairs)
return schedule
if __name__=='__main__':
for pairings in robin(range(5)):
print(pairings)
|
45031662df9be1dafbac90323ea6b977949328f5 | Jerwinprabu/practice | /reversepolish.py | 596 | 4.34375 | 4 | #!/usr/bin/python
"""
reverse polish notation evaluator
Functions that define the operators and how to evaluate them.
This example assumes binary operators, but this is easy to extend.
"""
ops = {
"+" : (lambda a, b: a + b),
"-" : (lambda a, b: a - b),
"*" : (lambda a, b: a * b)
}
def eval(tokens):
stack = []
for token in tokens:
if token in ops:
arg2 = stack.pop()
arg1 = stack.pop()
result = ops[token](arg1, arg2)
stack.append(result)
else:
stack.append(int(token))
return stack.pop()
print "Result:", eval("7 2 3 + -".split())
|
f8c4a3da8fa11ea8dda655f5e1aa03e8484208e5 | Jerwinprabu/practice | /reverse.py | 439 | 4 | 4 | #!/usr/bin/python
def reverse(arr):
if not arr: return
i, j = 0, len(arr)-1
while j > i:
arr[i], arr[j] = arr[j], arr[i]
i+=1
j-=1
return arr
def rotate(arr, n):
a = arr[:]
a = reverse(a)
a[n:] = reverse(a[n:])
a[:n] = reverse(a[:n])
return a
def test():
arr = [1,2,3,4,5]
print arr, rotate(arr, 1)
print arr, rotate(arr, 2)
if __name__ == "__main__":
test()
|
c195247fac44336cb05a705d803ed3070839eead | Jerwinprabu/practice | /subsets.py | 889 | 3.796875 | 4 | #!/usr/bin/python
""" find all subsets of a set """
import random
def subsets(array):
if len(array):
yield [array[0]]
for subset in subsets(array[1:]):
yield subset
yield subset + [array[0]]
def genadj(count):
return count * "()"
def genrec(count):
for p in paren(count-1):
yield "(" + p + ")"
def paren(count, gensymm=True):
if count == 0:
return
else:
if gensymm:
yield genadj(count)
for p in paren(count-1, False):
yield "()" + p
yield p + "()"
for p in paren(count-1):
yield "(" + p + ")"
def test():
ints = [1, 2, 3]
print "ints {}".format(ints)
print "perm: {}".format([x for x in subsets(ints)])
print "paren: {}".format([x for x in paren(4)])
if __name__ == "__main__":
test()
|
d18d10a6fe1ce761b70b798e27754f497579011f | kengo-0805/pythonPractice | /day3.py | 520 | 3.953125 | 4 | '''
# 問題3-1
x = input("1つ目の数字:")
y = input("2つ目の数字:")
s1 = float(x)
s2 = float(y)
if s2 == 0:
print("0での割り算はできません")
else:
print("足し算:{} 引き算:{} 掛け算:{} 割り算:{}".format(s1+s2,s1-s2,s1*s2,s1/s2))
'''
# 問題3-2
text = input("文字を入力してください:")
count = len(text)
if count < 5:
print("短い文章")
elif 5 < count < 20:
print("中くらいの文章")
elif count < 20:
print("長い文章")
print(count) |
674ad6981f92ca3d53b1cc9a44d602bb28b76e4f | lcar99/URI | /Python 3/1018.py | 353 | 3.65625 | 4 | d = int (input ())
print (d)
print (d//100 , "nota(s) de R$ 100,00")
d = d % 100
print (d//50 , "nota(s) de R$ 50,00")
d = d % 50
print (d//20 , "nota(s) de R$ 20,00")
d = d % 20
print (d//10 , "nota(s) de R$ 10,00")
d = d % 10
print (d//5 , "nota(s) de R$ 5,00")
d = d % 5
print (d//2 , "nota(s) de R$ 2,00")
d = d % 2
print (d , "nota(s) de R$ 1,00")
|
5e9ebc5cbdad88b893dd0e537f54f67b132868ed | LamLauChiu/Tensorflow_Learning | /TextClassification/textClassification.py | 10,464 | 4.21875 | 4 | """
This notebook classifies movie reviews as positive or negative using the text of the review.
This is an example of binary—or two-class—classification, an important and widely applicable kind of machine learning problem.
We'll use the IMDB dataset that contains the text of 50,000 movie reviews from the Internet Movie Database.
These are split into 25,000 reviews for training and 25,000 reviews for testing.
The training and testing sets are balanced, meaning they contain an equal number of positive and negative reviews.
This notebook uses tf.keras, a high-level API to build and train models in TensorFlow.
For a more advanced text classification tutorial using tf.keras, see the MLCC Text Classification Guide.
"""
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
import numpy as np
print(tf.__version__)
"""
IMDB dataset
The IMDB dataset comes packaged with TensorFlow.
It has already been preprocessed such that the reviews (sequences of words) have been converted to sequences of integers,
where each integer represents a specific word in a dictionary.
The argument num_words=10000 keeps the top 10,000 most frequently occurring words in the training data.
The rare words are discarded to keep the size of the data manageable.
"""
imdb = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
#print("Training entries: {}, labels: {}".format(len(train_data), len(train_labels)))
"""
Explore the data
Let's take a moment to understand the format of the data.
The dataset comes preprocessed: each example is an array of integers representing the words of the movie review.
Each label is an integer value of either 0 or 1, where 0 is a negative review, and 1 is a positive review.
"""
#print(train_data[0])
#len(train_data[0]), len(train_data[1])
"""
It may be useful to know how to convert integers back to text.
Here, we'll create a helper function to query a dictionary object that contains the integer to string mapping:
"""
# A dictionary mapping words to an integer index
word_index = imdb.get_word_index()
# The first indices are reserved
word_index = {k:(v+3) for k,v in word_index.items()}
word_index["<PAD>"] = 0
word_index["<START>"] = 1
word_index["<UNK>"] = 2 # unknown
word_index["<UNUSED>"] = 3
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
# decode_review function to display the text for the first review:
def decode_review(text):
return ' '.join([reverse_word_index.get(i, '?') for i in text])
decode_review(train_data[0])
print(decode_review(train_data[0]))
"""
Prepare the data
The reviews—the arrays of integers—must be converted to tensors before fed into the neural network.
This conversion can be done a couple of ways:
Convert the arrays into vectors of 0s and 1s indicating word occurrence, similar to a one-hot encoding.
For example, the sequence [3, 5] would become a 10,000-dimensional vector that is all zeros except for indices 3 and 5,
which are ones. Then, make this the first layer in our network—a Dense layer—that can handle floating point vector data.
This approach is memory intensive, though, requiring a num_words * num_reviews size matrix.
Alternatively, we can pad the arrays so they all have the same length, then create an integer tensor of shape max_length * num_reviews.
We can use an embedding layer capable of handling this shape as the first layer in our network.
In this tutorial, we will use the second approach.
"""
"""
Build the model
The neural network is created by stacking layers—this requires two main architectural decisions:
How many layers to use in the model?
How many hidden units to use for each layer?
In this example, the input data consists of an array of word-indices.
The labels to predict are either 0 or 1. Let's build a model for this problem:
"""
train_data = keras.preprocessing.sequence.pad_sequences(train_data,
value=word_index["<PAD>"],
padding='post',
maxlen=256)
test_data = keras.preprocessing.sequence.pad_sequences(test_data,
value=word_index["<PAD>"],
padding='post',
maxlen=256)
len(train_data[0]), len(train_data[1])
print(train_data[0])
"""
The layers are stacked sequentially to build the classifier:
1. The first layer is an Embedding layer. This layer takes the integer-encoded vocabulary and looks up the embedding vector for each word-index.
These vectors are learned as the model trains. The vectors add a dimension to the output array.
The resulting dimensions are: (batch, sequence, embedding).
2. Next, a GlobalAveragePooling1D layer returns a fixed-length output vector for each example by averaging over the sequence dimension.
This allows the model to handle input of variable length, in the simplest way possible.
3. This fixed-length output vector is piped through a fully-connected (Dense) layer with 16 hidden units.
4. The last layer is densely connected with a single output node. Using the sigmoid activation function,
this value is a float between 0 and 1, representing a probability, or confidence level.
"""
# input shape is the vocabulary count used for the movie reviews (10,000 words)
vocab_size = 10000
model = keras.Sequential()
model.add(keras.layers.Embedding(vocab_size, 16))
model.add(keras.layers.GlobalAveragePooling1D())
model.add(keras.layers.Dense(16, activation=tf.nn.relu))
model.add(keras.layers.Dense(1, activation=tf.nn.sigmoid))
model.summary()
"""
Hidden units
The above model has two intermediate or "hidden" layers, between the input and output.
The number of outputs (units, nodes, or neurons) is the dimension of the representational space for the layer.
In other words, the amount of freedom the network is allowed when learning an internal representation.
If a model has more hidden units (a higher-dimensional representation space), and/or more layers,
then the network can learn more complex representations. However, it makes the network more computationally expensive
and may lead to learning unwanted patterns—patterns that improve performance on training data but not on the test data.
This is called overfitting, and we'll explore it later.
Loss function and optimizer
A model needs a loss function and an optimizer for training.
***
Since this is a binary classification problem and the model outputs a probability (a single-unit layer with a sigmoid activation),
we'll use the binary_crossentropy loss function.
This isn't the only choice for a loss function, you could, for instance, choose mean_squared_error.
But, generally, binary_crossentropy is better for dealing with probabilities—it measures the "distance" between probability distributions,
or in our case, between the ground-truth distribution and the predictions.
Later, when we are exploring regression problems (say, to predict the price of a house),
we will see how to use another loss function called mean squared error.
Now, configure the model to use an optimizer and a loss function:
"""
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['acc'])
"""
Create a validation set
When training, we want to check the accuracy of the model on data it hasn't seen before.
Create a validation set by setting apart 10,000 examples from the original training data.
(Why not use the testing set now?
Our goal is to develop and tune our model using only the training data,
then use the test data just once to evaluate our accuracy).
"""
x_val = train_data[:10000]
partial_x_train = train_data[10000:]
y_val = train_labels[:10000]
partial_y_train = train_labels[10000:]
"""
Train the model
Train the model for 40 epochs in mini-batches of 512 samples.
This is 40 iterations over all samples in the x_train and y_train tensors.
While training, monitor the model's loss and accuracy on the 10,000 samples from the validation set:
"""
history = model.fit(partial_x_train,
partial_y_train,
epochs=40,
batch_size=512,
validation_data=(x_val, y_val),
verbose=1)
"""
Evaluate the model
And let's see how the model performs.
Two values will be returned. Loss (a number which represents our error, lower values are better), and accuracy.
"""
results = model.evaluate(test_data, test_labels)
print(results)
#This fairly naive approach achieves an accuracy of about 87%. With more advanced approaches, the model should get closer to 95%.
"""
Create a graph of accuracy and loss over time
model.fit() returns a History object that contains a dictionary with everything that happened during training:
"""
history_dict = history.history
history_dict.keys()
# dict_keys(['loss', 'acc', 'val_loss', 'val_acc'])
"""
There are four entries: one for each monitored metric during training and validation.
We can use these to plot the training and validation loss for comparison, as well as the training and validation accuracy:
"""
import matplotlib.pyplot as plt
acc = history_dict['acc']
val_acc = history_dict['val_acc']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
epochs = range(1, len(acc) + 1)
# "bo" is for "blue dot"
plt.plot(epochs, loss, 'bo', label='Training loss')
# b is for "solid blue line"
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
plt.clf() # clear figure
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
#<Figure size 640x480 with 1 Axes> |
dd172806613ef476404aa4771dec704bb411281c | durveshpathak/Udacity_Data_structure_III | /problem_5.py | 2,036 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 27 18:03:18 2019
@author: durvesh
"""
class TrieNode():
def __init__(self):
self.is_word = False
self.children = {}
def insert(self, char):
if char not in self.children:
self.children[char] = TrieNode()
else:
pass
def suffixes(self, suffix = ''):
stored_suffix = []
if self.is_word and suffix!= '':
stored_suffix.append(suffix)
if len(self.children) == 0:
return stored_suffix
for char in self.children:
stored_suffix.extend(self.children[char].suffixes(suffix=suffix+char))
return stored_suffix
class Trie():
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
node.insert(char)
node = node.children[char]
node.is_word = True
def find(self, prefix):
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return node
MyTrie = Trie()
wordList = [
"ant", "anthropology", "antagonist", "antonym",
"fun", "function", "factory",
"trie", "trigger", "trigonometry", "tripod"
]
for word in wordList:
MyTrie.insert(word)
from ipywidgets import widgets
from IPython.display import display
from ipywidgets import interact
def f(prefix):
if prefix != '':
prefixNode = MyTrie.find(prefix)
if prefixNode:
print('\n'.join(prefixNode.suffixes()))
else:
print(prefix + "not found")
else:
print('')
#Test Case 1
interact(f,prefix='a');
"""
nt
ntagonist
ntonym
nthropology
"""
#Test Case 3
interact(f,prefix='tr');
"""
ipod
igonometry
igger
ie
"""
#Test Case 4
interact(f,prefix='');
"""
"""
|
8c7bc323fac2fe5a512c70597af0f99492522323 | Rutvik2610/Python-Playground | /Mile to Km Converter using Tkinter/main.py | 668 | 3.921875 | 4 | from tkinter import *
def convert():
miles = float(miles_input.get())
km = round(miles * 1.609)
km_output.config(text=f"{km}")
window = Tk()
window.title("Mile to Km Converter")
window.config(padx=20, pady=20)
miles_input = Entry(width=7)
miles_input.grid(row=0, column=1)
miles_input.insert(END, string="0")
label1 = Label(text="Miles")
label1.grid(row=0, column=2)
label2 = Label(text="is equal to")
label2.grid(row=1, column=0)
km_output = Label(text="0")
km_output.grid(row=1, column=1)
label4 = Label(text="Km")
label4.grid(row=1, column=2)
button = Button(text="Calculate", command=convert)
button.grid(row=2, column=1)
window.mainloop()
|
768377a03d93071676d31e1f6ee93f9d6b9e8c8c | Krysta1/Offer-Java | /src/leetcode/116. Populating Next Right Pointers in Each Node.py | 1,931 | 3.84375 | 4 | # My solution
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=0, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root:
return None
stack = []
stack.append(root)
root.next = None
while stack:
total = len(stack)
for i in range(total):
pre = stack.pop(0)
if i != total - 1:
pre.next = stack[0]
else:
pre.next = None
if pre.left:
stack.append(pre.left)
if pre.right:
stack.append(pre.right)
return root
# Discussion
class Solution(object):
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
cur = root # current node of current level
head = Node(0) # head of the next level
pre = head # the current node on the next level
while cur:
# if cur has left node, connect pre and cur.left, move cur forward
if cur.left:
pre.next = cur.left
pre = pre.next
# if cur has right node, connect pre and cur.right, move cur forward
if cur.right:
pre.next = cur.right
pre = pre.next
# if cur has next, move cur to the next
if cur.next:
cur = cur.next
# if not, cur = next level's head node, disconnect the head the the first node in the next level
# so as pre
else:
cur = head.next
head.next = None
pre = head
return root
|
5f76999608f0d7951f8b765ba07114542d975b19 | Krysta1/Offer-Java | /src/leetcode/111. Minimum Depth of Binary Tree.py | 1,853 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# self.res = 2e16
# if not root:
# return 0
# self.dfs(root, 1)
# return self.res
# def dfs(self, root, depth):
# if not root.left and not root.right:
# self.res = min(depth, self.res)
# return
# if root.left:
# self.dfs(root.left, depth + 1)
# if root.right:
# self.dfs(root.right, depth + 1)
# res = 2e16
# if not root:
# return 0
# queue = []
# queue.append(root)
# depth = 0
# while queue:
# length = len(queue)
# depth += 1
# while length > 0:
# node = queue.pop(0)
# length -= 1
# if not node.left and not node.right:
# return depth
# if node.left:
# queue.append(node.left)
# if node.right:
# queue.append(node.right)
# return res
if not root:
return 0
if None in [root.left, root.right]:
return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
else:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
|
f6ddb9c5c6a5f76958ac9f732192e80f438d9b41 | ataicher/learn_to_code | /careeCup/#q17.py# | 1,031 | 3.875 | 4 | #!/usr/bin/python -tt
import sys
import numpy as np
def set_zero_rows_cols(M,m,n):
nonZeroCols = range(n)
zeroRows = []; zeroCols = []
newZeroRow = False
for i in range(m):
j = 0
while j < len(nonZeroCols):
cnt += 1
if M[i,nonZeroCols[j]] == 0:
zeroRows.append(i); zeroCols.append(j); newZeroRow = True
break
j += 1
if newZeroRow:
nonZeroCols.remove(j)
newZeroRow = False
for j in zeroCols:
for i in range(m):
M[i,j] = 0
for i in zeroRows:
for j in nonZeroCols:
M[i,j] = 0
def main():
print 'set to zero rows and columns that have a zero entry in an mxn matrix'
if len(sys.argv) >= 2:
M = np.matrix(sys.argv[1])
print M
else:
M = np.matrix('1 2 3 0 ; 1 2 3 4 ; 0 2 3 4; 1 2 3 4')
print 'using default matrix:'
print M
(m,n) = M.shape
set_zero_rows_cols(M,m,n)
print 'the new matrix:'
print M
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
|
c5363e8be7c3e46cd35561d83880c3162f6ece0f | ataicher/learn_to_code | /careeCup/q14.py~ | 911 | 4.3125 | 4 | #!/usr/bin/python -tt
import sys
def isAnagram(S1,S2):
# remove white space
S1 = S1.replace(' ',''); S2 = S2.replace(' ','')
# check the string lengths are identical
if len(S1) != len(S2):
return False
# set strings to lower case
S1 = S1.lower(); S2 = S2.lower()
# sort strings
S1 = sorted(S1); S2 = sorted(S2)
if S1 == S2:
return True
else:
return False
def main():
print 'find out if two strings are anagrams'
if len(sys.argv) == 3:
S1 = sys.argv[1]
S2 = sys.argv[2]
print 'S1 =', S1
print 'S2 =', S2
else:
S1 = 'Namibia'
S2 = 'I am a bin'
print 'using default strings:\nS1 = Namibia\nS2 = I am a bin'
if isAnagram(S1,S2):
print 'the two strings are anagrams!'
else:
print 'sorry. The two strings are not anagrams'
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
|
389269b6491879b987a72d5d907e49f315be8faa | ataicher/learn_to_code | /careeCup/make_change.py | 426 | 3.703125 | 4 | #!/usr/bin/python -tt
import sys
import time
def make_change(n,d):
if d == 25:
n_d = 10
elif d == 10:
n_d = 5
elif d == 5:
n_d = 1
else:
return 1
ways = 0
for i in range(n/d+1):
ways += make_change(n-i*d,n_d)
return ways
def main():
n = int(sys.argv[1])
print make_change(n,25)
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
|
9317aaa0cb94a12b89f6960525791598088003d6 | HeavenRicks/dto | /primary.py | 2,273 | 4.46875 | 4 | #author: <author here>
# date: <date here>
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that prints the sum of two numbers
# 2 - create a print statement that prints the sum of three numbers
# 3 - create a print statement the prints the sum of two negative numbers
print(7+3)
print(3+6+2)
print(-5+-7)
# subtraction
# instructions
# 1 - create a print statement that prints the difference of two numbers
# 2 - create a print statement that prints the difference of three numbers
# 3 - create a print statement the prints the difference of two negative numbers
print(10-4)
print(24-8-3)
print(-9--3)
# multiplication and true division
# instructions
# 1 - create a print statement the prints the product of two numbers
# 2 - create a print statement that prints the dividend of two numbers
# 3 - create a print statement that evaluates an operation using both multiplication and division
print(8*4)
print(16/2)
print(4*6/2)
# floor division
# instructions
# 1 - using floor division, print the dividend of two numbers.
print(24//8)
# exponentiation
# instructions
# 1 - using exponentiation, print the power of two numbers
print(18**2)
# modulus
# instructions
# 1 - using modulus, print the remainder of two numbers
print(50%7)
# --------------- Section 2 --------------- #
# ---------- String Concatenation --------- #
# concatenation
# instructions
# 1 - print the concatenation of your first and last name
# 2 - print the concatenation of five animals you like
# 3 - print the concatenation of each word in a phrase
print('Heaven' + 'Ricks')
print('Dolphins'+'Pandas'+'Monkeys'+'Goats'+'Horse')
print('i'+'love'+'dolphins')
# duplication
# instructions
# 1 - print the duplpication of your first name 5 times
# 2 - print the duplication of a song you like 10 times
print('heaven'*5)
print('solid'*10)
# concatenation and duplpication
# instructions
# 1 - print the concatenation of two strings duplicated 3 times each
print('Heaven'+'Ricks'*3) |
e964bf6249b52ab72b188dcc18cb4f73b915c6e2 | PropeReferio/practice-exercises | /random_exercises/GuessNumberHiLow.py | 621 | 4.03125 | 4 | # From Intro to Python Crash Course, Eric Matthes
def guess():
print("I'm thinking of a number between 1 and 99.")
import random
num = random.randint(1,100)
g = int(input("Guess!"))
while g != num:
if g > num:
print("Nope, you're too high! Try again.")
else:
print("Nope, too low! Try again.")
g = int(input("Guess!"))
again = input("Great guess! Want to play again?")
while again != "yes" or "no":
again = input("What did you say?")
if again == "yes":
guess()
elif again == "no":
print("Thanks for playing!")
guess() |
f1f2b09a5a7d9453ee9ca98f74d12f73e75a182a | PropeReferio/practice-exercises | /important-concepts/get_digit.py | 823 | 3.8125 | 4 | import math
class Solution:
def get_digit(self, x: int, dig: int) -> int:
'''Takes an int an a digit as input, outputs the value of said digit.'''
return x // 10 ** dig % 10
# First floor division by 10 for 10's place,
# 100 for 100's place, etc (puts 100's place digit in 1's place)
# Then get the remainder of division by 10 to get digit's value
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
elif x == 0:
return True
left_dig, right_dig = int(math.log10(x)), 0
print(left_dig)
while left_dig > right_dig:
if self.get_digit(x, left_dig) != self.get_digit(x, right_dig):
return False
left_dig -= 1
right_dig += 1
return True |
9c4378edfdb41a942286830610d4bf2c24d2535f | PropeReferio/practice-exercises | /daily-coding-problem/dcp_10.py | 266 | 3.71875 | 4 | #This problem was asked by Apple.
#Implement a job scheduler which takes in a function f and an integer n,
# and calls f after n milliseconds.
import time
def scheduler(func, n):
time.sleep(n/1000)
f()
def f():
print('Do stuff')
scheduler(f, 5000)
|
07439e13efd7e16d993733605018fd0624c65820 | PropeReferio/practice-exercises | /random_exercises/alien_colors.py | 339 | 3.828125 | 4 | # Ex 5-3 from Python Crash Course
alien_color = 'red'
points = 0
if alien_color == 'green':
points += 5
print(f"Player 1 earned {points} points.")
elif alien_color == 'yellow':
points += 10
print(f"Player 1 earned {points} points.")
elif alien_color == 'red':
points += 15
print(f"Player 1 earned {points} points.") |
796c9387dce8f55b1a2a7efd90438bdff7eee5c8 | PropeReferio/practice-exercises | /random_exercises/filter_with_lambda_enumerate.py | 514 | 3.59375 | 4 | def multiple_of_index(arr):
print(arr)
for i, x in enumerate(arr):
print(i,x)
def divisible_by_index(lst):
for i, x in enumerate(lst):
if not x % i:
return True
else:
return False
#return list(filter(divisible_by_index, arr[1:]))
#The problem is that filter wants to run my function on each item of arr[:1], but those can't be enumerated.
#use enumerate
#my_enumerate = lambda x :[(t, x[t]) for t in range(len(x))] |
89a8e2146e366ce54617134d314e68d81c6b340a | PropeReferio/practice-exercises | /random_exercises/cars.py | 282 | 3.890625 | 4 | def car_info(manu, model, **car_info):
"""Creates a dictionary with info about a car that can receive an
arbitrary number of k,v pairs"""
car = {}
car['manufacturer'] = manu
car['model'] = model
for k, v in car_info.items():
car[k] = v
return car |
93dedb445a3623c144f6b064941685eea52144d8 | PropeReferio/practice-exercises | /random_exercises/opportunity_costs.py | 5,771 | 4.125 | 4 | # A program I made to compare my lifetime earnings in my current career, and
#after having taken a bootcamp, or going to college, taking into account
#cost of bootcamp/school and the time spent not making money.
current_age = float(input("How old are you? "))
retire_age = int(input("At what age do you expect to retire? ")) #The program
#could be further refined by having different retirement ages for different
#careers.
current_career = input("What is your current career? ")
current_income = int(input("What are the yearly earnings in your current"
" career? "))
bootcamp_income = int(input("What salary would you earn after a coding"
" bootcamp? "))
bootcamp_months = float(input("How many months does the bootcamp take? "))
bootcamp_years = bootcamp_months / 12 #Converts to years
bootcamp_cost = int(input("How much does the bootcamp cost? "))
college_income = int(input("What salary would you make after earning a"
" degree? "))
college_years = int(input("How many years would you spend in college? "))
college_cost = int(input("What would tuition cost per year? "))
total_tuition = int(college_cost * college_years)
def tax_rate(salary, career): #Based on 2019 Brackets,
if salary <= 39475: #determines effective tax rate and salary, filing
bracket1 = 9700 * 0.9 #singly, ignores deductions
bracket2 = (salary - 9700) * 0.88
after_tax = bracket1 + bracket2
taxes = salary - after_tax
eff_rate = taxes / salary
print(f"Your income after taxes in {career} would be {after_tax}. "
f"Your effective tax rate would be {eff_rate}.")
return after_tax
elif salary <= 84200:
bracket1 = 9700 * 0.9
bracket2 = (39475 - 9700) * 0.88
bracket3 = (salary - 39475) * 0.78
after_tax = bracket1 + bracket2 + bracket3
taxes = salary - after_tax
eff_rate = taxes / salary
print(f"Your income after taxes in {career} would be {after_tax}. "
f"Your effective tax rate would be {eff_rate}.")
return after_tax
elif salary <= 160725:
bracket1 = 9700 * 0.9
bracket2 = (39475 - 9700) * 0.88
bracket3 = (84200 - 39475) * 0.78
bracket4 = (salary - 84200) * 0.76
after_tax = bracket1 + bracket2 + bracket3 + bracket4
taxes = salary - after_tax
eff_rate = taxes / salary
print(f"Your income after taxes in {career} would be {after_tax}. "
f"Your effective tax rate would be {eff_rate}.")
return after_tax
elif salary <= 204100:
bracket1 = 9700 * 0.9
bracket2 = (39475 - 9700) * 0.88
bracket3 = (84200 - 39475) * 0.78
bracket4 = (160725 - 84200) * 0.76
bracket5 = (salary - 160725) * 0.68
after_tax = bracket1 + bracket2 + bracket3 + bracket4 + bracket5
taxes = salary - after_tax
eff_rate = taxes / salary
print(f"Your income after taxes in {career} would be {after_tax}. "
f"Your effective tax rate would be {eff_rate}.")
return after_tax
elif salary <= 510300:
bracket1 = 9700 * 0.9
bracket2 = (39475 - 9700) * 0.88
bracket3 = (84200 - 39475) * 0.78
bracket4 = (160725 - 84200) * 0.76
bracket5 = (204100 - 160725) * 0.68
bracket6 = (salary - 204100) * 0.65
after_tax = bracket1 + bracket2 + bracket3 + bracket4 + bracket5 + bracket6
taxes = salary - after_tax
eff_rate = taxes / salary
print(f"Your income after taxes in {career} would be {after_tax}. "
f"Your effective tax rate would be {eff_rate}.")
elif salary > 510300:
bracket1 = 9700 * 0.9
bracket2 = (39475 - 9700) * 0.88
bracket3 = (84200 - 39475) * 0.78
bracket4 = (160725 - 84200) * 0.76
bracket5 = (204100 - 160725) * 0.68
bracket6 = (510300 - 204100) * 0.65
bracket7 = (salary - 510300) * 0.63
after_tax = bracket1 + bracket2 + bracket3 + bracket4 + bracket5 + bracket6 + bracket7
taxes = salary - after_tax
eff_rate = taxes / salary
print(f"Your income after taxes in {career} would be {after_tax}. "
f"Your effective tax rate would be {eff_rate}.")
return after_tax
#Determines lifetime earnings before taxes
def before_tax_lifetime(salary, career, time_spent = 0, cost = 0):
lifetime_earnings = int((retire_age - current_age - time_spent) * salary)
adjusted_for_learning = lifetime_earnings - cost
print(f"\nBefore taxes, your lifetime earnings would be "
f"{lifetime_earnings} in a career in {career}. Adjusted "
f"for learning costs, this would be {adjusted_for_learning}.")
def after_tax_lifetime(salary, career, time_spent = 0, cost = 0): #Determines
after_tax_salary = tax_rate(salary, career) #lifetime earnings after taxes
after_tax_lifetime_earnings = int((retire_age - current_age - time_spent)
* after_tax_salary)
adjusted_for_learning = after_tax_lifetime_earnings - cost
print(f"After taxes, your lifetime earnings would be "
f"{after_tax_lifetime_earnings} in a career in {career}. Adjusted "
f"for learning costs, this would be {adjusted_for_learning}.")
before_tax_lifetime(bootcamp_income, "Software Development", bootcamp_years,
bootcamp_cost)
after_tax_lifetime(bootcamp_income, "Software Development", bootcamp_years,
bootcamp_cost)
before_tax_lifetime(college_income, "a college career", college_years,
college_cost)
after_tax_lifetime(college_income, "a college career", college_years,
college_cost)
before_tax_lifetime(current_income, current_career)
after_tax_lifetime(current_income, current_career)
print("Please note that tax deductions are ignored here.")
#Add in a standard deduction |
2c4c928322977ee0f99b7bfe4a97728e09402656 | PropeReferio/practice-exercises | /random_exercises/temp_converter.py | 586 | 4.28125 | 4 | unit = input("Fahrenheit or Celsius?")
try_again = True
while try_again == True:
if unit == "Fahrenheit":
f = int(input("How many degrees Fahrenheit?"))
c = f / 9 * 5 - 32 / 9 * 5
print (f"{f} degrees Fahrenheit is {c} degrees Celsius.")
try_again = False
elif unit == "Celsius":
c = int(input("How many degrees Celsius?"))
f = c * 9 / 5 + 32
print (f"{c} degrees Celsius is {f} degrees Fahrenheit.")
try_again = False
else:
print ("What unit is that?")
unit = input("Fahrenheit or Celsius?") |
25cc7ac225f74fd71ba79e365a251a2daf83aeb7 | PropeReferio/practice-exercises | /random_exercises/rand_pass.py | 730 | 3.8125 | 4 | # Ex 16 from practicepython.org Write a password generator in Python. Be
#creative with how you generate passwords - strong passwords have a mix
# of lowercase letters, uppercase letters, numbers, and symbols. The
# passwords should be random, generating a new password every time the
# user asks for a new password. Include your run-time code in a main method.
def generate_password(s):
import random
pass_length = random.randint(8,20)
password = ""
while pass_length > 0:
new_char = s[random.randint(0, len(s) - 1)]
password += new_char
pass_length -= 1
return password
s = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()"
print(generate_password(s)) |
7b8aa1806a0084dfd6e189720fc10131d0e0b1b1 | PropeReferio/practice-exercises | /random_exercises/fave_fruits.py | 438 | 3.96875 | 4 | # Ex 5-7 from Python Crash Course
faves = ["Mangoes", "Papayas", "Maracuya"]
if "bananas" not in faves:
print("You don't like bananas?")
if "mangoes".title() in faves:
print("Yeah... mangoes are delish!")
if "papayas".title() in faves:
print("Papayas have a nice blend of flavors.")
if "Maracuya" in faves:
print("Maracuya makes great sauce for broccoli!")
if "apples" not in faves:
print("Apples are so overrated.") |
849c615ac2f77f6356650311deea9da6c32952bf | andrearus-dev/shopping_list | /myattempt.py | 1,719 | 4.1875 | 4 | from tkinter import *
from tkinter.font import Font
window = Tk()
window.title('Shopping List')
window.geometry("400x800")
window.configure(bg="#2EAD5C")
bigFont = Font(size=20, weight="bold")
heading1 = Label(window, text=" Food Glorious Food \n Shopping List",
bg="#2EAD5C", fg="#fff", font=bigFont).pack(pady=10)
# Adding input text to the list
def add_command():
text = entry_field.get()
for item in my_list:
list_layout.insert(END, text)
# Deleting one item at a time
def delete_command():
for item in my_list:
list_layout.delete(ACTIVE)
# Deleting all items with one click of a button
def delete_all_command():
list_layout.delete(0, END)
# Variable holding empty list
my_list = [""]
# Frame and scroll bar so the user can view the whole list
my_frame = Frame(window, bg="#00570D")
scrollBar = Scrollbar(my_frame, orient=VERTICAL)
# List box - where the items will be displayed
list_layout = Listbox(my_frame, width=40, height=20,
yscrollcommand=scrollBar.set)
list_layout.pack(pady=20)
# configure scrollbar
scrollBar.config(command=list_layout.yview)
scrollBar.pack(side=RIGHT, fill=Y)
my_frame.pack(pady=20)
heading2 = Label(window, text="Add items to your list \n Happy Shopping!",
bg="#2EAD5C", fg="#fff", font=1).pack(pady=5)
# Entry Field
entry_field = Entry(window)
entry_field.pack(pady=5)
# Buttons - when clicked the function is called
Button(window, text="Add Item", command=add_command).pack(pady=5)
Button(window, text="Delete Item", command=delete_command).pack(pady=5)
Button(window, text="Delete ALL Food Items",
command=delete_all_command).pack(pady=10)
window.mainloop()
|
74f7e45ab5fc619715f5e530b6790c65c51a3767 | caiooliveirac/Jogo-da-Forca | /core.py | 554 | 3.53125 | 4 | #Modelo de criação de diferentes arquivos txt com dificuldades diferentes baseados numa lista
arquivo = open('palavras2.txt',mode='r',encoding='utf8')
arquivo2 = open('palavras3.txt',mode='r',encoding='utf8')
todas = []
nivel = []
for linha in arquivo:
linha.strip()
todas.append(linha)
for palavra in arquivo2:
palavra.strip()
nivel.append(palavra)
with open('palavras2.txt','w',encoding='utf8') as arq:
for i, k in enumerate(todas):
if i > 0 and k not in nivel:
arq.write(f"{k}")
print(todas)
print(nivel)
|
66c823e68f5362768970826ee380e58da07b57d2 | jamesspearsv/cs50 | /pset6/mario/more/mario.py | 648 | 4.03125 | 4 | from cs50 import get_int
def main():
h = 0
while h < 1 or h > 8:
h = get_int("Height: ")
printPyramid(h)
# Function definitions
def printPyramid(h):
for i in range(h, 0, -1):
# Print left half
for j in range(h):
if j < i-1:
print(" ", end="")
else:
print("#", end="")
# Print gaps
print(" ", end="")
# Print right hal
for k in range(h, 0, -1):
if k <= i-1:
print("", end="")
else:
print("#", end="")
print() # Prints new line
# Main function
main() |
026dc30173ab7427f744b000f55558ffc19099e8 | glaxur/Python.Projects | /guess_game_fun.py | 834 | 4.21875 | 4 | """ guessing game using a function """
import random
computers_number = random.randint(1,100)
PROMPT = "What is your guess?"
def do_guess_round():
"""Choose a random number,ask user for a guess
check whether the guess is true and repeat whether the user is correct"""
computers_number = random.randint(1,100)
while True:
players_guess = int(input(PROMPT))
if computers_number == int(players_guess):
print("correct!")
break
elif computers_number > int(players_guess):
print("Too low")
else:
print("Too high")
while True:
print("Starting a new round")
print("The computer's number should be "+str(computers_number))
print("Let the guessing begin!!!")
do_guess_round()
print(" ")
|
19c763e647a12c9b697005354a86de78726e08b7 | lukechn99/leetcode | /nDistinct.py | 572 | 3.828125 | 4 | # given a string, find the number of substrings that have n distinct characters
# use sliding window
def distinct(string, ptr1, ptr2):
pass
def nDistinct(string, n):
ptr1 = 0
ptr2 = n
number_distinct = 0
while ptr1 < len(string) - n:
while ptr2 < len(string):
if distinct(string, ptr1, ptr2):
number_distinct += 1
ptr2 += 1
ptr1 += 1
ptr2 = ptr1 + n
return number_distinct
# we could also maintain a table of the characters and each time we slide we add or remove accordingly
|
d1a7e7a1efd779623129ce86fa8237e490690b4b | lukechn99/leetcode | /traverse.py | 264 | 3.5625 | 4 | import os
def traverse(dir):
print(dir)
tempcwd = os.getcwd()
if os.path.isdir(os.path.join(tempcwd, dir)):
for d in os.listdir(os.path.join(tempcwd, dir)):
os.chdir(os.path.join(tempcwd, dir))
traverse(d)
os.chdir(tempcwd)
traverse(".") |
4e9a3cb0737ffd797c2231646f57d6f00a14b4e9 | lukechn99/leetcode | /pleasePassTheCodedMessages.py | 2,429 | 3.984375 | 4 | # Please Pass the Coded Messages
# ==============================
# You need to pass a message to the bunny prisoners, but to avoid detection, the code you agreed
# to use is... obscure, to say the least. The bunnies are given food on standard-issue prison
# plates that are stamped with the numbers 0-9 for easier sorting, and you need to combine sets
# of plates to create the numbers in the code. The signal that a number is part of the code is
# that it is divisible by 3. You can do smaller numbers like 15 and 45 easily, but bigger numbers
# like 144 and 414 are a little trickier. Write a program to help yourself quickly create large
# numbers for use in the code, given a limited number of plates to work with.
# You have L, a list containing some digits (0 to 9). Write a function solution(L) which finds the
# largest number that can be made from some or all of these digits and is divisible by 3. If it is
# not possible to make such a number, return 0 as the solution. L will contain anywhere from 1 to 9
# digits. The same digit may appear multiple times in the list, but each element in the list may
# only be used once.
import unittest
import itertools
def solution(l):
return helper(sorted(l, reverse = True))
def helper(l):
if l == []:
return 0
if sum(l) % 3 != 0:
potentials = []
for i in range(len(l)):
new_l = l[:i] + l[i + 1:]
potentials.append(helper(new_l))
if potentials == []:
return 0
return max(potentials)
else:
str_list = [str(n) for n in l]
cur_perm = "".join(str_list)
int_cur_perm = int(cur_perm)
return int_cur_perm
# wrong solution, we must consider subsets
# def solution(l):
# perm = list(itertools.permutations(l))
# max = 0
# for p in perm:
# # convert to int
# str_list = [str(n) for n in p]
# cur_perm = "".join(str_list)
# int_cur_perm = int(cur_perm)
# if int_cur_perm > max and int_cur_perm % 3 == 0:
# max = int_cur_perm
# print(max)
# return max
class Test(unittest.TestCase):
def test1(self):
self.assertEqual(solution([3, 1, 4, 1]), 4311)
def test2(self):
self.assertEqual(solution([3, 1, 4, 1, 5, 9]), 94311)
if __name__=="__main__":
# main()
unittest.main() |
6ff855754a5b040e7b46749ce8a68a90e15a389a | lukechn99/leetcode | /count_clicks.py | 3,129 | 3.703125 | 4 | '''
You are in charge of a display advertising program. Your ads are displayed on websites all over the internet. You have some CSV input data that counts how many times that users have clicked on an ad on each individual domain. Every line consists of a click count and a domain name, like this:
counts = [ "900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"20,overflow.com",
"5,com.com",
"2,en.wikipedia.org",
"1,m.wikipedia.org",
"1,mobile.sports",
"1,google.co.uk"]
Write a function that takes this input as a parameter and returns a data structure containing the number of clicks that were recorded on each domain AND each subdomain under it. For example, a click on "mail.yahoo.com" counts toward the totals for "mail.yahoo.com", "yahoo.com", and "com". (Subdomains are added to the left of their parent domain. So "mail" and "mail.yahoo" are not valid domains. Note that "mobile.sports" appears as a separate domain near the bottom of the input.)
Sample output (in any order/format):
calculateClicksByDomain(counts) =>
com: 1345
google.com: 900
stackoverflow.com: 10
overflow.com: 20
yahoo.com: 410
mail.yahoo.com: 60
mobile.sports.yahoo.com: 10
sports.yahoo.com: 50
com.com: 5
org: 3
wikipedia.org: 3
en.wikipedia.org: 2
m.wikipedia.org: 1
mobile.sports: 1
sports: 1
uk: 1
co.uk: 1
google.co.uk: 1
n: number of domains in the input
(individual domains and subdomains have a constant upper length)
'''
counts = [
"900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"20,overflow.com",
"5,com.com",
"2,en.wikipedia.org",
"1,m.wikipedia.org",
"1,mobile.sports",
"1,google.co.uk"
]
'''
key: domain
value: (count, subdomains_list)
com : (900, [{yahoo : (300, [{sports : (40, []) }...]), {stackoverflow : (10, []), ])
[]
sports.yahoo.com
'''
# def add_value(count, domain, result):
# subdomains = domain.split(".")
# for name in reversed(subdomains):
# if name in
def parse_domain_counts(counts):
result = {}
for entry in counts:
count_split = entry.split(",")
count = int(count_split[0])
domain = count_split[1].split(".")
# see if each subdomain is in result
for i in reversed(range(len(domain))):
domain_name = ""
for j in range(i, len(domain)):
domain_name += domain[j]
if j < len(domain) - 1:
domain_name += "."
# add to dict
if domain_name in result:
result[domain_name] += count
else:
result[domain_name] = count
return result
parse_domain_counts(counts) |
fc3bd6d939a85c3cee0f57229bd9bbdcd4da9be0 | lukechn99/leetcode | /removeN.py | 822 | 3.75 | 4 | def removeEven (list):
for i in list:
if i % 2 == 0:
list.remove(i)
return list
list = [1, 2, 3, 4, 5, 6, 7, 8]
print(removeEven(list))
def removeMultTwo (n):
list = []
for i in range(2, n+1):
list.append(i)
for p in list:
# p starts as 2
# multiplier = 2
# multiplier = 3
# ...
for multiplier in range(2, len(list)):
if (p * multiplier) in list:
list.remove(p * multiplier)
# remove 4, 6, 8, 10... based on multiplier
return list
print("using mult two\n")
list2 = [2, 3, 4, 5, 6, 7, 8, 9, 10]
print(removeMultTwo(120))
def removeMultTwoByCount (n):
list = []
for i in range(2, n+1):
list.append(i)
for p in list:
sum = 2 * p
while sum <= list[-1]:
if sum in list:
list.remove(sum)
sum += p
return list
print(removeMultTwoByCount(100))
|
46f70133d8fc36aa8c21c51ba8cd35efd18fcfc7 | MenggeGeng/FE595HW4 | /hw4.py | 1,520 | 4.1875 | 4 | #part 1: Assume the data in the Boston Housing data set fits a linear model.
#When fit, how much impact does each factor have on the value of a house in Boston?
#Display these results from greatest to least.
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
#load boston dataset
boston = load_boston()
#print(boston)
data = pd.DataFrame(boston['data'], columns= boston['feature_names'])
print(data.head())
data['target'] = boston['target']
print(data.head())
# The correlation map
correlation = data.corr()
sns.heatmap(data = correlation, annot = True)
plt.show()
# The correlation coefficient between target and features
print(correlation['target'])
#prepare the regression objects
X = data.iloc[:, : -1]
Y = data['target']
print(X.shape)
print(Y.shape)
#build regression model
reg_model = LinearRegression()
reg_model.fit(X,Y)
print('coefficient : \n ', reg_model.coef_)
#The impact of each factor have on the value of a house in Boston
coef = pd.DataFrame(data= reg_model.coef_, index = boston['feature_names'], columns=["value"])
print(coef)
#Display these results from greatest to least.
coef_abs = abs(reg_model.coef_)
coef_1 = pd.DataFrame(data= coef_abs , index = boston['feature_names'], columns=["value"])
print("Display these coefficient from greatest to least:")
print(coef_1.sort_values("value",inplace=False, ascending=False))
|
256c69199c1891d4c678824e59db2b80b69e3aa2 | sangianpatrick/hacktiv8-python-datascience | /day_01/task5.py | 273 | 3.859375 | 4 | #pesanan
orderan = list()
order = input("Masukkan pesanan pertama: \n")
orderan.append(order)
order = input("Masukkan pesanan kedua: \n")
orderan.append(order)
order = input("Masukkan pesanan ketiga: \n")
orderan.append(order)
print("Pesanan anda: \n")
print(orderan)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.