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 |
|---|---|---|---|---|---|---|
fa5a9cb791bfdacbbac3ac9ab057404daef6c8bf | marcin-skurczynski/IPB2017 | /Michal Starzec ATM HM.py | 2,404 | 3.90625 | 4 | balance=2475.11
print(" > > > > eCard < < < < ")
for i in range (1,4):
PIN = int(input('Please Enter You 4 Digit Pin: '))
if PIN == (7546):
print('Your PIN Is Correct\n')
print("""
1) Balance
2) Withdraw
3) Deposit
4) Return Card
""")
Option=int(input("Enter Option: "))
if Option==1:
print("Balance $ ",balance)
print('Thank You For Using eCard')
exit()
if Option==2:
print("Balance $ ",balance)
Withdraw=float(input("Enter Withdraw amount $ "))
if Withdraw>0:
if Withdraw<balance:
forewardbalance=(balance-Withdraw)
print('You Have Withdrawn ',Withdraw)
print("Foreward Balance $ ",forewardbalance)
receipt=input('Would You Like To Print Receipt?\n Please Choose:\n y for YES\n n for NO')
if receipt=='y':
print('Printing Your Receipt\n')
print('PLEASE TAKE OUT YOUR CARD')
exit()
elif receipt=='n':
print('PLEASE TAKE OUT YOUR CARD\n')
print('THANK YOU FOR USING eCARD')
exit()
elif Withdraw>balance:
print("No Money No Honey")
exit()
else:
print("None withdraw made")
exit()
else: print('Negative Values are Impossible To Withdraw')
exit()
if Option==3:
print("Balance $ ",balance)
Deposit=float(input("Enter deposit amount $ "))
if Deposit>0:
forewardbalance=(balance+Deposit)
print("Forewardbalance ",forewardbalance)
receipt=input('Would You Like To Print Receipt?\n Please Choose:\n y for YES\n n for NO')
if receipt=='y':
print('Printing Your Receipt\n')
print('PLEASE TAKE OUT YOUR CARD')
exit()
elif receipt=='n':
print('PLEASE TAKE OUT YOUR CARD\n')
print('THANK YOU FOR USING eCARD')
exit()
else:
print("None deposit made\n PLEASE TAKE OUT YOUR CARD")
exit()
if Option==4:
print('THANK YOU FOR CHOOSING eCard\n ')
print('TAKE OUT YOUR CARD')
exit()
else:
if i==3:
print("You Have Reached The Limit Of Transactions Possible")
else:
print('Error Incorrect PIN Number\n \n PLEASE TRY AGAIN ')
|
bb00780bcd9e892df3913c24da81fb1b15f09e41 | Descalzo404/CS50-Problem-Sets | /Dna/dna.py | 2,693 | 3.875 | 4 | from sys import argv, exit
import csv
import re
from cs50 import get_string
def main():
# Open the data base csv
csv_file = argv[1]
with open(csv_file) as f:
reader = csv.reader(f)
# Getting the opitions of STR's from the header of the csv file
str_options = next(reader)[1:]
# Open the text file with the dna
person_DNA = argv[2]
with open(person_DNA) as d:
DNA = d.read()
# Getting the number of times the especific STR is repeated consecutive
person = []
for i in str_options:
value = maximum_len(DNA, i)
person.append(value)
# Comparing with the data base file
return(compare(reader, person))
# This is the comparing function
def compare(data_base, list_of_str):
for line in data_base:
name = line[0]
person_str = [int(value) for value in line[1:]]
# If the person is found in the data base
if person_str == list_of_str:
print(name)
return
# If the person is not in the data base
print("No match")
# This function gets the index of the ocurrances and check if they are consecutives
def maximum_len(string, substring):
len_of_substring = len(substring)
matches = re.finditer(substring, string)
# This gets the index of the ocurrance of the especific STR in the DNA text
ocurrances_list = [match.start() for match in matches]
was_consecutive = False
consecutives = 0
max_consecutives = []
# If there is only one ocurrance
if len(ocurrances_list) == 1:
return 1
# If there is two ocurrances
elif len(ocurrances_list) == 2:
if (ocurrances_list[1] - ocurrances_list[0]) == len_of_substring:
return 2
else:
return 0
# If there is more ocurrances
for i in range(len(ocurrances_list) - 1):
if ((ocurrances_list[i + 1] - ocurrances_list[i]) == len_of_substring and was_consecutive == False):
consecutives += 2
was_consecutive = True
elif ((ocurrances_list[i + 1] - ocurrances_list[i]) == len_of_substring and was_consecutive == True):
consecutives += 1
was_consecutive = True
max_consecutives.append(consecutives)
elif ((ocurrances_list[i + 1] - ocurrances_list[i]) != 4 and was_consecutive == True):
max_consecutives.append(consecutives)
consecutives = 0
was_consecutive = False
# If there is no consecutives
if len(max_consecutives) == 0:
return 0
return max(max_consecutives)
main()
|
d4627d478b1aa4b5d9b061d66ce6cb32643b5bc7 | HyeranShin/Deep-Learning-Lecture | /deep-learning-master/tensorflow_02.py | 614 | 3.65625 | 4 | x = 1
y = x + 9
print(y) # 10
import tensorflow as tf
# python 소스 코드 내의 x와 뒤의 string x는 다르다.
# 첫번째 x는 python 변수
# 두번째 x는 TensorFlow(그래프) 상의 이름
x = tf.constant(1, name = 'x')
y = tf.Variable(x + 9, name = 'y')
print(y) # <tf.Variable 'y:0' shape=() dtype=int32_ref>
print(y.value()) # Tensor("y/read:0", shape=(), dtype=int32)
model = tf.global_variables_initializer()
# with 구문 사용 시 close() 생략 가능
with tf.Session() as sess:
sess.run(model) # 한꺼번에 초기화
print(sess.run(y)) # 10 => 그래프를 그린 결과 값
|
fd541455bd5ad5ca18866082a77842561ca1b2b7 | cuotos/bash-python-caller | /test_python_helpers.py | 2,384 | 3.671875 | 4 | #!/usr/bin/env python
import unittest
import python_helpers as ph
import re
class TestPythonHelper(unittest.TestCase):
def test_helper_should_reject_calls_if_wrong_number_of_arguments_used(self):
# not expecting any arguments
def f():
pass
# pass in an argument that isnt expected
self.assertRaises(Exception, ph.main, ["programName", "arg1"], f)
def test_helper_should_reject_calls_if_not_enough_arguments_used(self):
# not expecting any arguments
def f(x, y, z):
pass
# pass in too many arguments for the function
self.assertRaises(Exception, ph.main, ["programName", "arg1"], f)
def test_helper_should_work_if_no_args_are_required(self):
# not expecting any arguments
def f():
return ["no args required"]
expected = ["no args required"]
# pass in an argument that isnt expected
actual = ph.main(["programName"], f)
self.assertEqual(expected, actual)
def test_helper_fail_if_more_than_max_arguments_provided(self):
def f(a, b, c, d, e, f, g, h, i, j, k, l):
pass
self.assertRaises(Exception, ph.main, list(range(0, 13)), f)
def test_main_helper_only_accepts_lists_from_functions(self):
def f():
return []
actual = ph.main(["programName"], f)
self.assertIsInstance(actual, list, msg="all functions should return a list, but got {}".format(type(actual)))
def test_main_helper_should_throw_exception_if_func_doesnt_return_a_list(self):
def f():
return 10
self.assertRaises(Exception, ph.main, ["programName"], f)
def test_if_the_only_argument_is_a_question_mark_should_print_pydoc(self):
def f():
"""this is the documentation
it spans multiple lines"""
pass
expected = ["this is the documentation it spans multiple lines"]
actual = ph.main(["programName", "?"], f)
actual_trimmed = [" ".join(actual[0].split())]
self.assertEqual(expected, actual_trimmed)
def test_if_no_py_doc_is_provided_print_helpful_message(self):
def f():
pass
expected = ["warning: function contains no documentation"]
actual = ph.main(["programName", "?"], f)
self.assertEqual(expected, actual)
|
db3e8d4e2f32b0327c4d4ebad59c6270ddfa92ba | syedshameersarwar/python | /quicksortAssignment.py | 1,650 | 4 | 4 | def readfile():
file = open("QuickSort.txt")
numbers = []
for line in file:
numbers.append(int(line.strip()))
return numbers
def quickSort(List,start,end,partition = None ):
if start < end:
comparisions = end - start
pivot_index = partition(List,start,end)
comparisions += quickSort(List,start,pivot_index-1,partition)
comparisions += quickSort(List,pivot_index+1,end,partition)
else:
return 0
return comparisions
def base_partition(List,start,end):
pivot_element = List[start]
pivot_index = start+1
for j in range(pivot_index,end+1):
if List[j]<=pivot_element:
List[j],List[pivot_index] = List[pivot_index],List[j]
pivot_index += 1
List[pivot_index-1],List[start] = pivot_element,List[pivot_index-1]
return pivot_index-1
def firstPivot(List,start,end):
return base_partition(List,start,end)
def lastPivot(List,start,end):
List[start],List[end] = List[end],List[start]
return base_partition(List,start,end)
def medianPivot(List,start,end):
middle = (start + end)//2
first = start
last = end
if List[start] < List[middle] <List[last] or List[last] < List[middle] < List[start]:
pivot_index = middle
elif List[middle] < List[start] < List[last] or List[last] < List[start] < List[middle]:
pivot_index = first
else:
pivot_index = last
List[start],List[pivot_index] = List[pivot_index],List[start]
return base_partition(List,start,end)
if __name__ == '__main__':
List = readfile()
print(quickSort(List,0,len(List)-1,medianPivot))
|
b2788add12ce65a30a8856de3575d0d7100d4591 | syedshameersarwar/python | /secondMaximum.py | 3,011 | 3.5625 | 4 | '''You are given as input an unsorted array of n distinct numbers,
where n is a power of 2.Give an algorithm that identifies the
second-largest number in the array,and that uses at most
n+log2n−2 comparisons.'''
def findMaxTournament(List):
if len(List)==1:
return List[:]
mid = len(List)//2
firstHalf = findMaxTournament(List[:mid])
secondHalf = findMaxTournament(List[mid:])
if firstHalf[0]>secondHalf[0]:
firstHalf.append(secondHalf[0])
return firstHalf
else:
secondHalf.append(firstHalf[0])
return secondHalf
def findSecondMax(List):
result_set = findMaxTournament(List)
comparedElements = result_set[1:]
second_max = comparedElements[0]
for i in range(1,len(comparedElements)):
if comparedElements[i]>second_max:
second_max = comparedElemets[i]
return second_max
print(findSecondMax([3,1,10,17,12,4]))
'''
Function FindMaxTournament(I,J, A[I..J],N) returns Compared[0..K]
begin
if I = J then //base case
Compared[0..N];
Compared[0]← 1;
Compared[1]← A[I];
return Compared;
endif
Compared1← FindMaxTournament(I, I+(J-I)/2, A,N);
Compared2← FindMaxTournament(1+I+(J-I)/2,J, A,N);
if Compared1[1]>Compared2[1] then
K←Compared1[0]+1;
Compared1[0]←K;
Compared1[K]←Compared2[1];
return Compared1;
else
K←Compared2[0]+1;
Compared2[0]←K;
Compared2[K]←Compared1[1];
return Compared2;
endif
end
Efficient Algorithm for Finding the second largest element
Using the two observations from above, an efficient algorithm for finding the
second largest number will work as follows:
1. Find the largest element of the array using the tournament method.
2. Collect all elements of the array that were compared to the largest
element.
3. Find the largest element among the elements collected in step 2 (can
use any method here).
Step 2 Issues. How can we efficiently collect all elements of the input
array that were compared to the largest element of the array?
Essentially, we would like to associate with the largest element of A an
array Compared[] of elements A was compared to. This, however, needs to
be done carefully. We do not know upfront which array element is going to
be the largest, so we will carry information about all comparisons an array
element won until this element loses a comparison.
From the technical side, we will change the FindMaxRecursive() algorithm
to return an array of integers Compared[0..K]. We will establish the following
convention:
• Compared[0] = K (i.e., the 0th element of the array holds the length
of the array);
• Compared[1] = max (i.e., the first element of the array is the number
that FindMaxRecursive() would return;
• Compared[2], . . . ,Compared[K] are all numbers with which max has
been compared thus far.
Using these conventions, the Algorithm FindSecondMax() can be written
as shown in Figure 2.
'''
|
9c7d666c90a63956d4cb2a7c36a26cbe5f1fb46d | syedshameersarwar/python | /infixpostfixprefrix.py | 2,726 | 3.84375 | 4 | class Stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items==[]
def push(self,value):
self.items.append(value)
def pop(self):
if self.size()==0:
return None
return self.items.pop()
def peek(self):
if self.size()==0:
return None
return self.items[-1]
def size(self):
return len(self.items)
def __str__(self):
exp = "["
for i in range(self.size()):
if i==self.size()-1:
exp +=str(self.items[i]) + "]"
else:
exp +=str(self.items[i])+ "," #patch for idle otherwise this expression is enough
return exp
def precedence(operator):
if operator == '+' or operator == '-':
return 1
elif operator == '/' or operator == '*':
return 2
elif operator == '^':
return 3
else:
return 0
def isoperator(operator):
if operator == '+' or operator == '-' or operator == '/' \
or operator == '*' or operator == '^' :
return True
return False
def infixtopostfix(infix):
s = Stack()
postfix = ""
s.push("(")
infix += ")"
for char in infix:
if char.isdigit() or char.isalpha():
postfix+= char
elif char == "(":
s.push(char)
elif isoperator(char):
while precedence(char)<=precedence(s.peek()):
postfix += str(s.pop())
s.push(char)
elif char == ")":
while s.peek()!= "(":
postfix += str(s.pop())
s.pop()
if s.is_empty():
return postfix
def infixtoprefix(infix):
infix_reverse = infix[::-1] #reverse postfix expression
for i in range(len(infix_reverse)): #replace ( with ), and ) with (
if infix_reverse[i] == '(':
infix_reverse = infix_reverse[:i] + ')' + infix_reverse[i+1:]
elif infix_reverse[i] == ')':
infix_reverse = infix_reverse[:i] + '(' + infix_reverse[i+1:]
postfix = infixtopostfix(infix_reverse) #convert to postfix
prefix = postfix[::-1] #reverse postfix to get prefix
return prefix
def eval_postfix(postfix):
s = Stack()
postfix += ")"
for char in postfix:
if char.isdigit():
s.push(char)
elif isoperator(char):
A = s.pop()
B = s.pop()
s.push(eval(str(B)+char+str(A)))
result = s.pop()
return result
print(infixtoprefix("(a-b/c)*(a/k-l)")) #test for prefix
print(infixtopostfix("( A + B ) * ( C + D )")) #test for postfix
print(eval_postfix("7 8 + 3 2 + /")) #test for postfix evaluation
|
3b8b8cc921b2bd664584adca2b8add2773823e36 | syedshameersarwar/python | /BresehhamCirle-algo.py | 740 | 4.03125 | 4 | from graphics import *
import math
import numpy as np
def drawPixel(x,y):
global screen
screen.plotPixel(int(x),int(y),"red")
def BresenhamCircle(Xc,Yc,r):
x = 0
y = r
d=3- (2*r)
while y > x:
drawSymmetricPoints(Xc,Yc,x,y)
if d <0:
d=d + 4*x +6
else:
d=d+ 4*(x-y) +10
y=y-1
x=x+1
def drawSymmetricPoints(Xc,Yc,x,y):
drawPixel(x+Xc,y+Yc)
drawPixel(y+Xc,x+Yc)
drawPixel(y+Xc,-x+Yc)
drawPixel(x+Xc,-y+Yc)
drawPixel(-x+Xc,-y+Yc)
drawPixel(-y+Xc,-x+Yc)
drawPixel(-y+Xc,x+Yc)
drawPixel(-x+Xc,y+Yc)
if __name__=='__main__':
screen = GraphWin("Circle Symmetric",800,800)
BresenhamCircle(500,200,100)
|
296dd75cbc77a834515929bc0820794909fb9e54 | sdaless/pyfiles | /CSI127/shift_left.py | 414 | 4.3125 | 4 | #Name: Sara D'Alessandro
#Date: September 12, 2018
#This program prompts the user to enter a word and then prints the word with each letter shifted left by 1.
word = input("Enter a lowercase word: ")
codedWord = ""
for ch in word:
offset = ord(ch) - ord('a') - 1
wrap = offset % 26
newChar = chr(ord('a') + wrap)
codedWord = codedWord + newChar
print("Your word in code is: ", codedWord)
|
138fd202c91719c37dbd579d03246426fb42bd4b | sdaless/pyfiles | /Hw2pr1.py | 1,070 | 3.875 | 4 | # Name:
# Hw2pr1.py
# STRING slicing and indexing challenges
h = "harvey"
m = "mudd"
c = "college"
# Problem 1: hey
answer1 = h[0] + h[4:6]
print(answer1,"\n")
# Problem 2: collude
answer2 = c[0:4] + m[1:3] + c[-1]
print(answer2,"\n")
# Problem 3: arveyudd
answer3 = h[1:] + m[1:]
print(answer3,"\n")
# Problem 4: hardeharharhar
answer4 = h[:3] + m[-1] + c[-1] + (h[:3]*3)
print(answer4,"\n")
# Problem 5: legomyego
answer5 = c[3:6] + c[1] + m[0] + h[-1] + c[4:6] + c[1]
print(answer5,"\n")
# Problem 6: clearcall
answer6 = c[0] + c[3:5] + h[1:3] + c[0] + h[1] + c[2:4]
print(answer6,"\n")
# LIST slicing and indexing challenges
#
pi = [3,1,4,1,5,9]
e = [2,7,1]
# Example problem (problem 0): [2,7,5,9]
answer0 = e[0:2] + pi[-2:]
print(answer0,"\n")
# Problem 7: creating [7,1]
answer7 = e[1:]
print(answer7,"\n")
# Problem 8: creating [9,1,1]
answer8 = pi[-1:-6:-2]
print(answer8,"\n")
# Problem 9: creating [1,4,1,5,9]
answer9 = pi[1:]
print(answer9,"\n")
# Problem 10: creating: [1,2,3,4,5]
answer10 = e[-1:-4:-2] + pi[0:5:2]
print(answer10) |
b3dbf8b4190548cd3787fbe0021ca46244b116af | sdaless/pyfiles | /CSI127/turtle_color.py | 208 | 4.53125 | 5 | #Sara D'Alessandro
#A program that changes the color of turtle
#September 26th, 2018
import turtle
tut = turtle.Turtle()
tut.shape("turtle")
hex = input("Enter a hex string starting with '#' sign: ")
tut.color(hex)
|
d6ff6244153119d0556db2ca0720e18b373af937 | sdaless/pyfiles | /CSI127/octagon.py | 164 | 3.9375 | 4 | #Name: Sara D'Alessandro
#Date: August 29, 2018
#This program draws an octagon.
import turtle
tia = turtle.Turtle()
for i in range(8):
tia.forward(50)
tia.right(45)
|
3bcbd6b47d2963aa858db475bb55fd4137523a89 | sdaless/pyfiles | /CSI127/dna_string.py | 306 | 4.09375 | 4 | #Name: Sara D'Alessandro
#Date: September 23, 2018
#This program prompts the user for a DNA string, and then prints the length and GC-content.
dna = input("Enter a DNA string: ")
l = len(dna)
print("The length is", l)
numC = dna.count('C')
numG = dna.count('G')
gc = (numC + numG) / l
print('GC-content is', gc)
|
9f53a5c4227a048e38bdf88430c1de6c69da6493 | wenqiang0517/PythonWholeStack | /day15/第一次考试机试题讲解.py | 5,051 | 3.578125 | 4 | # 机试题
# 1.lis = [['哇',['how',{'good':['am',100,'99']},'太白金星'],'I']] (2分)
lis = [['哇', ['how', {'good': ['am', 100, '99']}, '太白金星'], 'I']]
# o列表lis中的'am'变成大写。(1分)
# lis[0][1][1]['good'][0] = lis[0][1][1]['good'][0].upper()
# print(lis)
# o列表中的100通过数字相加在转换成字符串的方式变成'10010'。(1分)
# lis[0][1][1]['good'][1] = str(lis[0][1][1]['good'][1] + 9910)
# print(lis)
# 2.dic = {'k1':'v1','k2':['alex','sb'],(1,2,3,):{'k3':['2',100,'wer']}} (3分)
dic = {'k1': 'v1', 'k2': ['alex', 'sb'], (1, 2, 3,): {'k3': ['2', 100, 'wer']}}
# o将'k3'对应的值的最后面添加一个元素'23'。(1分)
# dic[(1, 2, 3,)]['k3'].append('23')
# print(dic)
# o将'k2'对应的值的第0个位置插入元素'a'。(1分)
# dic['k2'].insert(0, 'a')
# print(dic)
# o将(1,2,3,)对应的值添加一个键值对'k4','v4'。(1分)
# dic[(1, 2, 3)].setdefault('k4', 'v4')
# print(dic)
# 3.实现一个整数加法计算器(多个数相加):(5分)
# 如:content = input("请输入内容:") 用户输入:5+9+6 +12+ 13,然后进行分割再进行计算。
# content = input("请输入内容:")
# content = content.strip().split('+')
# count = 0
# for i in content:
# count += int(i.strip())
# print(count)
# 4.请写一个电影投票程序。现在上映的电影列表如下:(10分)
# lst = ['复仇者联盟4', '驯龙高手3', '金瓶梅', '老男孩', '大话西游']
# 由用户给每⼀个电影投票.最终将该⽤户投票信息公布出来。
# 要求:
# o用户可以持续投票,用户输入序号,进行投票。比如输入序号 1,给金瓶梅投票1。
# o每次投票成功,显示给哪部电影投票成功。
# o退出投票程序后,要显示最终每个电影的投票数。
# 建议最终投票的结果为这种形式:
# {'⾦瓶梅': 0, '复仇者联盟4': 0, '驯龙高手3': 0, '老男孩': 0,'大话西游':0}
"""
dic = {}
lst = ['金瓶梅', '复仇者联盟4', '驯龙高手3', '老男孩', '大话西游']
while 1:
for x, y in enumerate(lst):
print(x + 1, y)
content = input("请输入序号(输入q或者Q退出): ").strip()
if content.isdecimal():
content = int(content)
if 0 < content <= len(lst):
if lst[content - 1] in dic:
print(f'给{lst[content - 1]}投票 1')
dic[lst[content - 1]] += 1
else:
print(f'给{lst[content - 1]}投票 1')
dic[lst[content - 1]] = 1
else:
print('输出有误')
elif content.upper() == 'Q':
print(dic)
break
else:
print('输出有误')
"""
# 5.有文件t1.txt里面的内容为:(10分)
# id,name,age,phone,job
# 1,alex,22,13651054608,IT
# 2,wusir,23,13304320533,Tearcher
# 3,taibai,18,1333235322,IT
# 利用文件操作,将其构造成如下数据类型。
# [{'id':'1','name':'alex','age':'22','phone':'13651054608','job':'IT'},......]
# lst = []
# with open('t1.txt', encoding='utf-8') as f:
# f = f.readlines()
# for i in f[1:]:
# i = i.strip().split(',')
# dic = {f[0].split(',')[0]: i[0], f[0].split(',')[1]: i[1], f[0].split(',')[2]: i[2],
# f[0].split(',')[3]: i[3], f[0].split(',')[4].strip(): i[4], }
# lst.append(dic)
# print(lst)
# 6.按要求完成下列转化。(10分)
# list4 = [
# {"name": "alex", "hobby_list": ["抽烟", "喝酒", "烫头", "Massage"]},
# {"name": "wusir", "hobby_list": ["喊麦", "街舞", "出差"]},
# ]
# 将list3 这种数据类型转化成list4类型,你写的代码必须支持可拓展.
# 比如list3 数据在加一个这样的字典{"name": "wusir", "hobby": "溜达"},
# list4 {"name": "wusir", "hobby_list": ["喊麦", "街舞", "溜达"]
# 或者list3增加一个字典{"name": "太白", "hobby": "开车"},
# list4{"name": "太白", "hobby_list": ["开车"],
# 无论按照要求加多少数据,你的代码都可以转化.如果不支持拓展,则4分,支持拓展则10分.
list3 = [
{"name": "alex", "hobby": "抽烟"},
{"name": "alex", "hobby": "喝酒"},
{"name": "alex", "hobby": "烫头"},
{"name": "alex", "hobby": "Massage"},
{"name": "wusir", "hobby": "喊麦"},
{"name": "wusir", "hobby": "街舞"},
{"name": "wusir", "hobby": "出差"},
]
"""
# 第一种方式
list4 = []
for i in list3:
for x in list4:
if i['name'] == x['name']:
x['hobby_list'].append(i['hobby'])
break
else:
list4.append({'name': i['name'], 'hobby_list': [i['hobby'], ]})
print(list4)
"""
# 第二种方式
# dic = {'alex':{"name": "alex", "hobby_list": ["抽烟", "喝酒", "烫头", "Massage"]},
# "wusir": {"name": "wusir", "hobby_list": ["喊麦", "街舞","出差"]}
# }
# print(list(dic.values()))
dic = {}
for i in list3:
if i['name'] not in dic:
dic[i['name']] = {'name': i['name'], 'hobby_list': [i['hobby'], ]}
else:
dic[i['name']]['hobby_list'].append(i['hobby'])
print(list(dic.values()))
|
d2322f9a5514dbe9dd807dab9053d3b1ef7bc35f | wenqiang0517/PythonWholeStack | /day06/03 代码块.py | 1,215 | 3.65625 | 4 | # 代码块
# * 代码块:我们的所有代码都需要依赖代码块执行,Python程序是由代码块构造的。块是一个python程序的文本,他是作为一个单元执行的。
# * 一个模块,一个函数,一个类,一个文件等都是一个代码块
# * 交互式命令下一行就是一个代码块
# 两个机制同一个代码块下,有一个机制,不同的代码块下,遵循另一个机制
# 同一代码块下的缓存机制
# * 前提条件:同一代码块内
# * 机制内容:pass
# * 适用的对象:int bool str
# * 具体细则:所有的数字,bool,几乎所有的字符串
# * 优点:提升性能,节省内存
# 不同代码块下的缓存机制: 小数据池
# * 前提条件:不同代码块内
# * 机制内容:pass
# * 适用的对象:int bool str
# * 具体细则:-5-256数字,bool,满足规则的字符串
# * 优点:提升性能,节省内存
"""
总结:
1,面试题考
2,一定要分清楚:同一代码块下适应一个就缓存机制,不同的代码块下适用另一个缓存机制(小数据池)
3,小数据池:数字的范围是 -5-256
4,缓存机制的有点:提升性能,节省内存
"""
|
a7512d155221f8cf092c99cb58320fdb2ae6c2db | wenqiang0517/PythonWholeStack | /day26/08-反射的例子.py | 1,316 | 3.5625 | 4 | class Payment: pass
class Alipay(Payment):
def __init__(self, name):
self.name = name
def pay(self, money):
dic = {'uname': self.name, 'price': money}
print('%s通过支付宝支付%s钱成功' % (self.name, money))
class WeChat(Payment):
def __init__(self, name):
self.name = name
def pay(self, money):
dic = {'username': self.name, 'money': money}
print('%s通过微信支付%s钱成功' % (self.name, money))
class Apple(Payment):
def __init__(self, name):
self.name = name
def pay(self, money):
dic = {'name': self.name, 'number': money}
print('%s通过苹果支付%s钱成功' % (self.name, money))
class QQpay:
def __init__(self, name):
self.name = name
def pay(self, money):
print('%s通过qq支付%s钱成功' % (self.name, money))
import sys
def pay(name, price, kind):
class_name = getattr(sys.modules['__main__'], kind)
obj = class_name(name)
obj.pay(price)
# if kind == 'Wechat':
# obj = WeChat(name)
# elif kind == 'Alipay':
# obj = Alipay(name)
# elif kind == 'Apple':
# obj = Apple(name)
# obj.pay(price)
pay('alex', 400, 'WeChat')
pay('alex', 400, 'Alipay')
pay('alex', 400, 'Apple')
pay('alex', 400, 'QQpay')
|
f8571a2378d85ae0d51811f2c9c5b44d3cd0b475 | wenqiang0517/PythonWholeStack | /day23/02-命名空间问题.py | 3,168 | 3.859375 | 4 | # 类的成员和命名空间
# class A:
# Country = '中国' # 静态变量/静态属性 存储在类的命名空间里的
# def __init__(self,name,age): # 绑定方法 存储在类的命名空间里的
# self.name = name
# self.age = age
# def func1(self):
# print(self)
# def func2(self):pass
# def func3(self):pass
# def func4(self):pass
# def func5(self):pass
#
# a = A('alex',83)
# print(a.name)
# print(a.Country)
# print(A.Country)
# a.func1() # == A.func1(a)
# class A:
# Country = '中国' # 静态变量/静态属性 存储在类的命名空间里的
# def __init__(self,name,age,country): # 绑定方法 存储在类的命名空间里的
# self.name = name
# self.age = age
# self.Country = country
# def func1(self):
# print(self)
# def func2(self):pass
# def func3(self):pass
# def func4(self):pass
# def func5(self):pass
#
# a = A('alex',83,'印度')
# print(a.name)
# print(a.Country)
# print(A.Country)
# class A:
# Country = '中国' # 静态变量/静态属性 存储在类的命名空间里的
# def __init__(self,name,age,country): # 绑定方法 存储在类的命名空间里的
# self.name = name
# self.age = age
# self.country = country
# def func1(self):
# print(self)
# def func2(self):pass
# def func3(self):pass
# def func4(self):pass
# def func5(self):pass
#
# a = A('alex',83,'印度')
# b = A('wusir',74,'泰国人')
# a.Country = '日本人'
# print(a.Country)
# print(b.Country)
# print(A.Country)
# class A:
# Country = '中国' # 静态变量/静态属性 存储在类的命名空间里的
# def __init__(self,name,age,country): # 绑定方法 存储在类的命名空间里的
# self.name = name
# self.age = age
# def func1(self):
# print(self)
# def func2(self):pass
# def func3(self):pass
# def func4(self):pass
# def func5(self):pass
#
# a = A('alex',83,'印度')
# b = A('wusir',74,'泰国人')
# A.Country = '日本人'
# print(a.Country)
# print(b.Country)
# print(A.Country)
# 类中的变量是静态变量
# 对象中的变量只属于对象本身,每个对象有属于自己的空间来存储对象的变量
# 当使用对象名去调用某一个属性的时候会优先在自己的空间中寻找,找不到再去对应的类中寻找
# 如果自己没有就引用类的,如果类也没有就报错
# 对于类来说,类中的变量所有的对象都是可以读取的,并且读取的是同一份变量
# 实现一个类,能够自动统计这个类实例化了多少个对象
# class A:pass
# A.Country = 123 # 属性的增加
# print(A.Country) # 查看或者引用
# class A:
# count = 0
# def __init__(self):
# A.count += 1
#
# a1 = A()
# print(a1.count)
# a2 = A()
# print(A.count)
# 类中的静态变量的用处
# 如果一个变量 是所有的对象共享的值,那么这个变量应该被定义成静态变量
# 所有和静态变量相关的增删改查都应该使用类名来处理
# 而不应该使用对象名直接修改静态变量
|
8b1a9df76b23b6f000a74cd458e84ac32b2fa2e4 | wenqiang0517/PythonWholeStack | /day01/test01.py | 534 | 3.78125 | 4 | # 炸金花发牌游戏(奖品)
# 生成一副扑克牌,去除大小王
# 5个玩家,每个人发三张牌
# 最后计算谁是赢家(进阶)
a = 1
number = []
poker = []
letter = ['J', 'Q', 'K', 'A']
design_color = ['H', 'M', 'F', 'X']
while a < 10:
a = a + 1
number.append(str(a))
num = number + letter
for i in design_color:
for y in num:
poker.append(i + y)
print(poker)
# print(len(poker))
player = ['小李', '小红', '小刚', '小智', '小夏']
# for x in player:
# pai = range(poker, 3)
|
18e3c19deb58a4a6933c5115994dea8e4e327e1d | wenqiang0517/PythonWholeStack | /day22/03 面向对象编程.py | 3,361 | 4.125 | 4 | # 先来定义模子,用来描述一类事物
# 具有相同的属性和动作
# class Person: # 类名
# def __init__(self,name,sex,job,hp,weapon,ad):
# # 必须叫__init__这个名字,不能改变的,所有的在一个具体的人物出现之后拥有的属性
# self.name = name
# self.sex = sex
# self.job = job
# self.level = 0
# self.hp = hp
# self.weapon = weapon
# self.ad = ad
# #
# alex = Person('alex','不详','搓澡工',260,'搓澡巾',1) # alex 就是对象 alex = Person()的过程 是通过类获取一个对象的过程 - 实例化
# print(alex,alex.__dict__)
# wusir = Person('wusir','male','法师',500,'打狗棍',1000)
# # print(wusir,wusir.__dict__)
# print(alex.name) # print(alex.__dict__['name']) 属性的查看
# alex.name = 'alexsb' # 属性的修改
# print(alex.name)
# alex.money = 1000000 # 属性的增加
# print(alex.money)
# print(alex.__dict__)
# del alex.money # 属性的删除
# print(alex.__dict__)
# 类名() 会自动调用类中的__init__方法
# 类和对象之间的关系?
# 类 是一个大范围 是一个模子 它约束了事物有哪些属性 但是不能约束具体的值
# 对象 是一个具体的内容 是模子的产物 它遵循了类的约束 同时给属性赋上具体的值
# Person是一个类 :alex wusir都是这个类的对象
# 类有一个空间,存储的是定义在class中的所有名字
# 每一个对象又拥有自己的空间,通过对象名.__dict__就可以查看这个对象的属性和值
# d = {'k':'v'}
# print(d,id(d))
# d['k'] = 'vvvv'
# print(d,id(d))
# 修改列表\字典中的某个值,或者是对象的某一个属性 都不会影响这个对象\字典\列表所在的内存空间
# class Person: # 类名
# def __init__(self,n,s,j,h,w,a):
# # 必须叫__init__这个名字,不能改变的,所有的在一个具体的人物出现之后拥有的属性
# self.name = n
# self.sex = s
# self.job = j
# self.level = 0
# self.hp = h
# self.weapon = w
# self.ad = a
# 实例化所经历的步骤
# 1.类名() 之后的第一个事儿 :开辟一块儿内存空间
# 2.调用 __init__ 把空间的内存地址作为self参数传递到函数内部
# 3.所有的这一个对象需要使用的属性都需要和self关联起来
# 4.执行完init中的逻辑之后,self变量会自动的被返回到调用处(发生实例化的地方)
# dog类 实现狗的属性 名字 品种 血量 攻击力 都是可以被通过实例化被定制的
class Dog:
def __init__(self, name, kind, blood, aggr, action):
self.dog_name = name
self.kind = kind
self.hp = blood
self.ad = aggr
self.action = action
small_write = Dog('小白', '哈士奇', '1000', '300', '咬')
print(small_write, small_write.dog_name)
print(small_write, small_write.kind)
print(small_write.__dict__)
# 定义一个用户类,用户名和密码是这个类的属性,实例化两个用户,分别有不同的用户名和密码
class User:
def __init__(self, name, password):
self.user_name = name
self.password = password
zhaoxin = User('赵信', 123456)
gailun = User('盖伦', 123456789)
print(zhaoxin.user_name, zhaoxin.password)
print(gailun.user_name, gailun.password)
|
07f0648241f066c609a566dbd1ca4688530438f8 | wenqiang0517/PythonWholeStack | /day25/04-父类对子类的约束.py | 2,960 | 3.5625 | 4 | # 普通的类
# 抽象类 是一个开发的规范 约束它的所有子类必须实现一些和它同名的方法
# 支付程序
# 微信支付 url连接,告诉你参数什么格式
# {'username':'用户名','money':200}
# 支付宝支付 url连接,告诉你参数什么格式
# {'uname':'用户名','price':200}
# 苹果支付
# class Payment: # 抽象类
# def pay(self,money):
# '''只要你见到了项目中有这种类,你要知道你的子类中必须实现和pay同名的方法'''
# raise NotImplementedError('请在子类中重写同名pay方法')
#
# class Alipay(Payment):
# def __init__(self,name):
# self.name = name
# def pay(self,money):
# dic = {'uname':self.name,'price':money}
# # 想办法调用支付宝支付 url连接 把dic传过去
# print('%s通过支付宝支付%s钱成功'%(self.name,money))
#
# class WeChat(Payment):
# def __init__(self,name):
# self.name = name
# def pay(self,money):
# dic = {'username':self.name,'money':money}
# # 想办法调用微信支付 url连接 把dic传过去
# print('%s通过微信支付%s钱成功'%(self.name,money))
#
# class Apple(Payment):
# def __init__(self,name):
# self.name = name
# def pay(self,money):
# dic = {'name': self.name, 'number': money}
# # 想办法调用苹果支付 url连接 把dic传过去
# print('%s通过苹果支付%s钱成功' % (self.name, money))
# aw = WeChat('alex')
# aw.pay(400)
# aa = Alipay('alex')
# aa.pay(400)
# 归一化设计
# def pay(name,price,kind):
# if kind == 'Wechat':
# obj = WeChat(name)
# elif kind == 'Alipay':
# obj = Alipay(name)
# elif kind == 'Apple':
# obj = Apple(name)
# obj.pay(price)
#
# pay('alex',400,'Wechat')
# pay('alex',400,'Alipay')
# pay('alex',400,'Apple')
# appa = Apple('alex')
# appa.fuqian(500)
# 实现抽象类的另一种方式,约束力强,依赖abc模块
# from abc import ABCMeta,abstractmethod
# class Payment(metaclass=ABCMeta):
# @abstractmethod
# def pay(self,money):
# '''只要你见到了项目中有这种类,你要知道你的子类中必须实现和pay同名的方法'''
# raise NotImplementedError('请在子类中重写同名pay方法')
#
# class Alipay(Payment):
# def __init__(self,name):
# self.name = name
# def pay(self,money):
# dic = {'uname':self.name,'price':money}
# # 想办法调用支付宝支付 url连接 把dic传过去
# print('%s通过支付宝支付%s钱成功'%(self.name,money))
#
# class WeChat(Payment):
# def __init__(self,name):
# self.name = name
# def pay(self,money):
# dic = {'username':self.name,'money':money}
# # 想办法调用微信支付 url连接 把dic传过去
# print('%s通过微信支付%s钱成功'%(self.name,money))
#
# WeChat('alex')
|
831e5bb5428964879e6cf64ca8291cd1771db5dc | wenqiang0517/PythonWholeStack | /day23/01-内容回顾.py | 1,619 | 3.609375 | 4 | # 面向对象
# 类 对象/实例 实例化
# 类是具有相同属性和相似功能的一类事物
# 一个模子\大的范围\抽象
# *****************
# 你可以清楚的知道这一类事物有什么属性,有什么动作
# 但是你不能知道这些属性具体的值
# 对象===实例
# 给类中所有的属性填上具体的值就是一个对象或者实例
# 只有一个类,但是可以有多个对象都是这个类的对象
# 实例化
# 实例 = 类名()
# 首先开辟空间,调用init方法,把开辟的空间地址传递给self参数
# init方法中一般完成 : 把属性的值存储在self的空间里 - 对象的初始化
# self这个地址会作为返回值,返回给"实例"
# 方法 : 定义在类里的函数,并且还带有self参数
# 实例变量 : self.名字
# 类 : 这个类有什么属性 用什么方法 大致的样子
# 不能知道具体的属性对应的值
# 对象 :之前所有的属性值就都明确了
# 类型 :int float str dict list tuple set -- 类(内置的数据类型,内置的类)
# 变量名 = xx数据类型对象
# a = 10
# b = 12.5
# l = [1,2,3]
# d = {'k':'v'}
# o = 函数
# q = 迭代器
# u = 生成器
# i = 类名
# python中一切皆对象,对象的类型就是类
# 所有的对象都有一个类型,class A实例化出来的对象的类型就是A类
# 123的类型是int/float
# 'ajksfk'的类型是str
# {}的类型是dict
# alex = Person()的类型是Person
# 小白 = Dog()的类型是Dog
# def abc():pass
# print(type(abc))
|
269201af84089e19d224373dbdaf11e941033cf8 | wenqiang0517/PythonWholeStack | /day25/07-作业.py | 5,634 | 3.96875 | 4 | # 1,面向对象为什么要有继承
# 当两个类中有相同或相似的静态变量或绑定方法时,使用继承可以减少代码的重用,提高代码可读性,规范编程模式
# 2,python继承时,查找成员的顺序遵循什么规则
# 经典类 -- 深度优先
# 新式类 -- 广度优先
# 3,看代码,写结果
"""
class Base1:
def f1(self):
print('base1.f1')
def f2(self):
print('base1.f2')
def f3(self):
print('base1.f3')
self.f1()
class Base2:
def f1(self):
print('base2.f1')
class Foo(Base1, Base2):
def f0(self):
print('foo.f0')
self.f3()
obj = Foo()
obj.f0()
# 执行结果
# foo.fo
# base1.f3
# base1.f1
"""
# 4,看代码,写结果
"""
class Base:
def f1(self):
print('base.f1')
def f3(self):
self.f1()
print('base.f3')
class Foo(Base):
def f1(self):
print('foo.f1')
def f2(self):
print('foo.f2')
self.f3()
obj = Foo()
obj.f2()
# 执行结果
# foo.f2
# foo.f1
# base.f3
"""
# 5,补充代码实现下列需求
# 5.1 while循环提示用户输入: 用户名、密码、邮箱(正则满足邮箱格式)
# 5.2 为每个用户创建1个对象,并添加到列表中。
# 5.3 当列表中的添加 3个对象后,跳出循环并以此循环打印所有用户的姓名和邮箱
"""
import re
class User:
def __init__(self, username, password, email):
self.username = username
self.password = password
self.email = email
user_list = []
while True:
if len(user_list) < 3:
user = input("请输入用户名:")
pwd = input("请输入密码:")
while True:
email = input("请输入邮箱:").strip()
result = re.search('\w+@\w+\.com(\.cn)?', email)
if result:
email = result.group()
break
else:
print('重新输入')
continue
people = User(user, pwd, email)
user_list.append(people)
else:
for i in user_list:
print(i.username, i.email)
break
"""
# 6,补充代码,实现用户登录和注册
class User:
def __init__(self, name, pwd):
self.name = name
self.pwd = pwd
class Account:
def __init__(self):
# 用户列表,数据格式:[user对象,user对象,user对象]
self.user_list = []
self.dic = {}
self.lis = []
def login(self):
"""
用户登录,输入用户名和密码然后去self.user_list中校验用户合法性
:return:
"""
username = input('请输入用户名').strip()
pwd = input('请输入密码').strip()
for i in self.user_list:
self.dic = dict()
self.dic[i.name] = i.pwd
# print(self.dic)
if username in self.dic.keys():
if pwd == self.dic[username]:
print('登录成功')
return True
else:
print('密码错误,重新输入')
else:
print('用户不存在,请先注册')
self.register()
def register(self):
"""
用户注册,每注册一个用户就创建一个user对象,然后添加到self.user_list中,表示注册成功。
:return:
"""
while True:
username = input('请输入用户名').strip()
pwd = input('请输入密码').strip()
for i in self.user_list:
self.lis = []
self.lis.append(i.name)
print(self.lis)
if username in self.lis:
print('用户已存在,请重新输入')
else:
people = User(username, pwd)
self.user_list.append(people)
break
def run(self):
"""
主程序
:return:
"""
opt_lst = ['登录', '注册']
while True:
for a, b in enumerate(opt_lst, 1):
print(a, b)
num = input('请选择:').strip()
if num == '1':
self.login()
elif num == '2':
self.register()
elif num.upper() == 'Q':
print('退出')
break
else:
print('请重新输入')
if __name__ == '__main__':
obj = Account()
obj.run()
# 6.5 将第6题的需求进行修改,不用列表了,改成读取本地文件
# 7,读代码写结果
"""
class Base:
x = 1
obj = Base()
print(obj.x)
obj.y = 123
print(obj.y)
obj.x = 123
print(obj.x)
print(Base.x)
# 执行结果
# 1
# 123
# 123
# 1
"""
# 8,读代码写结果
"""
class Parent:
x = 1
class Child1(Parent):
pass
class Child2(Parent):
pass
print(Parent.x, Child1.x, Child2.x)
Child2.x = 2
print(Parent.x, Child1.x, Child2.x)
Child1.x = 3
print(Parent.x, Child1.x, Child2.x)
# 执行结果
# 1 1 1
# 1 1 2
# 1 3 2
"""
# 9,读代码写结果
"""
class Foo(object):
n1 = '武沛齐'
n2 = '金老板'
def __init__(self):
self.n1 = 'eva'
obj = Foo()
print(obj.n1)
print(obj.n2)
# 执行结果
# eva
# 金老板
"""
# 10,看代码写结果,如果有错误,则标注错误即可,并且假设程序报错可以继续执行
"""
class Foo(object):
n1 = '武沛齐'
def __init__(self, name):
self.n2 = name
obj = Foo('太白')
print(obj.n1)
print(obj.n2)
print(Foo.n1)
print(Foo.n2)
# 执行结果
# 武沛齐
# 太白
# 武沛齐
# 报错------
"""
|
6f566cf1fba184c37d48176800c2a6073b4041fb | YoniSchirris/SimCLR-1 | /modules/deepmil.py | 6,942 | 3.625 | 4 |
import torch as torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, hidden_dim=2048, intermediate_hidden_dim=128, num_classes=2, attention_bias=True):
super(Attention, self).__init__()
self.L = hidden_dim
# self.D = int(hidden_dim / 2)
self.D = intermediate_hidden_dim
self.K = 1
self.classes = num_classes
self.A_grad = None
# --- transformation f #
# -- What exactly is this attention? Is this gated attention? Normal attention?
# -- This is normal attention. Gated attention adds an element-wise multiplication with a linear layer and a sigmoid non-linearity
self.attention = nn.Sequential( # in : batch_size * L
nn.Linear(self.L, self.D, bias=attention_bias), # per tile, gives 1*D
nn.Tanh(),
nn.Linear(self.D, self.K, bias=attention_bias) # per tile, gives 1*K
)
self.classifier = nn.Sequential(
nn.Linear(self.L * self.K, self.classes),
# nn.Sigmoid() # Since we use the torch crossentropy class we need no sigmoid here
)
def forward(self, H):
"""
Takes an bag of extracted feature vectors and classifies them accordingl
"""
# print(f"Shape of H being passed: {H.shape}")
#TODO CHANGE BACK, THIS WAS FOR THE KATHER DATA MSI TEST
H = H.permute(0,2,1) # (batch x channels x instances) -> (batch x instances x channels)
# print(f"Shape of H being passed after permutation: {H.shape}")
# We pass a (batch x channels) x instances tensor into attention network, which does a tile-wise attention computation. This is then reshaped back to represen the batches
A = self.attention(H.reshape(-1, H.shape[-1])).reshape((H.shape[0], H.shape[1], 1)) # A = (batch x instances x K=1)
A = F.softmax(A, dim=1) # softmax over # instances. A = (batch x instances x K=1)
if self.train and H.requires_grad:
A.register_hook(self._set_grad(A)) # save grad specifically here. only when in train mode and when grad's computed
M = torch.einsum('abc, abd -> ad', A, H) # (batch x instances x K=1) * (batch x instances x channels) -> (batch x instances). We end up with a weighted average feature vectors per patient
Y_out = self.classifier(M) # (batch x channels) -> (batch x num_classes)
if self.classes > 1:
# When doing logistic regression
Y_hat = Y_out.argmax(dim=1) # (batch x num_classes) -> (batch x 1)
else:
# When doing linear regression
Y_hat = Y_out
return Y_out, Y_hat, A
# internal function to extract grad
def _set_grad(self, var):
def hook(grad):
self.A_grad = grad
return hook
# AUXILIARY METHODS
def calculate_classification_error(self, Y, Y_hat):
Y = Y.float()
# _, Y_hat, _ = self.forward(X)
# print(Y_hat)
error = 1. - Y_hat.eq(Y).cpu().float().mean().item()
return error, Y_hat
class AttentionWithStd(nn.Module):
def __init__(self, hidden_dim=2048, intermediate_hidden_dim=128, num_classes=2, attention_bias=True):
super(AttentionWithStd, self).__init__()
self.L = hidden_dim
# self.D = int(hidden_dim / 2)
self.D = intermediate_hidden_dim
self.K = 1
self.classes = num_classes
self.A_grad = None
# --- transformation f #
# -- What exactly is this attention? Is this gated attention? Normal attention?
# -- This is normal attention. Gated attention adds an element-wise multiplication with a linear layer and a sigmoid non-linearity
self.attention = nn.Sequential( # in : batch_size * L
nn.Linear(self.L, self.D, bias=attention_bias), # per tile, gives 1*D
nn.Tanh(),
nn.Linear(self.D, self.K, bias=attention_bias) # per tile, gives 1*K
)
self.classifier = nn.Sequential(
nn.Linear(2 * self.L * self.K, self.classes),
# nn.Sigmoid() # Since we use the torch crossentropy class we need no sigmoid here
)
def compute_weighted_std(self, A, H, M):
# Following https://www.itl.nist.gov/div898/software/dataplot/refman2/ch2/weightsd.pdf
# A: Attention (weight): batch x instances x 1
# H: Hidden: batch x instances x channels
H = H.permute(0,2,1) # batch x channels x instances
# M: Weighted average: batch x channels
M = M.unsqueeze(dim=2) # batch x channels x 1
# ---> S: weighted stdev: batch x channels
# N is non-zero weights for each bag: batch x 1
N = (A != 0).sum(dim=1)
upper = torch.einsum('abc, adb -> ad', A, (H - M)**2) # batch x channels
lower = ((N-1) * torch.sum(A, dim=1)) / N # batch x 1
S = torch.sqrt(upper / lower)
return S
def forward(self, H):
"""
Takes an bag of extracted feature vectors and classifies them accordingl
"""
H = H.permute(0,2,1) # (batch x channels x instances) -> (batch x instances x channels)
# We pass a (batch x channels) x instances tensor into attention network, which does a tile-wise attention computation. This is then reshaped back to represen the batches
A = self.attention(H.reshape(-1, H.shape[-1])).reshape((H.shape[0], H.shape[1], 1)) # A = (batch x instances x K=1)
A = F.softmax(A, dim=1) # softmax over # instances. A = (batch x instances x K=1)
if self.train and H.requires_grad:
A.register_hook(self._set_grad(A)) # save grad specifically here. only when in train mode and when grad's computed
M = torch.einsum('abc, abd -> ad', A, H) # (batch x instances) * (batch x instances x channels) -> (batch x channels). We end up with a weighted average feature vectors per patient
S = self.compute_weighted_std(A, H, M)
MS = torch.cat((M,S), dim=1) # concatenate the two tensors among the feature dimension, giving a twice as big feature
Y_out = self.classifier(MS) # (batch x channels) -> (batch x num_classes)
if self.classes > 1:
# When doing logistic regression
Y_hat = Y_out.argmax(dim=1) # (batch x num_classes) -> (batch x 1)
else:
# When doing linear regression
Y_hat = Y_out
return Y_out, Y_hat, A
# internal function to extract grad
def _set_grad(self, var):
def hook(grad):
self.A_grad = grad
return hook
# AUXILIARY METHODS
def calculate_classification_error(self, Y, Y_hat):
Y = Y.float()
# _, Y_hat, _ = self.forward(X)
# print(Y_hat)
error = 1. - Y_hat.eq(Y).cpu().float().mean().item()
return error, Y_hat
|
51a2d991ba8669d5fa8a30d849904c0bb3c13861 | yangxin6/3DPointCloud | /lesson2/bst.py | 5,093 | 3.546875 | 4 | import numpy as np
import math
from lesson2.result_set import KNNResultSet, RadiusNNResultSet
class Node:
def __init__(self, key, value=-1):
self.left = None
self.right = None
self.key = key
self.value = value
def __str__(self):
return "key: %s, value: %s" % (str(self.key), str(self.value))
# 插入
def insert(root: Node, key, value=-1):
if root is None:
root = Node(key, value)
else:
if key < root.key:
root.left = insert(root.left, key, value)
elif key > root.key:
root.right = insert(root.right, key, value)
else:
pass
return root
# 中序遍历
def inorder(root):
if root is not None:
inorder(root.left)
print(root)
inorder(root.right)
# 前序遍历
def preorder(root):
if root is not None:
print(root)
inorder(root.left)
inorder(root.right)
# 后序遍历
def postorder(root):
if root is not None:
inorder(root.left)
inorder(root.right)
print(root)
# 查找 递归
def search_recursive(root: Node, key):
if root is None or root.key == key:
return root
if key < root.key:
return search_recursive(root.left, key)
elif key > root.key:
return search_recursive(root.right, key)
# 查找 循环
def search_iterative(root: Node, key):
current_node = root
while current_node is not None:
if current_node.key == key:
return current_node
elif key < current_node.key:
current_node = current_node.left
elif key > current_node.key:
current_node = current_node.right
return current_node
# 1NN 最邻近搜索
def search_1nn(root: Node, key, worst_distance=float('inf')):
if root is None or root.key == key:
return root
value = math.fabs(key - root.key)
worst_distance = value if value < worst_distance else worst_distance
if key < root.key:
# 遍历左子树
if math.fabs(key - root.key) < worst_distance:
if root.right is None:
return root
return search_1nn(root.right, key, worst_distance)
else:
if root.left is None:
return root
return search_1nn(root.left, key, worst_distance)
elif key > root.key:
# 遍历右子树
if math.fabs(key - root.key) < worst_distance:
if root.left is None:
return root
return search_1nn(root.left, key, worst_distance)
else:
if root.right is None:
return root
return search_1nn(root.right, key, worst_distance)
# kNN Search
def knn_search(root: Node, result_set: KNNResultSet, key):
if root is None:
return False
result_set.add_point(math.fabs(root.key - key), root.value)
if key <= root.key:
# 遍历左子树
if knn_search(root.left, result_set, key):
return False
elif math.fabs(root.key - key) < result_set.worstDist():
return knn_search(root.right, result_set, key)
elif key > root.key:
# 遍历右子树
if knn_search(root.right, result_set, key):
return False
elif math.fabs(root.key - key) < result_set.worstDist():
return knn_search(root.left, result_set, key)
# radius Search
def radius_search(root: Node, result_set: RadiusNNResultSet, key):
if root is None:
return False
result_set.add_point(math.fabs(root.key - key), root.value)
if key <= root.key:
# 遍历左子树
if radius_search(root.left, result_set, key):
return False
elif math.fabs(root.key - key) < result_set.worstDist():
return radius_search(root.right, result_set, key)
elif key > root.key:
# 遍历右子树
if radius_search(root.right, result_set, key):
return False
elif math.fabs(root.key - key) < result_set.worstDist():
return radius_search(root.left, result_set, key)
def main():
db_size = 100
k = 5
radius = 2.0
data = np.random.permutation(db_size).tolist()
# 临近搜索把 2 删掉
data.remove(11)
root = None
for i, point in enumerate(data):
root = insert(root, point, i)
# inorder(root)
# 递归查找
# value = search_recursive(root, 11)
# print(value)
# 循环查找
# value = search_iterative(root, 11)
# print(value)
# 1NN 最邻近搜索
value = search_1nn(root, 11)
print(value)
# kNN最邻近搜索
knn_result_set = KNNResultSet(capacity=k)
knn_search(root, knn_result_set, 20)
print(knn_result_set)
for i in knn_result_set.dist_index_list:
print(data[i.index])
# radius search
radius_result_set = RadiusNNResultSet(radius=radius)
radius_search(root, radius_result_set, 20)
print(radius_result_set)
for i in radius_result_set.dist_index_list:
print(data[i.index])
if __name__ == '__main__':
main()
|
344be7d9070c5770d993d6376d6bca00c0d171d1 | type9/CS-1.2-Intro-Data-Structures | /Code/dictionary_words.py | 1,263 | 3.890625 | 4 | import random
import sys
from fisheryates_shuffle import shuffle
def random_sentence(num_words):
dictionary = open('/usr/share/dict/words', 'r')
dictionary_list = list()
word_list = list() # final list of words
num_lines = 0 # total word count
for line in dictionary: # converts each line of the dictionary to an array
num_lines += 1
dictionary_list.append(line.strip()) # slices off new line char and appends
dictionary.close() # closes dictionary
if num_lines < num_words: # checks edges case that more words are requested than exist in the file
return False
rand_indexes = gen_rand_indexes(num_lines, num_words) # generates a random index for the number of random words we need
for index in rand_indexes: # for each random index generated, append the word at that index
word = dictionary_list[index]
word_list.append(word)
return shuffle(word_list)
def gen_rand_indexes(num_lines, num_indexes):
indexes = list()
for i in range(num_indexes): # for the number of idexes append a random index
index = random.randint(0, num_lines)
return indexes
if __name__=='__main__':
num_words = sys.argv[1:]
print(random_sentence(int(num_words[0]))) |
15f73a195b2da78189198730bb2f6ffb12fc70dc | BhujayKumarBhatta/myflask | /experiments/ospath.py | 1,426 | 3.5 | 4 | import os
print(" current working directory is % s" % os.getcwd())
print("dirname of current file is % s" % os.path.dirname(__file__))
print("realpath of current file is % s" % os.path.realpath(__file__))
print("abspath of current file is % s" % os.path.abspath(__file__))
print(" one level up previous dir of current file is % s" % os.path.join(os.path.abspath(__file__), '..'))
print("basename of current file is % s" % os.path.basename(__file__))
abspath = os.path.dirname(os.path.abspath(__file__))
print("dirname of os.path.abspath with current file is % s" % os.path.dirname(os.path.abspath(__file__)))
p = os.path.join(abspath, '../')
print("constructed path for prev dir is %s" % p)
print("check if path exists result is %s" % os.path.exists(p))
print("check if path is a dir %s" % os.path.isdir(p))
newfile = os.path.join(p, 'newfile')
with open(newfile, 'w') as f:
f.write('test')
print("check newfile is created %s" % os.path.exists(newfile))
print("check newfile is a file %s" % os.path.isfile(newfile))
print("listing all files and dirs in directory %s " % os.listdir(p))
'''
(venvp3flask) bhujay@DESKTOP-DTA1VEB:/mnt/c/mydev/myflask$ python ospath.py
current working directory is /mnt/c/mydev/myflask
dirname of current file is
abspath of current file is /mnt/c/mydev/myflask/ospath.py
basename of current file is ospath.py
dirname of os.path.abspath with current file is /mnt/c/mydev/myflask
'''
|
5f7c7a681de3287b0e2c05bb05d18df626eb3b54 | sudev/dsa | /graph/UsingAdjacencyList.py | 1,677 | 4.15625 | 4 | # A graph implementation using adjacency list
# Python 3
class Vertex():
def __init__(self, key):
self.id = key
# A dictionary to act as adjacency list.
self.connectedTo = {}
def addEdge(self, vert, w=0):
self.connectedTo[vert] = w
# Repr
def __str__(self):
return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])
def getConnections(self):
return self.connectedTo.keys()
def getId(self):
return self.id
def getWeight(self,vert):
return self.connectedTo[vert]
class Graph():
"""Graph"""
def __init__(self):
# A dictionary to map Vertex-keys and object vertex class.
self.vertlist = {}
self.vertexNum = 0
def addVertex(self, key):
self.vertlist[key] = Vertex(key)
self.vertexNum += 1
return self.vertlist[key]
def getVertex(self, key):
if key in self.vertlist:
return self.vertlist[key]
else:
return None
def addEdge(self, h, t, weight=0):
# If any of vertex not in list create them
if h not in self.vertlist:
nv = self.addVertex(h)
if t not in self.vertlist:
nv = self.addVertex(t)
# Add edge from head to tail
self.vertlist[h].addEdge(self.vertlist[t], weight)
def getVertices(self):
return self.vertlist.keys()
def __iter__(self):
return iter(self.vertlist.values())
# create a graph
g = Graph()
# add some vertex
for i in range(6):
g.addVertex(i)
print (g.vertlist)
# Some Egdes
g.addEdge(0,1,5)
g.addEdge(0,5,2)
g.addEdge(1,2,4)
g.addEdge(2,3,9)
g.addEdge(3,4,7)
g.addEdge(3,5,3)
g.addEdge(4,0,1)
g.addEdge(5,4,8)
g.addEdge(5,2,1)
# View them
for v in g:
for w in v.getConnections():
print("( %s , %s )" % (v.getId(), w.getId()))
|
9fd9d17de19a87eadcace063eab22e9a8f91a3e5 | gurupatoh/pypy | /employee.py | 1,443 | 3.65625 | 4 | class Employee:
def __init__(self, first_name, last_name, employee_id):
self.first_name = first_name
self.last_name = last_name
self.employee_id = employee_id
self.base_salary = 0
def set_base_salary(self, salary):
self.base_salary = salary
class TeachingStaff (Employee):
def __init__(self, first_name, last_name, employee_id, teaching_area, category):
super().__init__(first_name, last_name, employee_id)
self.teaching_area = teaching_area
self.category = category
def get_salary(self):
salary = (((self.category * 10) + 100)/100) * self.base_salary
return salary
def get_staff_info(self):
return 'First name: ' + self.first_name + \
'\nLast name: ' + self.last_name + \
'\nEmployee ID: ' + str(self.employee_id) + \
'\nArea of Expertise: ' + self.teaching_area + \
'\nCategory: ' + str(self.category) + \
'\nSalary: ' + str(self.get_salary())
class AdministrativeStaff(Employee):
def __init__(self, first_name, last_name, employee_id, level):
super().__init__(first_name, last_name, employee_id)
self.level = level
def get_salary(self):
salary = (((self.level * 15) + 100)/100) * self.base_salary
return salary
def get_staff_info(self):
return 'First name: ' + self.first_name + \
'\nLast name: ' + self.last_name + \
'\nEmployee ID: ' + str(self.employee_id) + \
'\nLevel: ' + str(self.level) + \
'\nSalary: ' + str(self.get_salary())
|
c461a5df6e2ef47e30b8a95d8da5f9373e31f182 | TrevorHuval/SchemePrettyPrinter | /Parse/Scanner.py | 7,594 | 3.71875 | 4 | # Scanner -- The lexical analyzer for the Scheme printer and interpreter
import sys
import io
from Tokens import *
class Scanner:
def __init__(self, i):
self.In = i
self.buf = []
self.ch_buf = None
def read(self):
if self.ch_buf == None:
return self.In.read(1)
else:
ch = self.ch_buf
self.ch_buf = None
return ch
def peek(self):
if self.ch_buf == None:
self.ch_buf = self.In.read(1)
return self.ch_buf
else:
return self.ch_buf
@staticmethod
def isDigit(ch):
return ch >= '0' and ch <= '9'
@staticmethod
def isLetter(ch):
return (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')
@staticmethod
def isSpecialInitial(ch):
return ch == '!' or ch == '$' or ch == '%' or ch == '&' or ch == '*' or ch == '/' or ch == ':' or ch == '<' or ch == '=' or ch == '>' or ch == '?' or ch == '^' or ch == '_' or ch == '`'
@staticmethod
def isSpecialSub(ch):
return ch == '+' or ch == '-' or ch == '.' or ch == '@'
@staticmethod
def isPeculiarIdentifier(ch):
return ch == '+' or ch == '-'
@staticmethod
def isInitial(ch):
# return ch.isLetter() or ch.isSpecialInitial()
return (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') or (ch == '!' or ch == '$' or ch == '%' or ch == '&' or ch == '*' or ch == '/' or ch == ':' or ch == '<' or ch == '=' or ch == '>' or ch == '?' or ch == '^' or ch == '_' or ch == '`')
@staticmethod
def isSubsequent(ch):
# return ch.isIntial() or ch.isDigit() or ch.specialSub()
return ((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') or (ch == '!' or ch == '$' or ch == '%' or ch == '&' or ch == '*' or ch == '/' or ch == ':' or ch == '<' or ch == '=' or ch == '>' or ch == '?' or ch == '^' or ch == '_' or ch == '`')) or (ch >= '0' and ch <= '9') or (ch == '+' or ch == '-' or ch == '.' or ch == '@')
def getNextToken(self):
try:
# It would be more efficient if we'd maintain our own
# input buffer for a line and read characters out of that
# buffer, but reading individual characters from the
# input stream is easier.
ch = self.read()
# HOPEFULLY: Skip white space and comments
loopBool = False
while(loopBool == False):
if(ch == ' ' or ch == '\t' or ch == '\r' or ch == '\n'):
return self.getNextToken()
elif(ch == ';'):
commentLoop = False
while(commentLoop == False):
ch = self.read()
if(ch == '\r' or ch == '\n'):
commentLoop = True
return self.getNextToken()
else:
loopBool = True
if ch == 'q': # Special character (quote)
quoteTempScanner = self
chQ = ch
quoteTempScanner.buf = []
quoteLoop = False
quoteTempScanner.buf.append(chQ)
while (quoteLoop == False):
if (quoteTempScanner.peek() != '('):
chQ = quoteTempScanner.read()
quoteTempScanner.buf.append(chQ)
else:
quoteLoop = True
quoteChecker = "".join(quoteTempScanner.buf)
if quoteChecker == "quote":
return Token(TokenType.QUOTE)
# Return None on EOF
if ch == "":
return None
# Special characters
elif ch == '\'':
return Token(TokenType.QUOTE)
elif ch == '(':
return Token(TokenType.LPAREN)
elif ch == ')':
return Token(TokenType.RPAREN)
elif ch == '.':
# We ignore the special identifier `...'.
return Token(TokenType.DOT)
# Boolean constants
elif ch == '#':
ch = self.read()
if ch == 't':
return Token(TokenType.TRUE)
elif ch == 'f':
return Token(TokenType.FALSE)
elif ch == "":
sys.stderr.write("Unexpected EOF following #\n")
return None
else:
sys.stderr.write("Illegal character '" +
chr(ch) + "' following #\n")
return self.getNextToken()
# String constants
elif ch == '"':
self.buf = []
# HOPEFULLY: scan a string into the buffer variable buf
stringLoop = False
while (stringLoop == False):
ch = self.read()
if (ch != '"'):
self.buf.append(ch)
else:
stringLoop = True
return StrToken("".join(self.buf))
# Integer constants
elif self.isDigit(ch):
i = ord(ch) - ord('0')
# HOPEFULLY: scan the number and convert it to an integer
curVal = i
intLoop = False
while (intLoop == False):
if (self.isDigit(self.peek())):
ch = self.read()
i = ord(ch) - ord('0')
curVal = (curVal * 10) + i
else:
intLoop = True
# make sure that the character following the integer
# is not removed from the input stream
return IntToken(curVal)
# Identifiers
elif (self.isInitial(ch) or self.isPeculiarIdentifier(ch)):
# or ch is some other valid first character
# for an identifier
self.buf = []
if self.isInitial(ch):
self.buf.append(ch)
if self.isSubsequent(self.peek()):
ch = self.read()
while(self.isSubsequent(ch)):
self.buf.append(ch)
if(self.isSubsequent(self.peek())):
ch = self.read()
else:
break
elif self.isPeculiarIdentifier(ch):
self.buf.append(ch)
# HOPEFULLY: scan an identifier into the buffer variable buf
# make sure that the character following the identifier
# is not removed from the input stream
return IdentToken("".join(self.buf))
# Illegal character
else:
sys.stderr.write("Illegal input character '" + ch + "'\n")
return self.getNextToken()
except IOError:
sys.stderr.write("IOError: error reading input file\n")
return None
if __name__ == "__main__":
scanner = Scanner(sys.stdin)
tok = scanner.getNextToken()
tt = tok.getType()
print(tt)
if tt == TokenType.INT:
print(tok.getIntVal())
|
45c512a90c4429bb6cc8303d11845d3205583e70 | TrevorHuval/SchemePrettyPrinter | /Special/Special.py | 404 | 3.78125 | 4 | # Special -- Parse tree node strategy for printing special forms
from abc import ABC, abstractmethod
# There are several different approaches for how to implement the Special
# hierarchy. We'll discuss some of them in class. The easiest solution
# is to not add any fields and to use empty constructors.
class Special(ABC):
@abstractmethod
def print(self, t, n, p):
pass
|
31d68d11fdc06c09e0721e6541024eb33b585c91 | selimozen/Hackerrank | /Python/ifelse.py | 546 | 4.3125 | 4 | #ENG: if n is odd, print Weird , if n is even and in the inclusive range of 2 to 5, print Not Weird,
#if n is even and in the inclusive range of 6 to 20, print Weird, if is even and greater than 20, print Not Weird
#TR: Eğer n sayısı tekil ise, 'Weird' yazdır, eğer n sayısı 2 veya 5'e eşit veya arasında ise Not Weird yazdır, eğer n sayısı 6 ile 20'ye eşit veya arasında ise Weird yazdır.
#Eğer n sayısı 20'den büyük ise Not Weird yazdır.
if(n%2==1) or n in range (5,21):
print("Weird")
else:
print("Not Weird")
|
a961f3be1e5d83fbd174bc21851b0753bec84c04 | andersonresende/learning_python | /chapter_19/recursion.py | 1,077 | 4.21875 | 4 | #nao mudar o tipo de uma variavel e uma boa pratica
#nao usar globais dentro de funcoes, pois pode criar dependencias.
#durante a recursao o escopo das funcoes e mantido, por isso funciona.
#recursao exige que vc crie uma funcao, enquanto procedural nao.
#vc nao pode alterar os valores de variaveis a partir de fora da funcao.
def mysum_1(l):
''' Soma uma lista recursivamente.'''
if not l:
return 0
return l[0] + mysum(l[1:])
def mysum_2(l):
'''
Soma uma lista recursivamente
usando ternary expression.
Funciona tambem com strings.
'''
return 0 if not l else l[0] + mysum(l[1:])
def mysum_3(l):
'''
Soma uma lista com while.
'''
soma = 0
while l:
soma+=l[0]
l = l[1:] #essa tecnica dispensa o uso de contadores.Muito bom!!!
return soma
print mysum_3([1,2,3,4])
def sumtree(L):
'''
Funcao avancada de recursao que
soma listas aninhadas. Essa soma
so pode ser feita com recursao
'''
tot = 0
for x in L:
if not isinstance(x, list):
tot += x
else:
tot += sumtree(x)
return tot
L = [1, [2, [3, 4], 5], 6, [7, 8]]
print(sumtree(L))
|
609add66f670ba8c7b3863bc12603b83e71c99af | andersonresende/learning_python | /chapter_18/min.py | 723 | 4.125 | 4 | def min1(*args):
'''
Retorna o menor valor, passado em uma tupla.
'''
res = args[0]
for arg in args[1:]:
if arg < res: res = arg
return res
print min1(10,2,3,4)
def min2(first, *rest):
'''
Retorna o menor valor, recebendo um argumento inicial
e outros em uma tupla.
'''
for arg in rest:
if arg < first: first = arg
return first
print min2('a','c','b')
def min3(*args):
'''
Recebe uma tupla e retorna o meno valor contido.
'''
tmp = list(args)
tmp.sort()
return tmp[0]
print min3([1,2],[3,4],[0,1])
#em python tuplas sao imutaveis logo, nao podemos trocar objetos ou
#reordena-las.
#lista.sort() ordena a lista
#strip()-tirar retira espacos, split('b')-divisao quebra por argumento, ou espaco. |
796c1142383f647d8774b94317198df0904523bd | rwesterman/MachineMarchMadness | /setup/clean_tables.py | 2,256 | 3.546875 | 4 | import pandas as pd
import re
from pprint import pprint
def get_xl_data():
"""
Returns a dictionary of dataframes where each key is a sheet name and each value is a dataframe
:return:
"""
# Setting sheet_name = None imports all sheets
df_dict = pd.read_excel("Training_Data\\KenPom_Rankings.xlsx", sheet_name = None, header = 0)
return df_dict
def remove_unranked(df):
# Add a boolean column checking if a team is ranked (has a number next to team name)
df["ranked?"] = df.Team.str.contains('[0-9]+')
# Create new dataframe of only teams that are ranked
new_df = df[df["ranked?"] == True]
# drop now-unnecessary "ranked?" column from new dataframe
new_df = new_df.drop("ranked?", axis = 1)
return new_df
def extract_mm_rank(df):
# Split only the last space between team name and seed number
teamrank = df.Team.str.rsplit(" ", 1)
# Get the element 0 (team name) and element 1 (seed) separately
team = teamrank.str.get(0)
seed = teamrank.str.get(1)
# Replace original Team column with new column of just team name, and create Seed column
df["Team"] = team
df["Seed"] = seed
return df
def df_to_csv(title, df):
# output new dataframe as .csv
df.to_csv(f"Training_Data\\KenPom_{title}.csv", index = False)
def add_year_col(year, df):
df["Year"] = year
return df
def set_kenpom_complete():
kenpom_complete = pd.DataFrame()
df_dict = get_xl_data()
for year, df in df_dict.items():
# Remove the unranked teams from the data
new_df = remove_unranked(df)
# # Extract the ncaa tournament seed from the team name
new_df = extract_mm_rank(new_df)
# # Add a column for the current year
new_df = add_year_col(year, new_df)
# Add the yearly dataframe to a compilation df of all years
kenpom_complete = kenpom_complete.append(new_df)
# Output the result to csv
df_to_csv("Complete", kenpom_complete)
return kenpom_complete
if __name__ == '__main__':
# Ignore warning about using .loc to replace values in dataframe
pd.options.mode.chained_assignment = None # default='warn'
# Get kenpom complete dataframe
kp_comp = set_kenpom_complete()
|
281fe91d03a3841187b5856bf42524a557c8b28b | dainbot/python-programming-practice | /Algorithm/gcd.py | 376 | 3.921875 | 4 | # Find the greatest common denominator of two numbers.
""" 1 For two integers a and b, where a > b, divide a by b
2 If the remainder, r, is 0, then stop: GCD is b
3 Otherwise, set a to b, b to r, and repeat at step 1 until r is 0 """
def gcd(a, b):
while (b != 0):
t = a
a = b
b = t % b
return a
print(gcd(60, 98))
print(gcd(20, 8)) |
0406e3cc0d3d09c9bbaf400c2808ebf0737d31d4 | bharathkkb/peer-tutor | /peer-tutor-api/timeBlock.py | 1,230 | 4.25 | 4 | import time
import datetime
class TimeBlock:
"""
Returns a ```Time Block``` object with the given startTime and endTime
"""
def __init__(self, start_time, end_time):
self.start_time = start_time
self.end_time = end_time
print("A time block object is created.")
def __str__(self):
"""
Prints the details of a time block.
"""
return self.start_time.strftime("%c") + " " + self.end_time.strftime("%c")
def get_json(self):
"""
returns a json format of a Time Block
"""
time_dict=dict()
time_dict["start"]=self.start_time
time_dict["end"] = self.end_time
return time_dict
def get_start_time(self):
"""
return TimeBlock's end_time
"""
return self.start_time
def get_end_time(self):
"""
return TimeBlock's end_time
"""
return self.end_time
def set_start_time(self, start_time):
"""
set start_time
"""
self.start_time = start_time
return True
def set_end_time(self, end_time):
"""
set end_time
"""
self.end_time = end_time
return True |
ff81de53a5684a0b156037e3e60b5ae9fa4127a7 | MB-TAYLOR/ScrabbleAR-Grupo29 | /ScrabbleAR_py/AiMaquina.py | 3,281 | 3.578125 | 4 | import itertools as it
from pattern.es import spelling,lexicon,parse
Tipo= {'adj':["AO", "JJ","AQ","DI","DT"],
'sus':["NC", "NCS","NCP", "NNS","NP", "NNP","W"],#Revisar volver a comprobar en facil , primero en spell y lexi luego en sus
'verb':[ "VAG", "VBG", "VAI","VAN", "MD", "VAS" , "VMG" , "VMI", "VB", "VMM" ,"VMN" , "VMP", "VBN","VMS","VSG", "VSI","VSN", "VSP","VSS" ]
}
##Verificar si la palabra es verbo o adjetivo parse() -> VB - JJ Dificultad -> Medio,Dificil
#if i in spelling.keys() and i in lexicon.keys(): #Dificultad -> Facil (Existe en lexicon y spelling) Hacer parse , si no es sut hacerla valida , si es sustantivo verificar si esta en spellin o lexicon si esta en alguna de las 2 es valida sino , es invalida
def palabra_larga(lista_palabras):
'''Busca en la lista recibida la palabra que es mas larga y la retorna'''
max=0
palabra_max=""
for x in lista_palabras:
if(len(x)>=max):
max=len(x)
palabra_max=x
return(palabra_max)
def Facil(i,palabras_existentes):
'''Para Facil ,verifica si la palabra es valida(cumple con las condiciones) y si lo es lo agrega a la lista palabras_existentes'''
if (i in spelling.keys() or i in lexicon.keys()):
palabras_existentes.append(i)
def Medio(i,palabras_existentes):
'''Para Medio ,verifica si la palabra es valida(cumple con las condiciones) y si lo es lo agrega a la lista palabras_existentes'''
if i in spelling.keys() and i in lexicon.keys(): #Dificultad -> Medio(Sea adjetivo o verbo)
if(parse(i).split("/")[1] in Tipo['verb']):
palabras_existentes.append(i)
elif(parse(i).split("/")[1] in Tipo['adj']):
palabras_existentes.append(i)
def Dificil_Personalizado(i,palabras_existentes,Dificil_elegido):
'''Para Dificil y Personalizado ,verifica si la palabra es valida(cumple con las condiciones) y si lo es lo agrega a la lista palabras_existentes'''
if i in spelling.keys() and i in lexicon.keys(): #Dificultad -> Medio(Sea adjetivo o verbo)
for x in range(len(Dificil_elegido)):
if(parse(i).split("/")[1] in Tipo[Dificil_elegido[x]]):
palabras_existentes.append(i)
def formar_palabra(letras,dificultad,Dificil_elegido):
'''Recibe x cantidad de letras , una dificultad y para Dificil y Personalizado una lista de tipos de palabras , devuelve la palabra mas larga que
se pueda formar con las condiciones dadas'''
letras=letras.lower()
palabras = set()
for i in range(2,len(letras)+1):
palabras.update((map("".join, it.permutations(letras, i))))
palabras_existentes=[]
for i in palabras:
if (dificultad=="Facil"):
Facil(i,palabras_existentes) or Facil(i.upper(),palabras_existentes)
elif(dificultad=="Medio"):
Medio(i,palabras_existentes) or Medio(i.upper(),palabras_existentes)
elif((dificultad=="Dificil") or (dificultad=="Personalizado")):
Dificil_Personalizado(i,palabras_existentes,Dificil_elegido) or Dificil_Personalizado(i.upper(),palabras_existentes,Dificil_elegido)
return(palabra_larga(palabras_existentes))
#---------Porgrama Principal---
if __name__ == '__main__':
print(formar_palabra("elfsas","Dificil",["adj","sus","verb"]))
|
06a1a7c44faa8688ce5d3229fc019aae1fe86fe5 | chennavamshikrishna/ml_algorithms | /linear regression.py | 595 | 3.65625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
dataset=pd.read_csv('Salary_Data.csv')
#print(dataset)
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1].values
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=0,test_size=1/3)
##print(X_train)
#print(y_train)
from sklearn.linear_model import LinearRegression
lin_reg=LinearRegression()
lin_reg.fit(X_train,y_train)
plt.scatter(X_train,y_train,c='red')
plt.plot(X_train,lin_reg.predict(X_train),c='blue')
plt.show()
print(lin_reg.score(X_train,y_train))
|
6edfeb4705a4f49b354ef9571029d19b9848f8e5 | dani3l8200/100-days-of-python | /day1-printing-start/project1.py | 454 | 4.28125 | 4 | #1. Create a greeting for your program.
print('Welcome to Project1 of 100 Days of Code Python')
#2. Ask the user for the city that they grew up in.
city_grew_user = input('Whats is your country that grew up in?\n')
#3. Ask the user for the name of a pet.
pet_of_user = input('Whats is the name of any pet that having?\n')
#4. Combine the name of their city and pet and show them their band name.
print('Band Name: ' + city_grew_user + " " + pet_of_user)
|
653c613be1c54d924fe2bf398295601817ab30a5 | dani3l8200/100-days-of-python | /day1-printing-start/exercise1.1.py | 265 | 3.828125 | 4 | print('Day 1 - Python Print Function')
print()
print('This function Print() is used for print strings, objects, numbers etc')
print('''Is posibble obtains errors, it is possible if not use parenthesis close or
triple single quote for indicate a print extend xd''')
|
399c6abffb5b4bc60849a84d0c0d112ab7cd2f96 | dyshko/hackerrank | /World Codesprint 13/P4.py | 911 | 3.515625 | 4 | #!/bin/python3
import os
import sys
# Complete the fewestOperationsToBalance function below.
def fewestOperationsToBalance(s):
rs = []
for c in s:
if c == '(':
rs.append(c)
if c == ')':
if len(rs) > 0 and rs[-1] == '(':
rs.pop()
else:
rs.append(c)
a = rs.count(')')
b = len(rs) - a
if a==b:
if a==0:
return 0
else:
return 2
else:
a, b = max(a,b), min(a,b)
if b == 0:
return 1
else:
return 2
return 0
# Return the minimum number of steps to make s balanced.
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = fewestOperationsToBalance(s)
fptr.write(str(result) + '\n')
fptr.close() |
593aa904c7c4b0dd294d25debb3eae2f67f1dc62 | imsilence/refactoring | /chapter01/v03.py | 1,823 | 3.5 | 4 | #encoding: utf-8
import json
import math
'''
以查询替代临时变量
内联局部变量
注意: 重构和性能之间首选选择重构,重构完成后进行性能调优
'''
def statement(invoice, plays):
total = 0
credits = 0
print("Statement for: {0}".format(invoice['customer']))
def play_for(performance):
return plays.get(performance.get('playId', 0), {})
def amount_for(performance):
rt_amount = 0
type_ = play_for(performance).get('type')
if type_ == 'tragedy':
rt_amount = 40000
if performance['audience'] > 30:
rt_amount += 1000 * (performance['audience'] - 30)
elif type_ == 'comedy':
rt_amount = 30000 + 300 * performance['audience']
if performance['audience'] > 20:
rt_amount += 10000 + 500 * (performance['audience'] - 20)
else:
print("error type: {0}", type_)
return rt_amount
for performance in invoice['performances']:
credits += max(performance['audience'] - 30, 0)
if 'comedy' == play_for(performance).get('type'):
credits += math.floor(performance['audience'] / 5)
total += amount_for(performance)
print("\t{0}: {1} ({2} seats)".format(play_for(performance).get('name'), amount_for(performance) / 100, performance['audience']))
print("total: {0}".format(total / 100))
print("credits: {0}".format(credits))
return total, credits
if __name__ == '__main__':
invoices = []
with open("invoices.json", "rt", encoding="utf-8") as cxt:
invoices = json.loads(cxt.read())
plays = {}
with open("plays.json", "rt", encoding="utf-8") as cxt:
plays = json.loads(cxt.read())
for invoice in invoices:
statement(invoice, plays) |
215ae22230731d3c486c7b652128fb1b212c78e0 | islamrumon/PythonProblems | /Sets.py | 2,058 | 4.40625 | 4 | # Write a Python program to create a new empty set.
x =set()
print(x)
n = set([0, 1, 2, 3, 4])
print(n)
# Write a Python program to iteration over sets.
num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n)
# Write a Python program to add member(s) in a set.
color_set = set()
color_set.add("Red")
print(color_set)
color_set.update(["Blue","Green"])
print(color_set)
# Write a Python program to remove item(s) from set.
num_set = set([0, 1, 3, 4, 5])
num_set.pop()
print(num_set)
num_set.pop()
print(num_set)
# Write a Python program to create an intersection of sets.
#Intersection
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx & sety
print(setz)
# Write a Python program to create a union of sets.
seta = setx | sety
print(seta)
# Write a Python program to create set difference.
setn = setx - sety
print(setn)
# Write a Python program to create a symmetric difference.
seto = setx^sety
print(setn)
# Write a Python program to test whether every element in s is in t and every element in t is in s.
setz = set(["mango"])
issubset = setx <= sety
print(issubset)
issuperset = setx >= sety
print(issuperset)
issubset = setz <= sety
print(issubset)
issuperset = sety >= setz
print(issuperset)
# Write a Python program to create a shallow copy of sets.
setp = set(["Red", "Green"])
setq = set(["Green", "Red"])
#A shallow copy
setr = setp.copy()
print(setr)
# Write a Python program to clear a set.
setq.clear()
print(setq)
# Write a Python program to use of frozensets.
x = frozenset([1, 2, 3, 4, 5])
y = frozenset([3, 4, 5, 6, 7])
#use isdisjoint(). Return True if the set has no elements in common with other.
print(x.isdisjoint(y))
#use difference(). Return a new set with elements in the set that are not in the others.
print(x.difference(y))
#new set with elements from both x and y
print(x | y)
# Write a Python program to find maximum and the minimum value in a set.
#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find maximum value
print(max(seta))
#Find minimum value
print(min(seta))
|
a8d0633d0c553059cb45d78de73748d340fa50e7 | yoku2010/just-code | /algorithms/number_combination.py | 2,008 | 3.953125 | 4 | #!/usr/bin/python
class NumberCombination(object):
def __init__(self, number_list, number):
self.number_list = number_list
self.number = number
self.result = []
def process(self):
'''
Algorithm process
'''
# Make It Unique
self.number_list = list(set(self.number_list))
# Number Count
self.number_list_len = len(self.number_list)
# Sort number list
self.number_list.sort()
i = 0
last_index = 0
lst = []
while i < self.number_list_len:
# figure out sum of current combination list
lst_sum = sum(lst)
# check the sum of combination list is less, equal or greater then the given number
if lst_sum < self.number:
lst.append(self.number_list[i]) # add more number in combination list
i += 1
else:
if lst_sum == self.number:
self.result.append(list(lst)) # append combination list into result list
lst_len = len(lst)
if 1 == lst_len:
break # because there is no more combination exist.
elif lst_len > 1:
lst.pop() # pop the combination list
last_index = self.number_list.index(lst.pop()) # pop the combination list and find the last index
i = last_index + 1
# if the last value is equal to the given number then add that into result list. because that will skip as per the logic of algorithm.
if self.number_list[self.number_list_len - 1] == self.number:
self.result.append([self.number])
def display(self):
'''
Display the result list
'''
for i in xrange(len(self.result)):
print ','.join(map(str,self.result[i]))
if '__main__' == __name__:
nc = NumberCombination([2,4,6,7,3,8,1,5,9], 9)
nc.process()
nc.display()
|
3bedc90616961f248924953f468206cc06e27f92 | yoku2010/just-code | /utility/spiral-pattern/code.py | 1,339 | 4.03125 | 4 | #!/usr/bin/python
"""
@author: Yogesh Kumar
@summary: To draw a spiral pattern of numbers like that.
Enter Number of Element: 21
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21
"""
def spiral_pattern(number):
n = 2
while True:
if number <= n*n:
a = [["-" for x in range(n)] for y in range(n)]
break
n += 2
k = 0
l = n*n + 1
c1 = 0
c2 = n - 1
r1 = 0
r2 = n - 1
while k<n*n:
for i in range(c1, c2 + 1):
k+=1
a[r1][i] = l - k <= number and l - k or ""
for i in range(r1 + 1, r2 + 1):
k+=1
a[i][c2] = l - k <= number and l - k or ""
for i in range(c2-1, c1 - 1, -1):
k+=1
a[r2][i] = l - k <= number and l - k or ""
for i in range(r2-1, r1, -1):
k+=1
a[i][c1] = l - k <= number and l - k or ""
c1 += 1
c2 -= 1
r1 += 1
r2 -= 1
print_pattern(a, n);
def print_pattern (a, n):
print "The Spiral Matrix is: "
print "\n".join(map(str, ["\t".join(map(str,a[i])) for i in range(n)]))
if __name__ == "__main__":
number = int(raw_input("Enter Number of Element: "));
spiral_pattern(number);
|
497ebf8e5b03ac3e9a424ef76838da53a46da8bb | shobasri/TrainingAssignments | /Naveena/patterns.py | 1,155 | 3.6875 | 4 | #!/usr/bin/python
import sys
r=int(sys.argv[1])
n = 0
print ("Pattern B")
for x in range (0,(r+1)):
n = n + 1
for a in range (0, n-1):
print ('*', end = '')
print ()
print ('')
print ("Pattern A")
for b in range (0,(r+1)):
n = n - 1
for d in range (0, n+1):
print ('*', end = '')
print ()
print ('')
print ("Pattern D")
for e in range ((r+1),0,-1):
print (((r+1)-e) * ' ' + e * '*')
print ('')
print ("Pattern C")
for g in range ((r+1),0,-1):
print (g * ' ' + ((r+1)-g) * '*')
print ('')
print ("Patter E")
print ('')
for row in range(1,5):
print (" " * (row -1) + row * "*" + (16 - row * 4) * " " + row * "*")
for row in range (0,4):
print (" " * (3-row)+ "*" *(4 -row) + row * 4 * " " +"*" *(4 -row))
print ("Pattern F")
for f in range ((r+1),0,-1):
print (f * ' ' + ((r+1)-f) * '* ')
print ('')
print ("Pattern H")
for h in range (0,(r+1)):
print ((r-h) * ' ' + '*'.join([' ']*h))
print ('')
print ("Pattern I")
for i in range (0,(r+1)):
print ((r-i) * ' ' + '*'.join(['*']*i))
print ((r-1) * ' ' + '*')
for i in range (1,(r-1)):
print ((r-i) * ' ' + '*'.join(['*']*i))
print ('')
|
42178b00cf2ba281a87c64c5ab945908fc1202a8 | shobasri/TrainingAssignments | /Sony/Assignments/divisable7.py | 140 | 4.34375 | 4 | #given no divisible by 7 or not
a=input("Enter a number ")
if (a%7==0):
print a,"is divsible by 7"
else:
print a,"is not divisible by 7"
|
81c99b4ece820adc4c322bbf5efaa475d5bd3a83 | mijodong/euler | /python/problem-20.py | 138 | 3.765625 | 4 | factorial = 1
for _ in range(1, 101):
factorial *= _
value_sum = 0
for _ in str(factorial):
value_sum += int(_)
print(value_sum) |
489d48a54197ec60c9e916605caf8235b09dddc7 | mijodong/euler | /python/problem-4.py | 464 | 3.84375 | 4 | from math import floor
def is_palindrome(value):
value_str = str(value)
length = len(value_str)
for i in range(floor(length / 2)):
if value_str[i] != value_str[-i - 1]:
return False
return True
palindrome = 0
for i1 in range(100, 999):
for i2 in range(100, 999):
product = i1 * i2
if is_palindrome(quotient):
if product > palindrome:
palindrome = product
print(palindrome) |
e49a5633e9f24f787b78987b8954b5c4b40f3b82 | roxdsouza/PythonLessons | /RegExp.py | 4,328 | 4.3125 | 4 | import re
# re module is used for regular expression
# Documentation - https://docs.python.org/2/library/re.html
# Examples - https://www.guru99.com/python-regular-expressions-complete-tutorial.html
# "\d" matches any digit; "\D" matches any non digit.
# "\s" matches any whitespace character; '\S" matches any non-alphanumeric character.
# "\w" matches any alphanumeric characters; "\W" matches any non-alphanumeric character.
# "^" matches the beginning of the string; "$" matches the end of the string.
# "\b" matched a word boundary; "\B" matches position that is not a word boundary.
# x|y matches x or y
# x* matches zero or more x's
# x+ matches one or more x's
# x? matches zero or one x's
# x{m,n} matches i x's, where m<i<n. Example >> "d{2,3}" matches "dd" or "ddd"
text = 'Game of Thrones is roughly based on the storylines of A Song of Ice and Fire, set in the fictional \
Seven Kingdoms of Westeros and the continent of Essos. The series chronicles the violent dynastic struggles among \
the realm\'s noble families for the Iron Throne, while other families fight for independence from it. It opens with \
additional threats in the icy North and Essos in the east.'
# print ('---------------SEARCH / MATCH FUNCTION---------------')
# print re.search('Game', text) #Just returns the MATCH object for the first instance of the match within a string
# match = re.search('Game', text)
# print match.group()
# print re.match('Game', text) #Searches for the word at the begining of the string and returns a MATCH object.
# print re.match('is', text)
#
# print ('---------------FIND ALL---------------')
# print re.findall('the', text) #Searches for ALL the instances of the word in the entire string
# print len(re.findall('the', text))
#
# print re.findall(r'noble|icy|power', text) #using the OR operator. r - means raw string.
# print re.findall(r'i[a-z]*', text) #Find all words contains 'i' and the rest of the word
# print re.findall(r'i[a-z]+', text) #Find all words contains 'i' and the rest of the word
#
# print re.findall(r'i[a-z].', text) # '.' means show one character after match
# print re.findall(r'\bi[a-z]\b', text) #Find 2 letter words starting with 'i'
# print re.findall(r'\ba[a-n|p-z]*\b', text) # Ignores words starting with 'a' but contains 'o'
# print re.findall(r'\ba[^o]*\b', text) # Ignores words starting with 'a' but contains 'o'
# print re.findall(r'^\w+', text) # Matches the start of a string
# print re.findall(r'\bf[a-z]*\b', text) # Searches for words that start with 'f'
#
# print ('---------------MATCH OBJECT---------------')
# r = re.search('violent', text)
# print r.group() # Returns the string that matched
#
# print 'Starting location of the index', r.start()
# print 'Ending location of the index', r.end()
# print 'Start and end location of the index (returns in Tuple)', r.span()
#
# # r = re.search('final', text) #Trying to find a non-existent word and it throws an exception.
# # print r.group() # Returns the string that matched
#
# m = re.match(r"(..)+", "edureka") # This matches every 2 consecutive characters - ed, ur, ek.
# # 'a' is left out as it does not have a pair.
# print m.group(1) # Returns only the last match i.e. ek
#
# # Another example
#
# var = "I work at Edureka, and thomas@edureka.in is my email id."
# domain = re.search(r'[\w.]+@[\w.]+', var)
# print (domain.group())
# DatePattern = 'There are multiple date patterns. Some of them are 01-01-2019, 01-Jan-2019, 2019-01-01, 01/01/2019, 01 Jan 2019, 01-01-19, etc.'
#
# # r = re.search(r'\b[\d]*|-|[\d.]|-|[\d.]\b', DatePattern)
# r = re.search(r'[\d]{4}-[\d]{2}-[\d]{2}', DatePattern)
# print (r.group())
# # Verify SSN number assuming the format is XXX-XX-XXXX
#
# SSNData = "Social security number of Michael Clarke is 724-132-8761"
# r = re.search(r'[\d]{3}-[\d]{3}-[\d]{4}', SSNData)
# print (r.group())
#
# Program to find a particular e-mail address
# Emails = "sachin@yahoo.com, tendulkar@yahoo.co.in, michael@aol.com, pravin@gmail.com, manisha@microsoft.com, "\
# "mitesh@gmail.com, tejas@gmail.co.in, manoj@microsoft.com"
# pick = re.findall(r'[\w\.-]+@microsoft[\w\.-]+', Emails)
#
# for mails in pick:
# print mails
# Program to find IPv4 addresses
IPaddr = "Here are a few samples of IPv4 addresses: 192.0.2.1, 172.16.254.1, 192.168.1.15, 255.255.255.255, 10.142.0.2"
addr = re.findall(r'[\d]{1,3}.[\d]{1,3}.[\d]{1,3}.[\d]{1,3}', IPaddr)
for IPtext in addr:
print IPtext |
aae16277602c86460bafa3df51c1eb258c7d85db | roxdsouza/PythonLessons | /Dictionaries.py | 2,088 | 4.65625 | 5 | # Dictionary is written as a series of key:value pairs seperated by commas, enclosed in curly braces{}.
# An empty dictionary is an empty {}.
# Dictionaries can be nested by writing one value inside another dictionary, or within a list or tuple.
print "--------------------------------"
# Defining dictionary
dic1 = {'c1':'Churchgate', 'c5':'Marine Drive', 'c4':'Vile Parle', 'c3':"Bandra", 'c2':'Dadar', 'c6':'Andheri'}
dic2 = {'w3':'Wadala', 'c5':'Chowpatty', 'w4':'Kurla', 'w5':"Thane", 'c2':'Dadar', 'w7':'Andheri'}
# Printing dictionary
print dic1
# Print all keys
print dic1.keys()
# Print all values
print dic1.values()
# Printing a particular value using key
print 'Value of key c4 is: ' + dic1["c4"]
print "Value of key c4 is: " + dic1.get("c4")
# Print all keys and values
print dic1.items()
print "--------------------------------"
# Add value in dictionalry
dic1['w1']='Victoria Terminus'
dic1['w2']=10001
dic1[20]='Byculla'
print dic1
print "--------------------------------"
# Finding data type of key
print [type(i) for i in dic1.keys()]
print "--------------------------------"
print "Length of dictionary is:",
print len(dic1)
print "--------------------------------"
# "in" used to test whether a key is present in the dictionary
print dic1
print 20 in dic1
print "c6" in dic1
print "c6" not in dic1
print "--------------------------------"
# Adding values in dictionary using another dictionary
# If same key exist in both the dictionaries then it will update the value of the key available from dic2 in dic1
# If both dictionaries have same key + value then it will only keep the original value from dic1
dic1.update(dic2)
print dic1
print "--------------------------------"
# Remove value from dictionary
dic1.pop('w4')
print dic1
print "--------------------------------"
# Looping through dictionary
for key, value in dic2.items():
print key, value
print "--------------------------------"
dic1.clear()
print "Total number of elements in dic1 after using the clear function: ",
print len(dic1)
print "-------------THE END-------------------" |
4fa1560b335f86dae73766c7f6b316e339d54671 | roxdsouza/PythonLessons | /Classes04.py | 964 | 4.125 | 4 | # Program to understand class and instance variables
# class Edureka:
#
# # Defining a class variable
# domain = 'Big data analytics'
#
# def SetCourse(self, name): # name is an instance variable
# # Defining an instance variable
# self.name = name
#
#
# obj1 = Edureka() # Creating an instance of the class Edureka
# obj2 = Edureka()
#
# print obj1.domain
# print obj2.domain
#
# obj1.SetCourse('Python') # Calling the method
# obj2.SetCourse('Hadoop')
#
# print obj1.name
# print obj2.name
########################################################
# Program to understand more about constructor or distructor
class Edureka:
def __init__(self, name):
self.name = name
def __del__(self): # Called when an instance is about to be destroyed
print 'Destructor started'
obj1 = Edureka('Python')
obj2 = obj1
# Calling the __del__ function
del obj1
obj1 = obj2
print obj2.name
print obj1.name
del obj1, obj2 |
7b73ee12749b361ea8b2581da5ff19ad01c584f6 | mertzd1/MachineLearning-Python | /Regression/Section 5 - Multiple Linear Regression/multiple_linear_regression_1.py | 2,315 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 10 13:51:42 2019
@author: donal
"""
#When creating dummy variables ***Always** omit one dummy variable in a multiple regression model
#This is called Avoiding the Dummy Variable Trap
#importing the Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the dataset
#saved to my working folder and then pressed F5
dataset= pd.read_csv('50_Startups.csv')
X=dataset.iloc[:,:-1].values
y = dataset.iloc[:,4].values
# Encoding categorical data
# Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
onehotencoder = OneHotEncoder(categorical_features = [3])
X = onehotencoder.fit_transform(X).toarray()
#Avoiding the Dummy Variable Trap
X=X[:,1:]
#Splitting the dataset inuto the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
#Feature Scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train=sc_X.fit_transform(X_train)
X_test=sc_X.transform(X_test)"""
#Fit Multiple Linear Regression to the Training Set
from sklearn.linear_model import LinearRegression
regressor=LinearRegression()
regressor.fit(X_train, y_train)
#Predicting the Test set resutls
y_pred=regressor.predict(X_test)
#Note if you have an error while running code and have to reenter that code to make it work
#you must remove all variables from the console or it will throw the data off
#Building the optimal model using backward elimination
import statsmodels.formula.api as sm
import statsmodels.regression.linear_model as lm
X = np.append(arr=np.ones((50, 1)).astype(int), values=X ,axis =1)
X_opt = X[:, [0,1,2,3,4,5]]
regressor_ols= lm.OLS(endog=y, exog=X_opt).fit()
regressor_ols.summary()
X_opt = X[:, [0,1,3,4,5]]
regressor_ols= lm.OLS(endog=y, exog=X_opt).fit()
regressor_ols.summary()
X_opt = X[:, [0,3,4,5]]
regressor_ols= lm.OLS(endog=y, exog=X_opt).fit()
regressor_ols.summary()
X_opt = X[:, [0,3,5]]
regressor_ols= lm.OLS(endog=y, exog=X_opt).fit()
regressor_ols.summary()
X_opt = X[:, [0,3]]
regressor_ols= lm.OLS(endog=y, exog=X_opt).fit()
regressor_ols.summary()
|
e8c8201207c84dade087650a761921226e2f0cf1 | mbytes21/Python-Autoclicker | /autoclick.py | 352 | 3.671875 | 4 | import time
import pynput
from time import sleep
from pynput import mouse
from pynput.mouse import Button, Controller
mouse = Controller()
delay1 = input("How long until the clicking starts? ")
clicknum = int(input("How many times do you want it to click? "))
x=int(delay1)
for i in range(x):
sleep(1)
mouse.click(Button.left, clicknum) |
a8630178035f69f14bb41418b6b70a3fc120945e | olk911/ps-pb-hw3 | /plural_form.py | 725 | 3.90625 | 4 | def plural_form(number, form1, form2, form3):
f ='' # правильная форма для числа number
date = str(number) # преобразование в строку и следовательно в список []
if int(date[-1]) == 1 and int(date[-2:]) != 11:
f = form1
if int(date[-1]) > 1 and int(date[-1]) < 5:
f = form2
if int(date[-1]) == 0 or (int(date[-1]) > 4 and int(date[-1]) <= 9):
f = form3
return date + ' ' + f
print(plural_form(1, 'form1', 'form2', 'form3'))
print(plural_form(105, 'студент', 'студента', 'студентов'))
print(plural_form(39, 'яблоко', 'яблока', 'яблок')) |
1df9b8f1c11e8837892fb037232d3be40a124f80 | GenghisKhanDoritos/Calculator-python-ver.- | /Calculator_Memory_Type.py | 2,094 | 4.0625 | 4 | #Calculator Memory Type.py
print('='*50)
print('Calculator Memory type')
print('='*50)
Working_Memory = 0
Secondary_Memory = 0
def operation(FN,OP,SN,Default):
if OP=='1':
Working_Memory = Default+FN+SN
print(Working_Memory)
elif OP=='2':
Working_Memory = Default+FN-SN
print(Working_Memory)
elif OP=='3':
Working_Memory = FN*SN
print(Working_Memory)
elif OP=='4':
Working_Memory = FN/SN
print(Working_Memory)
else:
print('Please input operator number correctly')
print('''1.Add
2.Subtract
3.Multiply
4.Division''')
OP=input("Input Operator number correctly\n")
return Working_Memory
def operation2(Default,SN,ME,OP):
if SN==0:
Working_Memory = 0
print(Working_Memory)
elif OP=='1':
Working_Memory = Default+SN
print(Working_Memory)
elif OP=='2':
Working_Memory = Default-SN
print(Working_Memory)
elif OP=='3':
Working_Memory = Default*SN
print(Working_Memory)
elif OP=='4':
Working_Memory = Default/SN
print(Working_Memory)
else:
print('Please input operator number correctly')
print('''1.Add
2.Subtract
3.Multiply
4.Division''')
OP=input("Input Operator In Number(if you input 0,input any operator.)\n")
return Working_Memory
First_Number = int(input("Input First number\n"))
print('''1.Add
2.Subtract
3.Multiply
4.Division''')
Operator = input('Input Operator in Number\n')
Second_Number = int(input('Input Second number\n'))
Working_Memory = operation(First_Number,Operator,Second_Number,Working_Memory)
while True:
Second_Number = int(input("Input Next number('input 0 to Reset')\n"))
print('''1.Add
2.Subtract
3.Multiply
4.Division''')
Operator = input('Input Operator in Number(if you input 0, input any Operator)\n')
Working_Memory = operation2(Working_Memory,Second_Number,Secondary_Memory,Operator) |
8e56d445bc8dfff8db0f2658a92f19dcbb2f7922 | ArrobaAnderson/Ejer_Class | /Sem2/condicion2.py | 425 | 3.875 | 4 | class Condicion:
def __init__(self,num1=6,num2=8):
self.numero1= num1
self.numero2= num2
numero= self.numero1+self.numero2
self.numero3= numero
def usoIf(self):
print(self.numero3)
print("instancia de la clase")
cond1= Condicion(70,94)
cond2= Condicion()
print(cond2.numero3)
cond1.usoIf()
cond2.usoIf()
print("Gracias por su visita")
|
6e4eac8476b5580ec806298f05ebfd0386bd57f4 | ArrobaAnderson/Ejer_Class | /Sem5&6/Ordenaciones.py | 4,850 | 3.75 | 4 | class Ordernar:
def __init__(self,lista):
self.lista=lista
def recorrer(self):
for ele in self.lista:
print(ele)
def recorrerPosicion(self):
for pos,ele in enumerate(self.lista):
print(pos,ele)
def recorrerRange(self):
for pos in range(len(self.lista)):
print(pos,self.lista[pos])
def buscar(self,buscado):
enc=False
for pos,ele in enumerate(self.lista):
if ele == buscado:
enc=True
break
if enc == True : return pos
else: return -1
def ordenarAsc(self):
for pos in range(0,len(self.lista)):
for sig in range(pos+1,len(self.lista)):
if self.lista[pos] > self.lista[sig]:
aux = self.lista[pos]
self.lista[pos]=self.lista[sig]
self.lista[sig]=aux
# ord1.recorrerElemento()
# ord1.recorrerPosicion()
# ord1.recorrerRange()
# print(ord1.buscar(3))
# buscado=9
# resp = ord1.buscar()
# if resp !=-1:
# print("El Numero={} se encuentra en la Posicion:({}) de la lsta:{}".format(buscado,resp,ord1.lista))
# else:
# print("El Numero={} no se encuentra en la lista".format(buscado,ord1.lista))
def ordenarDes(self):
for pos,ele in enumerate(self.lista):
for sig in range(pos+1,len(self.lista)):
if ele < self.lista[sig]:
aux = self.lista[pos]
self.lista[pos]=self.lista[sig]
self.lista[sig]= aux
def primer(self):
return self.lista[0]
#Complejo
def primerEliminado(self):
primer = self.lista[0]
auxlista = []
for pos in range(1,len(self.lista)):
auxlista.append(self.lista[pos])
self.lista=auxlista
return primer
#Fácil
def primerEliminado2(self):
primer = self.lista[0]
self.lista = self.lista[1:]
return primer
def ultimo(self):
return self.lista[-1]
#Complejo
def ultimoEliminado(self):
ultimo = self.lista[-1]
auxlista = []
for pos in range(0,len(self.lista)-1):
auxlista.append(self.lista[pos])
self.lista=auxlista
return ultimo
#Fácil
def ultimoEliminado2(self):
ultimo = self.lista[-1]
self.lista = self.lista[0:-1]
return ultimo
# Insertar
def insertar(self,num):
self.ordenarAsc()
auxlista=[]
for pos,ele in enumerate(self.lista):
if num < ele:
auxlista.append(num)
break
self.lista=self.lista[0:pos]+auxlista+self.lista[pos:]
def insertar2(self,num):
self.ordenarasc()
auxlista=[]
for pos,ele in enumerate(self.lista):
if num < ele:
break
for i in range(pos):
auxlista.append(self.lista[i])
auxlista.append(num)
for j in range(pos,len(self.lista)):
auxlista.append(self.lista[j])
self.lista=auxlista
#Usar cuando no hay limitaciones
def insertarorden(self,num):
self.lista.append(num)
self.ordenarAsc()
#Eliminar
def eliminar(self,num):
for pos,ele in enumerate(self.lista):
if num==ele:
break
self.lista=self.lista[0:pos]+self.lista[pos+1:]
def eliminar2(self,num):
enc=False
for pos,ele in enumerate(self.lista):
if num==ele:
enc=True
break
if enc: self.lista=self.lista[0:pos]+self.lista[pos+1:]
return enc
lista = [2,3,8,10]
#lista = [2,3,1,5,8,10]
#inserta= 4
ord1= Ordernar(lista)
if ord1.eliminar(8)==True: print("el numero se elimino de la lista",ord1.lista)
else: print("el numero nose encuentra en la lista")
#print(ord1.lista)
#print(ord1.ultimoEliminado())
#print(ord1.insertar(5))
#print(ord1.insertar2(5))
#print(ord1.eliminar(8))
#print(ord1.lista)
# print("Primer", ord1.primer())
# print("Segundo", ord1.ultimo())
# print("Normal",ord1.lista)
# ord1.ordenarAsc()
# print("Asc",ord1.lista)
# ord1.ordenarDes()
# print("Des",ord1.lista)
lista = [2,4,8,5,10]
#Posicion 0 1 2 3 4
x= lista[2]
list1 = lista[1:]
list2 = lista[:-1]
for pos in range(len(lista)-1):
print("Primer for", pos, lista[pos])
for j in range(pos+1,len(lista)):
print("Segundo for",j,lista[j])
input("presione una tecla para continuar..")
|
81bb1e1f9c2972273b89457532534d9ba321654c | ArrobaAnderson/Ejer_Class | /Sem2/Diccionario.py | 915 | 3.625 | 4 | class Sintaxis:
instancia=0
def __init__(self,dato="LLamando al constructor1"):
self.frase=dato
Sintaxis.instancia = Sintaxis.instancia+1
def usoVariables(self):
edad, _peso = 21, 70.5
nombres = "Leonardo Arroba"
dirDomiciliaria= "El Triunfo"
Tipo_sexo = "M"
civil=True
usuario=()
usuario = ('Zancrow','186','zancrow1864@gmail.com')
materias=[]
materias = ['Programacion Web','PHP','POO']
estudiante={}
estudiante = {"nombre":"Anderson","edad":21,}
edad= estudiante["edad"]
estudiante["edad"]= 18
print(usuario,usuario[0],usuario[0:2],usuario[-1])
print(nombres,nombres[0],nombres[0:2],nombres[-1])
print(materias,materias[2:],materias[:3],materias[::-1],materias[-2:])
ejer1 = Sintaxis()
ejer1.usoVariables()
|
29aa99e1ece33882ff8e24ba1feb008b4eb9bd8f | LewisT543/Notes | /Learning_OOP/Classes and Instances/Python OOP 2 - Class Variables.py | 868 | 4.03125 | 4 | # SELF REFERS TO THE INSTANCE, in this case EMPLOYEE is what self is
# referring to
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, fname, lname, pay):
self.fname = fname
self.lname = lname
self.pay = pay
self.email = fname + '.' + lname + '@company.com'
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.fname, self.lname)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
emp_1 = Employee('Jeff', 'Goldblum', 55000)
emp_2 = Employee('Sid', 'Meyers', 100000)
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
Employee.raise_amount = 1.05
emp_1.raise_amount = 1.07
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
print(Employee.num_of_emps)
|
e759d2b446b087c10defe5664b855e15f468c650 | LewisT543/Notes | /Learning_OOP/Different Faces of Python Methods/11Part3.py | 2,284 | 3.671875 | 4 | from datetime import datetime
class TimeList(list):
@staticmethod
def add_timestamp(txt):
now = datetime.now().strftime("%Y-%m-%d (%H:%M:%S)")
return f'{now} >>> {txt} '
def __setitem__(self, index, value):
value = TimeList.add_timestamp(value)
list.__setitem__(self, index, value)
def append(self, value):
value = TimeList.add_timestamp(value)
list.append(self, value)
def insert(self, index, value):
value = TimeList.add_timestamp(value)
list.insert(self, index, value)
class AccountException(Exception):
pass
class BankAccount:
def __init__(self, acc_num, balance):
self.__acc_num = acc_num
self.__balance = balance
self.__history = TimeList()
self.__history.append('Account Created')
@property
def account_number(self):
return self.__acc_num
@account_number.setter
def account_number(self, num):
return AccountException('Cannot edit your account number.')
@property
def balance(self):
return self.__balance
@balance.setter
def balance(self, num):
if num < 0:
raise AccountException('Cannot set negative balance.')
else:
self.__balance = num
self.__history.append(f'Updated Balance: {self.__balance}')
@balance.deleter
def balance(self):
if self.__balance == 0:
self.__history = None
else:
raise AccountException('Cant do that, balance is not 0')
@property
def history(self):
return self.__history
def transact(self, amount):
if self.__balance + amount < 0:
raise AccountException('Insufficient funds')
if amount > 100000 or amount < -100000:
print('Thats a heckin large transaction mate (>100000)')
self.__history.append(f'Large Transaction detected, Size: {amount}')
self.__balance += amount
self.__history.append(f'Transaction Succesful, Balance: {self.__balance}')
def neat_history(BA_obj):
for i in BA_obj.history:
print(i)
myac = BankAccount(1234, 10)
myac.transact(10)
myac.transact(20)
myac.transact(-10)
myac.transact(50)
myac.transact(124231)
neat_history(myac)
|
78d56b418170f3c6a011439fc528ee4fec66e4ce | LewisT543/Notes | /Learning_Tkinter/17Main-window+user-convos.py.py | 4,950 | 4.09375 | 4 | #### SHAPING THE MAIN WINDOW AND CONVERSING WITH THE USER ####
# CHANGING ASPECTS OF THE WINDOW
# Changing the TITLE
import tkinter as tk
def click(*args):
global counter
if counter > 0:
counter -= 1
window.title(str(counter))
counter = 10
window = tk.Tk()
window.title(str(counter))
window.bind("<Button-1>", click)
window.mainloop()
# Changing the ICON
from tkinter import PhotoImage
window = tk.Tk()
window.title('Icon?')
window.tk.call('wm', 'iconphoto', window._w, PhotoImage(file='logo.png'))
window.bind("<Button-1>", lambda e: window.destroy())
window.mainloop()
# Changing the SIZE of the window
# + limiting the size of a window
import tkinter as tk
def click(*args):
global size, grows
if grows:
size += 50
if size >= 500:
grows = False
else:
size -= 50
if size <= 100:
grows = True
window.geometry(str(size) + "x" + str(size))
size = 100
grows = True
window = tk.Tk()
window.title('Geometry+Minsize')
####
window.minsize(width=250, height=250) # we use two keyword arguments for this
window.maxsize(width=1000, height=1000) # and this
####
window.geometry("500x500") # We use a string in format 'width x height' as a parameter for geometry()
####
window.bind("<Button-1>", click)
window.mainloop()
# Enabling and diabling resizign
import tkinter as tk
window = tk.Tk()
window.title('Resizable')
####
window.resizable(width=False, height=False) # Boolean values not integers - IMPORTANT
####
window.geometry("400x200")
window.mainloop()
# True allows the user to alter the window size along that diemension, false disables this.
####
# BINDING CALLBACKS TO THE CLOSURE OF THE MAIN WINDOW
# protocol("WM_DELETE_WINDOW", callback)
import tkinter as tk
from tkinter import messagebox
def really():
if messagebox.askyesno("?", "Wilt thou be gone?"):
window.destroy()
window = tk.Tk()
window.title('Exit - protocol()')
window.protocol("WM_DELETE_WINDOW", really)
window.mainloop()
# <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> #
# USER CONVERSATION
# There are built in methods that allow us to handle simple yes/no questions:
# one of these is:
# messagebox.askyesno(title, message, options)
# title – a string displayed in the dialog’s title bar
# message – a string displayed inside the dialog; note: the \n plays its normal role and breaks up the message’s lines;
# options – a set of options shaping the dialog in a non-default way, two of which are useful to us:
# default – sets the default (pre-focused) answer; usually, it’s focused on the button located first from the left; this can be changed
# by setting the keyword argument with identifiers like CANCEL, IGNORE, OK, NO, RETRY, and YES;
# icon – sets the non-default icon for the dialog: possible values are: ERROR, INFO, QUESTION, and WARNING.
# RETRIEVING BOOLEAN (YES/NO) ANSWERS FROM USER
import tkinter as tk
from tkinter import messagebox
def question():
answer = messagebox.askyesno("?", "YES OR NO")
print(answer)
def question2():
answer = messagebox.askokcancel("?", "OK OR CANCEL")
print(answer)
def question3():
answer = messagebox.askretrycancel("?", "RETRY OR CANCEL") # Makes os perform a 'bing' noise on messagebox opening
print(answer)
window = tk.Tk()
window.title('Return-True/False')
button = tk.Button(window, text="Ask the question! (1)", command=question)
button.pack()
button2 = tk.Button(window, text="Ask the question! (2)", command=question2)
button2.pack()
button3 = tk.Button(window, text="Ask the question! (3)", command=question3)
button3.pack()
window.mainloop()
# RETRIEVING STRING ANSWERS FROM USER
# The askquestion() function
import tkinter as tk
from tkinter import messagebox
def question():
answer = messagebox.askquestion("?", "I'm going to format your hard drive") # Return 'Yes' if user response is positive
print(answer) # Return 'No' if user response is negative
# Both of these are STRINGS
window = tk()
window.title('Returning Strings')
button = tk.Button(window, text="What are your plans?", command=question)
button.pack()
window.mainloop()
####
# The showerror() function
import tkinter as tk
from tkinter import messagebox
def question():
answer = messagebox.showerror("!", "Your code does nothing!") # Returns 'OK' string in every case
print(answer)
window = tk.Tk()
window.title('Return Errors + Warnings Strings')
button = tk.Button(window, text="Alarming message", command=question)
button.pack()
window.mainloop()
|
dbb7e09bda996ede7be312e7a9b3fa5c6b0c0af8 | LewisT543/Notes | /Learning_Tkinter/6Building-a-GUI-from-scratch.py | 2,191 | 4.03125 | 4 | import tkinter as tk
from tkinter import messagebox
def Click():
replay = messagebox.askquestion('Quit?', 'Are, you sure?')
if replay == 'yes':
window.destroy()
window = tk.Tk()
# Label
label = tk.Label(window, text = "Little label:")
label.pack()
# Frame
frame = tk.Frame(window, height=30, width=100, bg="#000099")
frame.pack()
# Button
button = tk.Button(window, text="Button", command = Click)
button.pack(fill=tk.X)
# Switch
switch = tk.IntVar()
switch.set(1)
# Switch is not visible.
# IntVar objects are set to hold integer values and controls internal communication between different widgets
# to set a value to and IntVar obj, we must use the set() method.
# Checkbutton
checkbutton = tk.Checkbutton(window, text="Check Button", variable=switch)
checkbutton.pack()
# If you check or uncheck the checkbutton, because of the variable=switch argument above, the switch will change its
# state from a 1 (checked), to a 0 (unchecked) and vice-versa.
# If you change the state of the SWITCH object, the CHECKBUTTON object would IMMEDIATELY reflect the change. This means
# we do not have to access the checkbutton object directly, we can modify the switch value instead.
# Entry
entry = tk.Entry(window, width=30)
entry.pack()
# This allows us to input small data, of width 30 chars.
# Radio Buttons
radiobutton_1 = tk.Radiobutton(window, text="Steak", variable=switch, value=0)
radiobutton_1.pack()
radiobutton_2 = tk.Radiobutton(window, text="Salad", variable=switch, value=1)
radiobutton_2.pack()
# Radiobuttons are similar to switches but work in groups, while 1 is active, the other(s) is/are not.
# ONLY ONE OF THE PAIR (OR MORE) OF RADIOBUTTONS MAY BE ACTIVE AT ONCE
# Radiobutton arguments:
# The VARIABLE argument binds a SWITCH object to both of the widgets,
# and this is the clue – the fact that both Radiobuttons are bound to
# the SAME OBJECT creates the GROUP. Don’t forget that!
# The value argument distinguishes the Radiobuttons inside the group,
# and thus each of the Radiobuttons has to use a different value (we’ve used 0 and 1)
# all pack()'ed so potentially messy.
window.mainloop() |
4e7b02140879900cbbb4e3889789c8b3dcd15291 | LewisT543/Notes | /Learning_Data_processing/3SQLite-update-delete.py | 1,440 | 4.46875 | 4 | #### SQLITE UPDATING AND DELETING ####
# UPDATING DATA #
# Each of the tasks created has its own priority, but what if we decide that one of them should be done earlier than the others.
# How can we increase its priority? We have to use the SQL statement called UPDATE.
# The UPDATE statement is used to modify existing records in the database. Its syntax is as follows:
'''
UPDATE table_name
SET column1 = value1, column2 = value2, column3 = value3, …, columnN = valueN
WHERE condition;
'''
# If we'd like to set the priority to 20 for a task with idequal to 1, we can use the following query:
'''
UPDATE tasks SET priority = 20 WHERE id = 1;
'''
# IMPORTANT NOTE: If you forget about the WHERE clause, all data in the table will be updated.
import sqlite3
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute('UPDATE tasks SET priority = ? WHERE id = ?', (20, 1))
conn.commit()
conn.close()
# DELETING DATA #
# After completing a task, we would like to remove it from our database. To do this, we must use the SQL statement called DELETE
'''
DELETE FROM table_name WHERE condition;
DELETE FROM tasks WHERE id = 1;
'''
# NOTE: If you forget about the WHERE clause, all data in the table will be deleted.
conn = sqlite3.connect('todo.db')
c = conn.cursor()
c.execute('DELETE FROM tasks WHERE id = ?', (1,)) # Tuple here? Not sure why, could be required...
conn.commit()
conn.close() |
5ba9ce856ff7469ae0283044f155c2d7213da8fb | LewisT543/Notes | /Learning_OOP/Shallow and Deep Copy/4Example-copy-speed-comparison.py | 2,783 | 4.0625 | 4 | #### SPEED COMPARISON ####
# We can see the differences in execution time very clearly.
# Single ref: no time at all,
# Shallow copy: almost no time at all,
# Deep copy: exponentially longer.
import copy
import time
a_list = [(1,2,3) for x in range(1_000_000)]
print('Single reference copy')
time_start = time.time()
b_list = a_list
print('Execution time:', round(time.time() - time_start, 3))
print('Memory chunks:', id(a_list), id(b_list))
print('Same memory chunk?', a_list is b_list)
print()
print('Shallow copy')
time_start = time.time()
b_list = a_list[:]
print('Execution time:', round(time.time() - time_start, 3))
print('Memory chunks:', id(a_list), id(b_list))
print('Same memory chunk?', a_list is b_list)
print()
print('Deep copy')
time_start = time.time()
b_list = copy.deepcopy(a_list)
print('Execution time:', round(time.time() - time_start, 3))
print('Memory chunks:', id(a_list), id(b_list))
print('Same memory chunk?', a_list is b_list)
print('\n\n\n')
# <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> #
# The same deepcopy() can be applied to dictionaries or custom class objects.
a_dict = {
'first name': 'James',
'last name': 'Bond',
'movies': ['Goldfinger (1964)', 'You Only Live Twice']
}
b_dict = copy.deepcopy(a_dict)
print('Memory chunks:', id(a_dict), id(b_dict))
print('Same memory chunk?', a_dict is b_dict)
print("Let's modify the movies list")
a_dict['movies'].append('Diamonds Are Forever (1971)')
print('a_dict movies:', a_dict['movies'])
print('b_dict movies:', b_dict['movies'])
# Because we deep copied this, we are able to change one instance of the list and not the other.
print('\n\n\n')
# <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> #
# In this example we see that a deepcopy does not run the __init__() method of the copy object. We only see one
# __init__() execution dispite the fact we have 2 Example objects.
class Example:
def __init__(self):
self.properties = ["112", "997"]
print("Hello from __init__()")
a_example = Example()
b_example = copy.deepcopy(a_example)
print("Memory chunks:", id(a_example), id(b_example))
print("Same memory chunk?", a_example is b_example)
print()
print("Let's modify the movies list")
b_example.properties.append("911")
print('a_example.properties:', a_example.properties)
print('b_example.properties:', b_example.properties)
# output:
# Hello from __init__() <<<<< ONLY ONE INIT
# Memory chunks: 2260624417792 2260626205088
# Same memory chunk? False
# Let's modify the movies list
# a_example.properties: ['112', '997']
# b_example.properties: ['112', '997', '911'] |
77a3de5d9a5a2fea41962f745456533430eca80f | LewisT543/Notes | /Learning_Data_processing/11Labs-exams-report.py | 2,704 | 3.78125 | 4 |
# Your task will be to prepare a report summarizing the results of exams in maths, physics and biology.
# The report should include the name of the exam, the number of candidates, the number of passed exams, the number of failed exams,
# and the best and the worst scores. All the data necessary to create the report is in the exam_results.csv file.
# Note that one candidate may have several results for the same exam. The number of candidates should express the number of unique
# people in each exam identified by Candidate ID. The final report should look like this:
'''
Exam Name,Number of Candidates,Number of Passed Exams,Number of Failed Exams,Best Score,Worst Score
Maths,8,4,6,90,33
Physics,3,0,3,66,50
Biology,5,2,3,88,23
'''
import csv
import pandas as pd
class MakeReport:
def __init__(self):
self.csvfile = 'exam_results.csv'
self.header_names = ['Exam Name', 'Number of Candidates', 'Number of Passed Exams',
'Number of Failed Exams', 'Best Score', 'Worst Score']
def read_results_csv(self):
self.current_dataframe = pd.read_csv(self.csvfile)
print(self.current_dataframe)
def prepare_report(self):
self.read_results_csv()
self.new_df = pd.DataFrame(columns=self.header_names)
exam_names = self.current_dataframe.Exam_Name.unique()
for exam in exam_names:
participants = [] # Currently contains dupes
passes, fails = 0, 0
scores = []
for ind in self.current_dataframe.index:
if self.current_dataframe.Exam_Name[ind] == exam:
participants.append(self.current_dataframe.Candidate_ID[ind])
scores.append(self.current_dataframe.Score[ind])
if self.current_dataframe.Grade[ind] == 'Pass':
passes += 1
elif self.current_dataframe.Grade[ind] == 'Fail':
fails += 1
num_students = list(dict.fromkeys(participants)) # drop dupes from participants list
highest, lowest = max(scores), min(scores)
data_struct = {'Exam Name': exam, 'Number of Candidates': len(num_students), 'Number of Passed Exams': passes,
'Number of Failed Exams': fails, 'Best Score': highest, 'Worst Score': lowest}
self.new_df = self.new_df.append(data_struct, ignore_index=True)
def write_new_report(self):
self.new_df.to_csv('exam_results_report.csv', index=False)
my_reader = MakeReport()
my_reader.prepare_report()
my_reader.write_new_report() |
2c191da1dddc35a17485a3519f63c0a2dd879dd0 | LewisT543/Notes | /Learning_OOP/Decorators/Timer.py | 1,026 | 3.59375 | 4 | from functools import wraps
class Logging_decorator(object):
def __init__(self, origional_function):
self.origional_function = origional_function
def __call__(self, *args, **kwargs):
import logging
logging.basicConfig(filename=f'{self.origional_function.__name__}.log', level=logging.INFO)
logging.info(f'Program: {self.origional_function.__name__}. Ran with args: {args}, and kwargs: {kwargs}. ')
return self.origional_function(*args, **kwargs)
class Timer_decorator(object):
def __init__(self, origional_function):
self.origional_function = origional_function
def __call__(self, *args, **kwargs):
import time
t1 = time.time()
result = self.origional_function(*args, **kwargs)
t2 = time.time() - t1
print(f'{self.origional_function.__name__} ran in {t2} sec')
@Logging_decorator
@Timer_decorator
def display2(name, age):
print(f'Your name is {name}, your age is {age}')
display2('Jeff', 21) |
95ce1eb58837658a9f65247e7c3c84548644ebe0 | ahovhannes/Disco_API_Test | /Source/TestFunctions/FunctionRandom/Function_Random.py | 613 | 3.671875 | 4 | #
# Collection of functions generating random numbers
#
import random
class bddRandom:
def generate_random_number(self, beginNumber, endNumber, seedValue=None):
"""
Generate random number between given numbers
Args:
beginNumber : Start number
endNumber : End number
seedValue : Optional seed value
Returns:
Generated random number
"""
n = None
if seedValue:
random.seed(seedValue)
n = random.randint(beginNumber, endNumber)
return n
|
2f69fc3c07f2bdd21293db493df9e25ef1f7978a | adambjorgvins/pricelist | /snake.py | 2,389 | 3.890625 | 4 | import random
class Game:
dimension = None
board = None
current_x = None
current_y = None
monster = None
snake = None
brick = None
score = None
def __init__(self, dimension):
self.current_x = random.randint(0,9)
self.current_y = random.randint(0,9)
self.current_monster_x = random.randint(0,9)
self.current_monster_y = random.randint(0,9)
self.dimension = dimension
self.score = 0
self.brick = "\33[;31m'\33[;0m"
self.snake = "\33[;32mO\33[;0m"
self.monster = "@"
self.board = []
for x in range(dimension):
line = []
for y in range(dimension):
line.append(self.brick)
self.board.append(line)
self.board[self.current_y][self.current_x] = self.snake
self.move_monster()
def draw(self):
print(self)
def move_monster(self):
self.current_monster_y = random.randint(0,9)
self.current_monster_x = random.randint(0,9)
self.board[self.current_monster_y][self.current_monster_x] = self.monster
def move_snake(self, direction):
left = "a"
down = "s"
right = "d"
up = "w"
self.board[self.current_y][self.current_x] = self.brick
if direction == left:
self.current_x -= 1
if direction == right:
self.current_x += 1
if direction == down:
self.current_y += 1
if direction == up:
self.current_y -= 1
# never more then dimension
self.current_x = min(self.current_x, self.dimension-1)
self.current_y = min(self.current_y, self.dimension-1)
# never less then 0
self.current_x = max(self.current_x, 0)
self.current_y = max(self.current_y, 0)
# get what is where the snake should be placed
current_thing = self.board[self.current_y][self.current_x]
# check if there is a monster there
if current_thing == self.monster:
self.move_monster()
self.score += 1
# place the snake
self.board[self.current_y][self.current_x] = self.snake
def __str__(self):
result = "\nSCORE : {}\n\n".format(self.score)
for line in self.board:
for x in line:
result += "| {} ".format(x)
result += "\n"
return result
def main():
some_game = Game(10)
some_game.draw()
inp = input("Enter asdw ")
while inp != "q":
some_game.move_snake(inp)
some_game.draw()
inp = input("Enter asdw ")
main()
|
b99087927611afb1de15d89e863cc7ad162abf7e | velios/6_password_strength | /password_strength.py | 2,341 | 3.59375 | 4 | import re
from string import (ascii_lowercase,
ascii_uppercase,
punctuation,
digits)
from getpass import getpass
from os import path
def check_upper_and_lower_case_in_string(string):
return any(char in string for char in ascii_uppercase) and \
any(char in string for char in ascii_lowercase)
def check_digits_in_string(string):
return any(char in string for char in digits)
def check_punctuation_in_string(string):
return any(char in string for char in punctuation)
def check_10k_most_common_passwords_equal_string(string):
check_file = '10k_most_common.txt'
if not path.exists(check_file):
return None
with open(check_file, 'r') as bad_passwords_file:
return any(word.rstrip('\n') == string for word in bad_passwords_file)
def check_string_length(string, min_length=5):
return len(string) > min_length
def check_no_regexp_in_string(string):
regexp_checks = {
'iso_data': re.compile(r'[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])'),
'email': re.compile(r'^[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}$'),
'domain_name': re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$')
}
return all([re.match(check, string) is None for check in regexp_checks.values()])
def get_password_strength(password):
checks = [check_upper_and_lower_case_in_string,
check_digits_in_string,
check_punctuation_in_string,
check_string_length,
check_no_regexp_in_string]
check_results_list = [check_func(password) for check_func in checks]
positive_check_count = check_results_list.count(True)
all_check_count = sum([check_results_list.count(True), check_results_list.count(False)])
min_password_strength = 1
max_password_strength = 9
calculated_password_strength = min_password_strength + int(round(positive_check_count / all_check_count * max_password_strength))
return min_password_strength if check_10k_most_common_passwords_equal_string(password) \
else calculated_password_strength
if __name__ == '__main__':
password = getpass('Enter the password and I will analyze its strength: ')
print('Strong of your password {} of 10'.format(get_password_strength(password)))
|
9c64a4aab34c6af4b71fc4162f6ea30d7b74bc2f | iceman67/algorithm | /02-analysis/search/linsear_search.py | 923 | 3.75 | 4 | def linearSearch(arr, key):
n = len(arr)
for i in range(0, n):
if arr[i] == key:
return i
return -1
list = [1,2,3,4,5]
key = 2
pos = linearSearch(list, key)
print ("position = ", pos )
if pos == -1:
print("not found" )
else:
print (" ", list[pos])
key = -1
pos = linearSearch(list, key)
print ("position = ", pos )
if pos == -1:
print(" not found" )
else:
print ( list[pos])
if __name__ == '__main__':
import timeit
import random
t1 = timeit.Timer("list=range(100000); k = random.randint(1,100000); key=k; linearSearch(list,key)", "from __main__ import linearSearch, random")
print("linear search ran:", t1.timeit(number=100), "milliseconds")
t1 = timeit.Timer("list=range(1000000); k = random.randint(1,1000000); key=k; linearSearch(list,key)", "from __main__ import linearSearch, random")
print("linear search ran:", t1.timeit(number=100), "milliseconds")
|
1827787e352eccbf15888adb66acdafee51cfdec | davidsamuelwhite/visualnba | /JSONGameData.py | 3,431 | 3.859375 | 4 | # this file contains functions that manipulate the data from the JSON file which
# holds all the data that is plotted by the program. it creates objects called
# dataframes from the pandas packages, which are essentially 2d lists that are
# easier to data manipulation with.
import json
import pandas as pd
# disables warnings from pandas package. cleans the console
pd.options.mode.chained_assignment = None
# load data from a JSON file
def loadData(file):
JSON = open(file)
return json.load(JSON)
# get the info about the players in a game, and create a dataframe
def getPlayerInfo(JSON):
# row headers
playerColumns = JSON["events"][0]["home"]["players"][0].keys()
# home, then away team info
homePlayers = pd.DataFrame(data = [home for home in \
JSON["events"][0]["home"]["players"]], columns = playerColumns)
visitingPlayers = pd.DataFrame(data = [visitor for visitor in \
JSON["events"][0]["visitor"]["players"]], columns = playerColumns)
# rename and add some columns
homePlayers.rename(columns = {'playerid':'playerID'}, inplace = True)
visitingPlayers.rename(columns = {'playerid':'playerID'}, inplace = True)
homePlayers['team'] = JSON["events"][0]['home']['name']
visitingPlayers['team'] = JSON["events"][0]['visitor']['name']
# merge together
df = pd.merge(visitingPlayers, homePlayers, how='outer')
# delete for memory conservation
del homePlayers
del visitingPlayers
df = df.drop(columns = ['position'])
return df
# create a dataframe of the movement data of a whole game
# output will be roughly 2,000,000 rows
def getMovementInfo(JSON):
final = []
# hierarchy of info: JSON --> events --> moments
for event in JSON['events']:
eventID = event['eventId']
for moment in event['moments']:
# moment[5] is a 11x5 matrix of movement info for all 10 players
# on the court along with the ball
for entity in moment[5]:
entity.extend((eventID, moment[0], moment[2], moment[3]))
final.append(entity)
columns = ["teamID", "playerID", "x", "y", "radius", "eventID", "period", \
"gameClock", "shotClock"]
df = pd.DataFrame(final, columns = columns)
# delete the list and some columns to save memoery
del final
df = df.drop(columns = ['teamID', 'radius'])
return df
# merge the player data to each row of movement so we know who exactly is moving
def mergePlayerAndMovement(df, players):
# we create an index to sort by because the original order of the movement
# data is important and needs to be preserved. merging by default loses
# the order
df['index'] = range(len(df))
df = pd.merge(df, players, how = 'outer')
df = df.sort_values('index')
df = df.reset_index(drop=True)
return df
# takes the raw JSON data and creates a tidy dataframe for plotting
def createDF(JSON):
players = getPlayerInfo(JSON)
movement = getMovementInfo(JSON)
df = mergePlayerAndMovement(movement, players)
df.shotClock = df.shotClock.fillna('')
del players
del movement
return df
# subset the tidy movement dataframe by a specific event we wish to plot
def subsetMovements(df, eventNum):
newDF = df[df.eventID == str(eventNum)]
newDF = newDF.reset_index(drop=True)
return newDF |
8a57681c6bd62de888d89661572c134906752f24 | mihai064/my-projects | /python/hello.py | 1,134 | 3.96875 | 4 | import time
print("hello")
var1 = input("what's your name? ")
print("nice to meet you",var1)
user_reply = input("do you wanna play something? ")
if user_reply == "yes":
ur2 = input("greatfull. so do you like programmig? ")
if ur2 == "yes":
print ("let's learn python")
user_reply2 = input ("do you want to try to make a calculator? ")
if user_reply2 == "yes":
a = input("a=")
b = input("b=")
ur3 = input ("what do you wanna do with this?")
if ur3 == "+":
print(int(a) + int(b))
if ur3 == "-":
print(int(a) - int(b))
if ur3 == "*":
print(int(a) * int(b))
if ur3 == "/":
print(int(a) / int(b))
if user_reply2 == "no":
print ("let's make a timer then")
timer_timer = input ("how many seconds?")
s=1
while int(s) < int(timer_timer):
print (s)
s=s+1
time.sleep(1.0)
if int(s) == int(timer_timer) / 2:
print("that's half")
else:
print ("timer out")
else:
print ("ok. bye then.") |
443ba59840b6aa72447c04f6e9d2dccdf9429df7 | mihai064/my-projects | /python/buton.py | 529 | 3.8125 | 4 | import tkinter
window = tkinter.Tk()
button = tkinter.Button(window, text="Do not press this button.",width=40)
button.pack (padx=10, pady=10)
clickCount = 0
def onClick (event):
global clickCount
clickCount = clickCount + 1
if clickCount == 1:
button.configure (text="Seriously? Do. Not. Press. It.")
elif clickCount == 2:
button.configure (text="Gah! Next time, no more button.")
else:
button.pack_forget()
button.bind("<ButtonRelease-1>", onClick)
window.mainloop()
|
509be7160806b00c6f34042fbe3e5f3e6308b082 | prahaladh/webscrape | /webscrape.py | 555 | 3.53125 | 4 | import pandas as pd
import requests
from bs4 import BeautifulSoup
def get_data(url):
res = requests.get(url)
soup = BeautifulSoup(res.content,'lxml')
table = soup.find_all('table')[0]
list_of_rows = []
for row in table.findAll('tr'):
list_of_cells = []
for cell in row.findAll(["th","td"]):
text = cell.text
list_of_cells.append(text)
list_of_rows.append(list_of_cells)
print(list_of_rows)
url="https://www.w3schools.com/html/tryit.asp?filename=tryhtml_tables2"
get_data(url)
|
c7eb2f952f6ceadba48a40220ed18ec0b103b386 | pcw109550/id0-rsa.pub | /32_Caesar/solve.py | 404 | 3.515625 | 4 | #!/usr/bin/env python3
import string
chset = string.ascii_uppercase
N = len(chset)
f = open("ct", "r")
ct = f.read().strip()
f.close()
for i in range(N):
pt = ""
for c in ct:
x = chset.find(c)
pt += chset[(x + i) % N]
if "CAESAR" in pt:
print("KEY: {:s}".format(chset[i]))
break
assert(len(ct) == len(pt))
print("PT: {:s}".format(pt))
sol = "VAJDUXFCPV"
|
ee7040b673ccc088d8e708f017a5dd17e203e6c6 | pcw109550/id0-rsa.pub | /38_Easy_Passwords/solve.py | 1,512 | 3.5 | 4 | #!/usr/bin/env python
from passlib.hash import md5_crypt
from itertools import product
from string import ascii_lowercase
def hash(salt, msg):
h = md5_crypt.using(salt=salt, salt_size=8)
return h.hash(msg)
def step1(salt, res, datas):
# https://www.scrapmaker.com/data/wordlists/dictionaries/rockyou.txt
f = open("rockyou.txt", "r")
while True:
m = f.readline().strip('\x0a')
h = hash(salt, m)[12:]
if h in datas:
for i in range(len(datas)):
if datas[i] == h:
res[i] = m
print(m)
print(res)
f.close()
return res
def step2(salt, res, datas):
for n in range(2, 5):
for m in product(list(ascii_lowercase), repeat=n):
m = "".join(m)
h = hash(salt, m)[12:]
if h in datas:
for i in range(len(datas)):
if datas[i] == h:
res[i] = m
print(m)
print(res)
return res
f = open("data", "r")
data = f.read()
f.close()
datas = data.split("\n")[:-1]
salt = [d.split('$')[2:] for d in datas][0][0]
datas = [d.split('$')[-1] for d in datas]
res = [""] * len(datas)
# res = step1(salt, res, datas)
res = ["the", "second", "letter", "", "each", "word", "", "this", "", "", "order"]
# res = step2(salt, res, datas)
res = ["the", "second", "letter", "of", "each", "word", "in", "this", "list", "in", "order"]
res = "".join([c[1] for c in res])
print(res)
|
d530548acdd3fb83f6302d73ae83597fc38fc4f8 | Woltan/Chess | /board.py | 4,472 | 3.5625 | 4 | import random
from pieces import Pawn, Rook, Knight, King, Bishop, Queen
class Board(object):
Pieces = property(lambda self: self._pieces)
def __init__(self, pieces, turn):
self._pieces = pieces
self._turn = turn
self._lastMove = None
@classmethod
def CreateNewBoard(cls, fen=None):
if fen:
raise NotImplementedError()
else:
pieces = [Pawn((i, 1), "white") for i in range(8)] + [Pawn((i, 6), "black") for i in range(8)]
pieces.extend([Rook((0, 0), "white"), Rook((7, 0), "white"), Rook((0, 7), "black"), Rook((7, 7), "black")])
pieces.extend([Knight((1, 0), "white"), Knight((6, 0), "white"), Knight((1, 7), "black"), Knight((6, 7), "black")])
pieces.extend([Bishop((2, 0), "white"), Bishop((5, 0), "white"), Bishop((2, 7), "black"), Bishop((5, 7), "black")])
pieces.extend([King((4, 0), "white"), King((4, 7), "black")])
pieces.extend([Queen((3, 0), "white"), Queen((3, 7), "black")])
return cls(pieces, "white")
def Move(self):
possibleMoves = [(piece, newPos) for piece in self._pieces if piece.Color == self._turn for newPos in piece.GetPossibleMoves(self, None)]
piece, newPos = random.choice(possibleMoves)
removePiece = self.GetPiece(newPos)
if removePiece:
self._pieces.remove(removePiece)
prevPos = piece.HumanPos
piece.Move(newPos)
print("{}: {} -> {} (Pieces: {}, {})".format(piece.Abbreviation, prevPos, piece.HumanPos, len(self.GetPieces("white")), len(self.GetPieces("black"))))
self._turn = "white" if self._turn == "black" else "black"
def GetPiece(self, position):
for piece in self._pieces:
if piece.Pos == position:
return piece
else:
return None
def GetPieces(self, colors=None, positions=None, pieces=None):
filteredPieces = self._pieces
if colors is not None:
filteredPieces = [p for p in filteredPieces if p.Color in colors]
if positions is not None:
filteredPieces = [p for p in filteredPieces if p.Pos in positions]
if pieces is not None:
filteredPieces = [p for p in filteredPieces if p.__class__ in pieces]
return filteredPieces
def ExportFEN(self):
fen = ""
for i in range(7, -1, -1):
z = 0
for j in range(8):
piece = self.GetPiece((j, i))
if piece:
if z != 0:
fen += str(z)
fen += piece.Abbreviation if piece.Color == "white" else piece.Abbreviation.lower()
z = 0
else:
z += 1
else:
if z != 0:
fen += str(z)
if i > 0:
fen += "/"
fen += " {} ".format(self._turn[0])
# if self.GetPieces(["white"], pieces=["King"])[0].Moved:
# fen += "-"
# else:
# rook = self.GetPieces(["white"], (0, 0), ["Rook"])
# if rook and rook[0].Moved:
# fen += "-"
# else:
# fen += "Q"
#
# rook = self.GetPieces(["white"], (7, 0), ["Rook"])
# if rook and rook[0].Moved:
# fen += "-"
# else:
# fen += "K"
#
#
# if self.GetPieces(["black"], pieces=["King"])[0].Moved:
# fen += "-"
# else:
# pass
return fen
def Print(self):
board = "_" * 8 + "\n"
for i in range(7, -1, -1):
for j in range(8):
piece = self.GetPiece((j, i))
if piece:
board += piece.Abbreviation if piece.Color == "white" else piece.Abbreviation.lower()
else:
board += " "
board += "\n"
board += "-" * 8 + "\n"
print(board)
def printBoard(self):
print()
print(' ________ ________ ________ ________ ________ ________ ________ ________')
for a in range(7, -1, -1):
if (a) % 2 == 0:
print(' | | ---- | | ---- | | ---- | | ---- |')
else :
print(' | ---- | | ---- | | ---- | | ---- | |')
print( a, ' ', end = '')
for b in range (8):
piece = self.GetPiece((b, a))
if (a + b) % 2 == 0:
if not piece : print ('| ', end = '')
elif piece.Color == "white":print (piece.AbbreviationLong, end = '')
else:print (piece.AbbreviationLong.lower(), end = '')
else :
if not piece: print('| ---- ', end='')
elif piece.Color == "white": print (piece.AbbreviationLongColored, end = '')
else: print (piece.AbbreviationLongColored.lower(), end = '')
print('|')
if (a) % 2 == 0:
print(' |________|__----__|________|__----__|________|__----__|________|__----__|')
else :
print(' |__----__|________|__----__|________|__----__|________|__----__|________|')
print()
print(' a b c d e f g h ')
print() |
7b8414a39ff9a45806152126d9bd2bc12d1cd54a | satlawa/ucy_dsa_projects | /Project_1/problem_6.py | 4,138 | 4.1875 | 4 | #------------------------------------------------------#
# problem 6 - Union and Intersection
#------------------------------------------------------#
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
def __repr__(self):
cur_head = self.head
pointer_string = ""
while cur_head:
pointer_string += str(cur_head.value) + " -> "
cur_head = cur_head.next
return pointer_string
def append(self, value):
""" Add a Node to the end of the linked list """
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def size(self):
""" Calculate the size of the link list """
size = 0
node = self.head
while node:
size += 1
node = node.next
return size
def to_set(self):
""" Transforms the linked list content into a list """
out = set()
node = self.head
while node:
out.add(node.value)
node = node.next
return out
def union(llist_1, llist_2):
""" Calculate the union of two linked lists """
# convert linked lists to sets
set_1 = llist_1.to_set()
set_2 = llist_2.to_set()
# preform union on sets
set_union = set_1 | set_2
# create a linked list out of the union of sets
llist_union = LinkedList()
for item in set_union:
llist_union.append(item)
return llist_union
def intersection(llist_1, llist_2):
""" Calculate the intersection of two linked lists """
# convert linked lists to sets
set_1 = llist_1.to_set()
set_2 = llist_2.to_set()
# preform intersection on sets
set_intersection = set_1 & set_2
# create a linked list out of the intersection of sets
llist_intersection = LinkedList()
for item in set_intersection:
llist_intersection.append(item)
return llist_intersection
# Standard test cases
#---------------------------------------------------
# Test case 1
#---------------------------------------------------
linked_list_1 = LinkedList()
linked_list_2 = LinkedList()
element_1 = [3,2,4,35,6,65,6,4,3,21]
element_2 = [6,32,4,9,6,1,11,21,1]
for i in element_1:
linked_list_1.append(i)
for i in element_2:
linked_list_2.append(i)
print (union(linked_list_1,linked_list_2))
# 32 -> 65 -> 2 -> 35 -> 3 -> 4 -> 6 -> 1 -> 9 -> 11 -> 21 ->
print (intersection(linked_list_1,linked_list_2))
# 4 -> 21 -> 6 ->
#---------------------------------------------------
# Test case 2
#---------------------------------------------------
linked_list_3 = LinkedList()
linked_list_4 = LinkedList()
element_1 = [3,2,4,35,6,65,6,4,3,23]
element_2 = [1,7,8,9,11,21,1]
for i in element_1:
linked_list_3.append(i)
for i in element_2:
linked_list_4.append(i)
print (union(linked_list_3,linked_list_4))
# 65 -> 2 -> 35 -> 3 -> 4 -> 6 -> 1 -> 7 -> 8 -> 9 -> 11 -> 21 -> 23 ->
print (intersection(linked_list_3,linked_list_4))
#
# Edge test cases
#---------------------------------------------------
# Test case 3
#---------------------------------------------------
linked_list_5 = LinkedList()
linked_list_6 = LinkedList()
element_1 = []
element_2 = []
for i in element_1:
linked_list_5.append(i)
for i in element_2:
linked_list_6.append(i)
print (union(linked_list_5,linked_list_6))
#
print (intersection(linked_list_5,linked_list_6))
#
#---------------------------------------------------
# Test case 4
#---------------------------------------------------
linked_list_7 = LinkedList()
linked_list_8 = LinkedList()
element_1 = []
element_2 = [9,7,8,9,1,28,6,66]
for i in element_1:
linked_list_7.append(i)
for i in element_2:
linked_list_8.append(i)
print (union(linked_list_7,linked_list_8))
# 1 -> 66 -> 6 -> 7 -> 8 -> 9 -> 28 ->
print (intersection(linked_list_7,linked_list_8))
#
|
100a33b667fa60386fabf26718b7bdf71d25d26c | satlawa/ucy_dsa_projects | /Project_0/Task2.py | 1,759 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
def get_tel_num_max_time(calls):
"""
Function for finding the telephone number that spent the longest time on the phone.
Args:
calls(list): list containing call records
Return:
max_len(tuple): tuple containing the telephone number and the time spend on
the phone from the telephone number that spent the longest time on the phone.
"""
# dictionary for keeping track of the time of every tel number
tel_nums = {}
# loop all records
for record in calls:
# loop both columns
for i in range(2):
# if key already exists summ values
if record[i] in tel_nums:
tel_nums[record[i]] += int(record[3])
# key does not exist create key with value
else:
tel_nums[record[i]] = int(record[3])
# find tel number with max length
max_len = ("0",0)
for tel_num, length in tel_nums.items():
if length > max_len[1]:
max_len = (tel_num, length)
return max_len
tel_num, lenght = get_tel_num_max_time(calls)
print("{} spent the longest time, {} seconds, on the phone during September 2016."\
.format(tel_num, lenght))
|
89309e6aa3917fee2427a1e16113a3de202994d5 | achmielecki/AI_Project | /agent/agent.py | 2,136 | 4.25 | 4 | """
File including Agent class which
implementing methods of moving around,
making decisions, storing the history of decisions.
"""
class Agent(object):
""" Class representing agent in game world.
Agent has to reach to destination point
in the shortest distance. World is random generated. """
def __init__(self):
""" Initialize the Agent """
self.__history = []
self.__x = -1
self.__y = -1
self.__destination_x = -1
self.__destination_y = -1
# ---------
# TO DO
# ---------
def make_decision(self):
""" make decision where agent have to go """
pass
# ---------
# TO DO
# ---------
def move(self, way: int):
""" Move the agent in a given direction """
pass
def add_to_history(self, env_vector: list[int], decision: int):
""" Add new pair of environment vector and decision to history """
self.__history.append((env_vector, decision))
def __str__(self):
""" define how agent should be shown as string """
string_agent = "{"
string_agent += "position: (" + str(self.__x) + ", " + str(self.__y) + ")"
string_agent += " | "
string_agent += "destination: (" + str(self.__destination_x) + ", " + str(self.__destination_y) + ")"
string_agent += "}"
return string_agent
def set_position(self, x: int, y: int):
""" Set new agent position """
self.__x = x
self.__y = y
def clear_history(self):
""" clear agent history """
self.__history.clear()
def get_history(self):
""" Return agent history """
return self.__history
def get_position(self):
""" Return agent position as a tuple (x, y) """
return self.__x, self.__y
if __name__ == '__main__':
agent = Agent()
print(agent)
agent.add_to_history([1, 0, 0, 1, 0, 1], 5)
agent.add_to_history([1, 0, 2, 3, 5, 6], 5)
agent.add_to_history([1, 1, 0, 3, 6, 5], 5)
print(agent.get_history())
agent.clear_history()
print(agent.get_history())
|
b1e4492ff80874eeada53f05d6158fc3ce419297 | lovepurple/leecode | /first_bad_version.py | 1,574 | 4.1875 | 4 | """
278. 2018-8-16 18:15:47
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Example:
Given n = 5, and version = 4 is the first bad version.
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
同样是二分法 这个例子带边界值
"""
def isBadVersion(version):
return True if version >= 6 else False
class first_bad_version:
def firstBadVersion(self, n):
return self.findBadVersion(0, n)
def findBadVersion(self, left, right):
if right - left == 1:
if not isBadVersion(left) and isBadVersion(right):
return right
else:
middleVersion = (right + left) // 2
if isBadVersion(middleVersion):
return self.findBadVersion(left, middleVersion)
else:
return self.findBadVersion(middleVersion, right)
instance = first_bad_version()
print(instance.firstBadVersion(7)) |
1c84d570d09e47bf4e8e5404c637724605941471 | lovepurple/leecode | /binarySearch.py | 904 | 3.921875 | 4 | """
Given a sorted (in ascending order) integer array nums of n elements and a target value,
write a function to search target in nums.
If target exists, then return its index, otherwise return -1.
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
"""
class BinarySearch:
def search(self, nums, target):
index = len(nums) // 2
compareNum = nums[index]
while compareNum != target:
if compareNum > target:
index = (index - 1) // 2
else:
index = index + (len(nums) - index) // 2
compareNum = nums[index]
return index
search = BinarySearch()
index = search.search([-1, 0, 3, 5, 9, 12], 3)
print(index)
|
309d38b353e45b90da17d15b021b83ab43c80b1e | lovepurple/leecode | /contains_duplicate.py | 1,127 | 3.890625 | 4 | """
217. Contains Duplicate 2018-8-8 0:05:01
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
"""
class contains_duplicate:
def containsDuplicate(self, nums):
# 冒泡排序的时间复杂度太大
"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return True
return False
"""
# 借助set数据结构,非常巧妙,set 本身就会去重复,但如果使用C 使用基础语言没有set的情况下,利用排序思想(快排)
if len( set(nums)) == len(nums):
return False
return True
instance = contains_duplicate()
nums = [1, 1, 1, 3, 3, 4, 3, 2, 2, 4, 2]
print(instance.containsDuplicate(nums))
|
a1c12b3b59535fe7e82558ffe416e6cba5dbb1f6 | ravi4all/Oct_AdvPythonMorningReg | /01-OOPS/02-ObjDemo.py | 527 | 4 | 4 | class Emp:
"""This is my first class demo"""
id = 1
name = "Ram"
print("Hello world")
if __name__ == '__main__':
obj_1 = Emp()
# print(ram)
print(obj_1.id, obj_1.name)
obj_1.name = 'Shyam'
print(obj_1.name)
print(Emp.name)
obj_2 = Emp()
obj_2.name = 'Ram'
obj_2.id = 2
print(obj_2.id, obj_2.name)
print("Id before changing...",Emp.id)
Emp.id = 5
print("Id after change",Emp.id)
obj_3 = Emp()
print(obj_3.id, obj_3.name)
|
da39acfbccae16f554fc22a7e9d21300a1fac7f2 | ravi4all/Oct_AdvPythonMorningReg | /02-Inheritance/03-MultipleInheritance.py | 1,255 | 3.90625 | 4 | class Emp:
def __init__(self):
self.name = ""
self.age = 0
self.salary = 0
self.company = "HCL"
def printEmp(self):
print("Emp Details :",self.name, self.age, self.salary, self.company)
class Bank:
def __init__(self,balance,eligible):
self.balance = balance
self.eligible = eligible
self.bank = "HDFC"
def checkEligibility(self):
print("Welcome to {} bank".format(self.bank))
if self.eligible:
print("Your balance is {} You will get the loan".format(self.balance))
else:
print("You are not eligible because your balance is {}".format(self.balance))
class Emp_1(Emp, Bank):
def __init__(self, name,age,salary):
Emp.__init__(self)
self.name = name
self.age = age
self.salary = salary
def checkBalance(self):
if self.salary > 15000:
self.eligible = True
Bank.__init__(self, self.salary, self.eligible)
else:
self.eligible = False
Bank.__init__(self, self.salary, self.eligible)
ram = Emp_1("Ram", 20,19000)
ram.printEmp()
ram.checkBalance()
ram.checkEligibility()
|
03b65050e19e551c68bb94c17e6712357db67c09 | GuillemMartinezArdanuy/Becas-Digitaliza--PUE--Programaci-n-de-Redes | /Python/06_for.py | 1,033 | 3.90625 | 4 | #Crear un archivo llamado 06_for.py
#Crear una lista con nombres de persona e incluir, como mínimo, 5 nombres (como mínimo, uno ha de tener la vocal "a")
listaNombres=["Antonio","Manuel","Jose","Manuela","Antonia","Pepita","Carol","Ivan","Guillem","Alberto","Luis"]
#Crear una lista llamada "selected"
selected=[]
#Recorrer, mediante un for, la lista de los nombres e imprimir un texto con el nombre recorrido en dicha iterración.
#Asimismo, si el nombre de esa iteración contine una "a", añadirlo a la lista llamada "selected"
for nombre in listaNombres:
print(nombre)
if 'a' in nombre:
selected.append(nombre)
print("----FIN DE LA LISTA----\n")
#Finalmente, imprimir por pantalla la lista "selected"
print("imprimimos el valor de la lista SELECTED: ")
print(selected,"\n")
print("imprimimos el valor de la lista SELECTED (mostrando el valor uno por uno, es mas elegante (al menos para mi))")
for nombre in selected:
print(nombre)
#Subir el archivo a vuestra cuenta de GitHub |
be16fc36b1664629aed50ab10065ee94ad2858f1 | stefan9x/pa | /vezba01/z3.py | 370 | 3.8125 | 4 | #Napiši program koji na ulazu prima dva stringa i na osnovu njih formira
# i ispisuje novi string koji se sastoji od dva puta ponovljena prva tri
# karaktera iz prvog stringa i poslednja tri karaktera drugog stringa
if __name__ == "__main__":
s = input('Unesite dva stringa:')
s1, s2 = s.split(' ')
s_out = s1[0:3]+s1[0:3]+s2[-3:]
print(s_out)
|
4425e49cff1337a3691b647d5d7752bd451fad87 | stefan9x/pa | /vezba01/z2.py | 441 | 3.59375 | 4 | #Napisati funkciju koja računa zbir kvadrata prvih N prirodnih brojeva
#parametar N se unosi kao ulazni argument programa;
import sys
def zbir2_n(n):
zbir = 0
for i in range(n):
zbir+=i**2
zbir+=n**2
return zbir
if __name__ == "__main__":
if len(sys.argv) < 2:
print('Unesite N kao argument')
else:
sum = zbir2_n(int(sys.argv[1]))
print('Zbir kvadrata prvih N brojeva:', sum) |
5f54615d6649e495f45e630ba3c7d690e94c308a | AbelHristodor/ideas | /Games/Tris aka TicTacToe.py | 3,848 | 3.71875 | 4 | import time
player1 = 0
player2 = 0
answer = input("Ciao, vuoi giocare a Tris? Si/No ")
if answer == 'Si':
player1 = input("Giocatore 1, vuoi essere X oppure 0? ")
if player1 == 'X':
player2 = '0'
else:
player2 = 'X'
else:
print("Vabbè giocheremo un'altra volta.")
def display_board(board2):
print(' ' + board2[1] + ' | ' + board2[2] + ' | ' + board2[3] + ' ')
print("-----!-----!-----")
print(' ' + board2[4] + ' | ' + board2[5] + ' | ' + board2[6] + ' ')
print("-----!-----!-----")
print(' ' + board2[7] + ' | ' + board2[8] + ' | ' + board2[9] + ' ')
def player_choice(board, sign, n_player):
pos = int(input(f"Giocatore{n_player}, scegli un numero: "))
print("\n")
board[pos] = sign
return display_board(board)
def instructions():
print("\n\n")
print("Allora il gioco funzionerà cosi:")
print("Ogni casella corrisponderà al numero del numpad al contrario da 1(alto-sinistra) a 9 (basso-destra)")
print("Il numero scelto corrisponde a tale casella.")
def switcher(board, player_n1):
sign = player_n1
if board[1] == sign and board[2] == sign and board[3] == sign:
if player_n1 == 'X':
print(f"\nIl giocatore" + str(1) + " ha vinto!")
else:
print(f"\nIl giocatore" + str(2) + " ha vinto!")
elif board[4] == 'X' and board[5] == 'X' and board[6] == sign:
if player_n1 == 'X':
print(f"\nIl giocatore" + str(1) + " ha vinto!")
else:
print(f"\nIl giocatore" + str(2) + " ha vinto!")
elif board[7] == 'X' and board[8] == 'X' and board[9] == sign:
if player_n1 == 'X':
print(f"\nIl giocatore" + str(1) + " ha vinto!")
else:
print(f"\nIl giocatore" + str(2) + " ha vinto!")
elif board[1] == sign and board[5] == sign and board[9] == sign:
if player_n1 == 'X':
print(f"\nIl giocatore" + str(1) + " ha vinto!")
else:
print(f"\nIl giocatore" + str(2) + " ha vinto!")
elif board[3] == sign and board[5] == sign and board[7] == sign:
if player_n1 == 'X':
print(f"\nIl giocatore" + str(1) + " ha vinto!")
else:
print(f"\nIl giocatore" + str(2) + " ha vinto!")
elif board[1] == sign and board[4] == sign and board[7] == sign:
if player_n1 == 'X':
print(f"\nIl giocatore" + str(1) + " ha vinto!")
else:
print(f"\nIl giocatore" + str(2) + " ha vinto!")
elif board[2] == sign and board[5] == sign and board[8] == sign:
if player_n1 == 'X':
print(f"\nIl giocatore" + str(1) + "ha vinto!")
else:
print(f"\nIl giocatore" + str(2) + " ha vinto!")
elif board[3] == sign and board[6] == sign and board[9] == sign:
if player_n1 == 'X':
print(f"\nIl giocatore" + str(1) + " ha vinto!")
else:
print(f"\nIl giocatore" + str(2) + " ha vinto!")
else: return "\n"
instructions()
while True:
board_test = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
time.sleep(5)
print("\n" * 100)
print("Iniziamo\n")
while answer == 'Si':
display_board(board_test)
print("\n")
player_choice(board_test, player1, 1)
if switcher(board_test, player1) != "\n":
break
time.sleep(2)
print("\n" * 100)
display_board(board_test)
print("\n")
player_choice(board_test, player2, 2)
if switcher(board_test, player1) != "\n":
break
time.sleep(2)
print("\n" * 100)
answer = input("Vuoi giocare di nuovo? Si/No")
if answer == 'No':
break
else:
continue
|
ebed420431aece5085c524bc4a5ad5a4fdbf67ee | Willjox/WebSecurity | /HA1/micromint.py | 780 | 3.6875 | 4 | import random
import sys
import math
def stddev(results, average):
y= []
for x in results:
y.append((x - average)**2)
return math.sqrt( ( (sum(y))/z) )
def mint(u,k,c):
i = 0;
p = 0;
korg = [0]*(2**u)
rand = random.SystemRandom()
while p < c:
x = rand.randint(0, len(korg)-1)
if korg[x] <= k:
korg[x] +=1
if korg[x] == k:
p+=1
i+=1
return i
k = 0
avg = 0
ci = 0
s = 0
u =int(input("u = "))
k =int(input("k = "))
c =int(input("c = "))
z =int(input("Number of itterations = "))
results = []
i=0
while i<z:
results.append((mint(u,k,c)))
i+=1
print(i)
avg = sum(results)/len(results)
s = stddev(results,avg)
ci = 2*3.66*s/(math.sqrt(z))
print(avg)
print(ci)
|
6cffaeeb5b02ee6140fea0392f37d680fed205ae | dzenre/python-project-lvl1 | /brain_games/cli.py | 241 | 3.59375 | 4 | """Module to ask player's name."""
import prompt
def welcome_user():
"""Ask player's name.""" # noqa: DAR201
name = prompt.string('May I have your name? ')
print('Hello, {}!'.format(name)) # noqa: WPS421 P101
return name
|
2a381d75c58b0a97e5599adf17466bda066f9e02 | hyeongyun0916/Algorithm | /acmicpc/python/13163.py | 105 | 3.671875 | 4 | num = int(input())
for i in range(num):
name = input().split(' ')
name[0] = 'god'
print(''.join(name)) |
8b6c96bcb94daa09063d873ab6649f49f316edca | andersoncruzz/service-ENEM | /banco.py | 1,141 | 3.546875 | 4 | import sqlite3
def newTeacher(Nome, Email, Matricula, Senha):
try:
conn = sqlite3.connect('openLab.db')
cur = conn.cursor()
cur.execute("""
INSERT INTO teachers (idTeacher, Nome, Email, Password)
VALUES (?,?,?,?)
""", (Matricula, Nome, Email, Senha))
#gravando no bd
conn.commit()
print('Dados inseridos com sucesso.')
conn.close()
return True
except Exception:
print("Erro")
return False
def searchTeacher(Matricula, Senha):
try:
conn = sqlite3.connect('openLab.db')
cur = conn.cursor()
cur.execute("""
SELECT * FROM teachers;
""")
for linha in cur.fetchall():
if (linha[0] == Matricula and linha[3] == Senha):
break
conn.close()
return linha
except Exception:
print("Erro")
return []
def UpdateTeacher(Nome, Email, Matricula, Senha):
try:
conn = sqlite3.connect('openLab.db')
cur = conn.cursor()
cur.execute("""
INSERT INTO teachers (idTeacher, Nome, Email, Password)
VALUES (?,?,?,?)
""", (Matricula, Nome, Email, Senha))
#gravando no bd
conn.commit()
print('Dados inseridos com sucesso.')
conn.close()
except Exception:
print("Erro") |
9f7091f4f2d58967ef4f5e15f1ec47cd81995694 | cleytonoliveira/pythonLearning | /Fundamentals/exercise6.py | 215 | 3.96875 | 4 | firstNumber = int(input('Write the first number: '))
sucessor = firstNumber + 1
predecessor = firstNumber - 1
print('The number {} has the predecessor {} and sucessor {}'.format(firstNumber, predecessor, sucessor))
|
de8bc57cba471bb94f6aed67eb0a35077cca72bb | cleytonoliveira/pythonLearning | /Fundamentals/exercise14.py | 215 | 4 | 4 | salary = int(input('How much is your salary? '))
calculateImprove = salary + (salary * 0.15)
print('Your salary is R${}, but you received 15% of higher and now your salary is R${}'.format(salary, calculateImprove))
|
a91e85e800e795b48d9dac1586ad9b69bbd87221 | bacasable34/formation-python-scripts-exemples | /carnet.py | 4,882 | 3.5 | 4 | #! /usr/bin/env python3
# programme carnet.py
# import du module datetime utilisé dans la class Personne pour calculer l'âge avec la date de naissance
import datetime
class Contact:
#attribut de la class Contact
nb_contact =0
# __init__ dunder init est le constructeur de la class --> qd tu fais c1=Contact('0312050623','5 rue du chemin','France'
def __init__(self,telephone=None, adresse=None, pays='France'):
self.telephone = telephone
self.adresse = adresse
self.pays = pays
Contact.nb_contact+=1
# __del__ dunder del est le destructeur de la classe --> qd tu fais c1.__del__()
def __del__(self):
Contact.nb_contact-=1
# __repr__ dunder repr est la sortie print --> qd tu fais p1 pour afficher son contenu
def __repr__(self):
return("tel:" + str(self.telephone) +
", adr:" + str(self.adresse) +
", pays:" + str(self.pays) +
", Cnombre:" + str(Contact.nb_contact))
# class Personne fille de la class Contact
class Personne(Contact):
# attribut de la class Personne
nombre=0
# __init__ dunder init est le constructeur de la class --> qd tu fais p1=Personne('Mike','Nom','49','0312050623','5 rue du chemin','France'
def __init__(self, nom='Doe',prenom='John',age=33, telephone=None, adresse=None, pays=None):
super().__init__(telephone,adresse,pays)
self.nom = nom
self.prenom = prenom
self.age = age
Personne.nombre+=1
# __del__ dunder del est le destructeur de la classe --> qd tu fais p1.__del__()
def __del__(self):
super().__del__()
Personne.nombre-=1
def __repr__(self):
return ("nom:" + str(self.nom) +
", prenom:" + str(self.prenom) +
", age:" + str(self.age) +
", Pnombre: " + str(Personne.nombre) + "\n" +
super().__repr__())
#getteur
def _get_annee_naissance(self):
return datetime.date.today().year - self.age
#setteur
def _set_annee_naissance(self, annee_naissance):
self.age=datetime.date.today().year - annee_naissance
#property qui utilise le getteur et le setteur
annee_naissance=property(_get_annee_naissance,_set_annee_naissance)
class Organisation(Contact):
nombre=0
def __init__(self, telephone=None, adresse=None, pays=None, raison='World Company'):
super().__init__(telephone, adresse,pays)
self.raison = raison
Organisation.nombre+=1
def __del__(self):
super().__del__()
Organisation.nombre-=1
def __repr__(self):
return ("raison sociale:" + str(self.raison) +
", Onombre: " + str(Organisation.nombre) + "\n" +
super().__repr__())
#test du module
if __name__=="__main__":
print("****test de la classe Contact****")
c1=Contact('0611222344', 'rue des Lilas','France')
print(" c1 :",c1)
print(" c2=Contact()")
c2=Contact()
print("****test de la classe Personne****")
print(" p1=Personne('Doe','John',33)")
p1=Personne('0145453454','Paris','France', 'Doe', 'John',33)
print(" p1 :",p1)
p2=Personne('545464546','Reims','France', 'Seror', 'Mike',49)
print(" p2 :",p2)
p2.annee_naissance = 1995
print(" p2 :", p2)
print("****test de la classe Organisation****")
print(" o1=Organisation('World Company')")
o1=Organisation('0145453454','Paris','France', 'World Company')
print(" o1 :",o1)
""""
#test du module
if __name__=="__main__":
print("test de la classe Contact")
print(" Contact.nb_contact : ", Contact.nb_contact)
print(" c1=Contact('0612232324','rue des Lilas','France')")
c1=Contact('0611222344', 'rue des Lilas','France')
print(" Contact.nb_contact : ", Contact.nb_contact)
print(" c1 :",c1)
print(" c2=Contact()")
c2=Contact()
print(" Contact.nb_contact : ", Contact.nb_contact)
print(" del c2")
del c2
print(" Contact.nb_contact : ", Contact.nb_contact)
print("test de la classe Personne")
print(" p1=Personne('Doe','John',33)")
p1=Personne('Doe', 'John',33)
print(" p1 :",p1)
print(" c2=Personne()")
c2=Contact()
print(" Personne.nombre : ", Contact.nb_contact)
print(" del c2")
del c2
print(" Personne.nombre : ", Contact.nb_contact)
print("test de la classe Organisation")
print(" o1=Organisation('World Company')")
o1=Organisation('World Company')
print(" o1 :",o1)
print(" c2=Personne()")
c2=Contact()
print(" Personne.nombre : ", Contact.nb_contact)
print(" del c2")
del c2
print(" Personne.nombre : ", Contact.nb_contact)
"""
|
11fa3e02f3663a34cbd2804a52ac2525e2c84d35 | bacasable34/formation-python-scripts-exemples | /test_sub.py | 950 | 3.84375 | 4 | #! /usr/bin/env python3
#
# test_sub.py - Mickaël Seror
# demande à l'utilisateur une chaine et une sous chaine
# Compte le nombre de fois qu'apparaît la sous chaine dans la chaine
# affiche les positions de la sous chaine dans la chaine
# affiche la chaine avec le caractère * à la place de la sous chaine
#
# Usage : ./test_sub.py
#
# 2021.01.09 : version originale
chaine = input('donner une chaîne : ')
sschaine = input('donner une sous-chaîne : ')
print('nombre de fois que la sous chaîne apparaît : ' + str(chaine.count(sschaine)))
# Utilisation de find à la place de index car qd la sschaine n'est pas trouvé find renvoie -1
# tandis que index renvoie une erreur
pos=chaine.find(sschaine)
while pos>=0:
print('position de la sous chaine dans la chaine : ' + str(pos))
pos = chaine.find(sschaine,pos +1)
print('affiche la chaine avec le caractère * à la place de la sous chaine : ' + chaine.replace(sschaine,'*'*len(sschaine)))
|
29ef17e51ae29ba273a3b59e65419d73bacf6aa0 | mathivananr1987/python-workouts | /dictionary-tuple-set.py | 1,077 | 4.125 | 4 | # Tuple is similar to list. But it is immutable.
# Data in a tuple is written using parenthesis and commas.
fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print("count of orange", fruits.count("orange"))
print('Index value of orange', fruits.index("orange"))
# Python Dictionary is an unordered sequence of data of key-value pair form.
# It is similar to Map or hash table type.
# Dictionaries are written within curly braces in the form key:value
countries = {"India": "New Delhi", "China": "Beijing", "USA": "Washington", "Australia": "Canberra"}
print(countries["India"])
# adding entry to dictionary
countries["UK"] = "London"
print(countries)
# A set is an unordered collection of items. Every element is unique (no duplicates).
# In Python sets are written with curly brackets.
set1 = {1, 2, 3, 3, 4, 5, 6, 7}
print(set1)
set1.add(10)
# remove & discard does the same thing. removes the element.
# difference is discard doesn't raise error while remove raise error if element doesn't exist in set
set1.remove(6)
set1.discard(7)
print(set1)
|
4f1a69c960fb3c4575ad1dd493da268cb9b2298b | mathivananr1987/python-workouts | /try-except.py | 1,745 | 4.03125 | 4 | import os
import sys
# various exception combinations
# keywords: try, except, finally
try:
print("Try Block")
except Exception as general_error:
# without except block try block will throw error
print("Exception Block. {}".format(general_error))
try:
vowels = ['a', 'e', 'i', 'o', 'u']
print(vowels[5])
except IndexError as index_err:
print("Cannot print list item. Exception: {}".format(index_err))
try:
size = os.path.getsize("class-object1.py")
print("{} Bytes".format(size))
except FileNotFoundError as file_err:
print("Unable to retrieve size. Exception: {}".format(file_err))
try:
file_object = open("data.txt", "r")
print(file_object.read())
except FileNotFoundError as no_file_err:
print("Unable to open the file. Exception: {}".format(no_file_err))
try:
file_object = open("data/dummy.txt", "a")
file_object.write("Hi hello")
except PermissionError as access_err:
print("Unable to open the file. Exception: {}".format(access_err))
try:
variable_one = "Hello Good morning"
print(variable_two)
except NameError as name_err:
print("Unable to retrieve variable. Exception: {}".format(name_err))
sys.exit(1)
try:
print(10/0)
except ZeroDivisionError as operation_err:
print(operation_err)
finally:
# finally block gets executed regardless of exception generation
# optional block for try-except group
print("division operation over")
try:
user_input = int(input("enter a number"))
print("received input: {}".format(user_input))
except ValueError as input_err:
print("Unable to retrieve user input. {}".format(input_err))
# You can refer for various exceptions in python: https://docs.python.org/3/library/exceptions.html
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.