blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a9f4c5a776e6442e5b1e240630fb275f6c8b1334
VinhMaiVy/learning-python
/src/Algorithms/00 Implementation/py_life_the_universe.py
205
3.71875
4
#!/bin/python3 """ Python Input: Output: """ if __name__ == '__main__': while True: n = int(input()) if n == 42: break else: print(n)
6e4e764da06516d76a4a4596995109c8c222da54
GabrielReira/Python-Exercises
/05 - Reajuste salarial.py
207
3.5
4
s = float(input('Digite o salário atual: R$')) r = float(input('Digite a porcentagem de reajuste: ')) novo = s + s * (r / 100) print(f'Com o reajuste de {r}%, o funcionário passa a receber R${novo:.2f}.')
73fca4bc332ba4b3ef040785a934cfcf5e0e01d0
zaifrun/ml
/firstflow.py
2,551
3.515625
4
import tensorflow as tf import matplotlib.pyplot as plt from datetime import datetime def log_scalar(writer, tag, value, step): """Log a scalar variable. Parameter ---------- tag : basestring Name of the scalar value step : int training iteration """ summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)]) writer.add_summary(summary, step) print ("Tensorflow version "+str(tf.__version__)) x = tf.Variable(3,name="x") y = tf.Variable(4,name="y") f = x*x*y+y+2 init = tf.global_variables_initializer() session = tf.InteractiveSession() init.run() result = f.eval() print("result: "+str(result)) # should give 42 - the answer to everything # Model parameters - initialize to something W = tf.Variable([.3], dtype=tf.float32) b = tf.Variable([-.3], dtype=tf.float32) # Model input and output x = tf.placeholder(tf.float32) linear_model = W*x + b # the model we are trying to find the best value of W and b for our data y = tf.placeholder(tf.float32) # loss loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares of the difference # optimizer optimizer = tf.train.GradientDescentOptimizer(0.01) train = optimizer.minimize(loss) # training data - - in this example they fit perfectly to the model : y = -1 * x + 1, # so we should in an optimal training situation be able to achieve an error of 0 in theory. x_train = [1, 2, 3, 4] y_train = [0, -1, -2, -3] # training init init = tf.global_variables_initializer() sess = tf.Session() # setup a logdir for tensorflow to use root_logdir = "tf_logs" logdir = "{}/run-{}/".format(root_logdir,datetime.utcnow().strftime("%Y%m%d%H%M%S")) file_writer = tf.summary.FileWriter(logdir,tf.get_default_graph()) sess.run(init) # set values to our initialials error = [] slope = [] bvalue = [] # training for i in range(1000): sess.run(train, {x: x_train, y: y_train}) # train using our data - and minimize the loss function curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train}) error.append(curr_loss) log_scalar(file_writer,"error",curr_loss,i) slope.append(curr_W) bvalue.append(curr_b) file_writer.close() print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss)) session.close() plt.plot(error,label='Error') plt.plot(slope,label='Slope') plt.plot(bvalue,label='constant,b') plt.legend() plt.title("Tensorflow training to match data to the linear model of y = -1*x + 1") plt.xlabel("Training iteration") plt.show()
a2964f768434fc37556885e266a15fbd0d63933b
FatemaFawzy/Text-Segmentation
/Preprocessing.py
1,221
3.609375
4
import pandas as pd import re #Reading dataset from file. Covert all to lowercase df= pd.read_csv("sets\RandomSentencesDS.csv", error_bad_lines=False)['text'].dropna().str.lower() #remove special characters by replacing them with an empty string. Keep letters, hyphens, and white space only filtered_data= df.apply(lambda x: re.sub(r'[^a-z-\s]','',x)) #for word-word, replace - with white space because it's likely to improve detection accuracy filtered_data= filtered_data.apply(lambda x: re.sub(r'[-]',' ',x)) filtered_data.replace(" ", float("NaN"), inplace=True) filtered_data.replace("", float("NaN"), inplace=True) filtered_data.dropna(inplace=True) #remove spaces and save values in a new file with columns [input, output, original] allData= pd.DataFrame(filtered_data.apply(lambda x: x.replace(" ",""))) allData["output"]=filtered_data.apply(lambda x: x.split()) #expected word segmentation output ["hey","whats","up"] allData.rename(columns={'text':'input'},inplace=True) #compact sentence "heywhatsup" allData["original"]=filtered_data #original sentence after preprocessing "hey whats up" -> used for testing with a library allData.to_csv('sets\myDataSet.csv')
aac6eef18a908e4c625d00ebbfe8b097cbdbd4f0
YerraboluHimajaReddy/LalithaClass
/LalithaPythonClass/AdvancedDatatypes/Set Difference.py
226
3.578125
4
# Difference of two sets # initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use - operator on A print(A - B) #{1, 2, 3} print(B - A) #{8, 6, 7} print(A.difference(B)) #{1, 2, 3} print(B.difference(A)) #{8, 6, 7}
c6f1407abc3c12e2455b1cc75e3cc0c1b11513f5
ATOME1/arithmetic_exercise
/python-test/test_tmp.py
904
3.875
4
from day02.MergeSort import * from day02.QuickSort import * # 生成一组随机数组 def generateRandomArray(maxSize, maxValue): return [random.randint(0, maxValue) for i in range(maxSize)] # 默认排序方式 def comparator(arr): arr.sort() # 使用对数器的方式检测排序是否ok if __name__ == '__main__': testTimes = 10000 maxSize = 100 maxValue = 100 succeed = True for i in range(testTimes): arr1 = generateRandomArray(maxSize, maxValue) arr2 = copy.deepcopy(arr1) # mergeSort(arr1,0,len(arr1)-1) quickSort(arr1,0,len(arr1)-1) comparator(arr2) if (arr1 != arr2): succeed = False print(arr1) print(arr2) break print("Nice" if succeed else "Error") a1 = generateRandomArray(maxSize, maxValue) print(a1) mergeSort(a1,0,len(a1)-1) print(a1)
aa664c3e1d41d17349386d3a84a99deda7ea0450
soo-youngJun/pyworks
/exercise/test04.py
1,146
4.15625
4
# 1번 ''' def is_odd(number): if number % 2 == 1: return True else: return False print(is_odd(8)) # 2번 def avr_number(*args): result = 0 for i in args: result += i print(i, result) return result / len(args) print(avr_number(1, 2)) print(avr_number(3,2,5,4,1)) # 3번 input1 = int(input("첫번째 숫자를 입력하세요:")) input2 = int(input("두번째 숫자를 입력하세요:")) total = input1 + input2 print("두 수의 합은 %d" % total) # 4번 print("you""need""python") print("you"+"need"+"python") print("you", "need", "python") print("".join(["you", "need", "python"])) # 5번 f1 = open("test.txt", 'w') # with ~ as로 변경하거나 f1.write("Life is too short") f1.close() # close() 필요 f2 = open("test.txt", 'r') print(f2.read()) f1.close() # close() 필요 # 6번 user_input = input("저장할 내용을 입력하세요: ") f = open('test.txt', 'a') f.write(user_input) f.write("\n") f.close() ''' # 7번 f = open('text.txt', 'r') body = f.read() f.close() body = body.replace('java', 'python') f = open('text.txt', 'w') f.write(body) f.close()
fb2f26df768c504916e619ef9c97bae006d65594
oota030114/kadai
/study-01-search-main/03_search.py
1,498
3.6875
4
import csv import os # 検索ソース source=["ねずこ","たんじろう","きょうじゅろう","ぎゆう","げんや","かなお","ぜんいつ"] source_b=["ねずこ","たんじろう","きょうじゅろう","ぎゆう","げんや","かなお","ぜんいつ"] ### csv読込み def readCSV(csvFile): if os.path.exists(csvFile): with open(csvFile) as f: listCSV = f.read() f.close() return listCSV.split(',') ### リスト更新 def updateSource(listCSV): index = 0 while index < len(listCSV): if not(listCSV[index] in source): source.append(listCSV[index]) index = index + 1 return source ### 検索ツール def search(): word =input("鬼滅の登場人物の名前を入力してください >>> ") chk = word[-4:] if (chk == ".csv") or (chk == ".CSV"): if (os.path.isfile(word)): ###csv読込み listCSV = readCSV(word) ret = updateSource(listCSV) else: ret = "入力したCSVファイルは存在しません。" else: if not(word in source): source.append(word) ret = source return ret ### メイン処理 if __name__ == "__main__": ### 検索ツール source = search() ###更新結果 print("鬼滅の登場人物の(更新前)⇒",source_b) print("鬼滅の登場人物の(更新後)⇒",source)
38bd73a417ec268a652588f27f40be4f20b0fd73
willamesalmeida/Maratona-Datascience
/Semana 1 - O poderoso Python/fase 2 - Exercicios/Estruruda de Decisão/Exercicio 1.py
290
4.03125
4
# 1 - Faça um Programa que peça dois números e imprima o maior deles. a, b = map(float, input("Forneça dois valores e direi qual o maior deles: ").split()) if a > b: print("O maior número fornecido é: {} ".format(a)) else: print("O maior número fornecido é: {} ".format(b))
8fcbf0368bfb57f4f5d6c14ed67466b0e54b7213
bansal19/SfM_implementation
/DLT/direct_linear_transform.py
3,137
3.765625
4
import numpy as np import funcs def normalize_and_make_homogeneous(x_unnormalized): """Modify x_unnormalized to normalize the vector according to standard DLT methods and make homogeneous. Normalization is used to stabilize calculation of DLT x_unnormalized: 3 or 2 dimensional input data to be normalized """ mean, std_dev = np.mean(x_unnormalized, 0), np.std(x_unnormalized) if x_unnormalized.shape[1] == 2: transform = np.array([[std_dev, 0, mean[0]], [0, std_dev, mean[1]], [0, 0, 1]]) elif x_unnormalized.shape[1] == 3: transform = np.array([[std_dev, 0, 0, mean[0]], [0, std_dev, 0, mean[1]], [0, 0, std_dev, mean[2]], [0, 0, 0, 1]]) else: print("Please use number of dimensions equal to 2 or 3.") assert False transform = np.linalg.inv(transform) x_unnormalized = np.dot(transform, np.concatenate((x_unnormalized.T, np.ones((1,x_unnormalized.shape[0]))))) x_unnormalized = x_unnormalized[0:x_unnormalized.shape[1], :].T return transform, x_unnormalized def calculate_calibration_matrix(points3D, points2D): """Use DLT to calculate the 11 params of the calibration matrix. Calibration matrix transforms from 3D to 2D.""" transform3D, points3D_norm = normalize_and_make_homogeneous(points3D) transform2D, points2D_norm = normalize_and_make_homogeneous(points2D) matrix = [] for i in range(points3D.shape[0]): X, Y, Z = points3D_norm[i,0], points3D_norm[i,1], points3D_norm[i,2] x, y = points2D_norm[i, 0], points2D_norm[i, 1] matrix.append([-X, -Y, -Z, -1, 0, 0, 0, 0, x*X, x*Y, x*Z, x]) matrix.append([0,0,0,0,-X,-Y,-Z,-1,y*X,y*Y,y*Z, y]) matrix = np.array(matrix) _,_,V = np.linalg.svd(matrix) calibration_matrix = np.reshape(V[-1,:] / V[-1,-1], (3,4)) #Invert normalization with transform matrices calibration_matrix = np.dot(np.linalg.pinv(transform2D), np.dot(calibration_matrix, transform3D)) calibration_matrix = calibration_matrix / calibration_matrix[-1,-1] return calibration_matrix def get_calibration_points(old_points, old_points3D, new_image, dist): """Match feature points for the new image to the point cloud.""" _, mask_a, points2D, mask_b = funcs.find_matches(old_points[0], old_points[1], new_image[0], new_image[1], dist) points3D = old_points3D[mask_a] return points3D, points2D def perform_dlt(old_points, old_points3D, new_image, dist=0.7): """Perform dlt on the new image to get camera matrix. old_points: 2D points in pointcloud from image 1 or 2. list with old_points[0] being 2d points and old_points[1] being description vectors for the points old_points3D: same points as old_points but with depth. old_points3D are in the same order as old_points new_image: 2D points from image 3. list with new_image[0] being 2d points and new_image[1] being description vectors for the points """ old_points3D = np.array(old_points3D) points3D, points2D = get_calibration_points(old_points, old_points3D, new_image, dist) return calculate_calibration_matrix(points3D, points2D)
e4b68f6d90fd950a6342c20605ec1a8fc6e0afa4
Podakov4/pyCharm
/module_3/lesson_6.py
448
3.6875
4
# Задача 6. Игра в кубики cube_of_Kostia = int(input('Кубик Кости: ')) cube_of_owner = int(input('Кубик Владельца: ')) if cube_of_Kostia >= cube_of_owner: kostia_pay = cube_of_Kostia - cube_of_owner print('Сумма:', kostia_pay) print('Костя платит') else: owner_pay = cube_of_Kostia + cube_of_owner print('Сумма:', owner_pay) print('Владелец платит') print('Игра окончена')
2027b70382c76671c01d729ba75024a015f3d7fc
MinWooPark-dotcom/learn-pandas
/Part2/2.10_excewriter.py
1,456
3.734375
4
# -*- coding: utf-8 -*- import pandas as pd # 판다스 DataFrame() 함수로 데이터프레임 변환. 변수 df1, df2에 저장 data1 = {'name': ['Jerry', 'Riah', 'Paul'], 'algol': ["A", "A+", "B"], 'basic': ["C", "B", "B+"], 'c++': ["B+", "C", "C+"]} data2 = {'c0': [1, 2, 3], 'c1': [4, 5, 6], 'c2': [7, 8, 9], 'c3': [10, 11, 12], 'c4': [13, 14, 15]} df1 = pd.DataFrame(data1) df1.set_index('name', inplace=True) # name 열을 인덱스로 지정 print(df1) print('\n') # algol basic c++ # name # Jerry A C B+ # Riah A+ B C # Paul B B+ C+ df2 = pd.DataFrame(data2) df2.set_index('c0', inplace=True) # c0 열을 인덱스로 지정 print(df2) # c1 c2 c3 c4 # c0 # 1 4 7 10 13 # 2 5 8 11 14 # 3 6 9 12 15 # df1을 'sheet1'으로, df2를 'sheet2'로 저장 (엑셀파일명은 "df_excelwriter.xlsx") writer = pd.ExcelWriter("./df_excelwriter.xlsx") df1.to_excel(writer, sheet_name="sheet1") df2.to_excel(writer, sheet_name="sheet2") writer.save() #! my writer2 = pd.ExcelWriter("./my.xlsx") df1.to_excel(writer2, sheet_name="anything2") df2.to_excel(writer2, sheet_name="anything1") writer2.save() #! my writer3 = pd.ExcelWriter("./my2.xlsx") df1.to_excel(writer3, sheet_name="any2") df2.to_excel(writer3, sheet_name="any1") # writer2.save() 없으면 생성 안 됨.
71614977e3e2bc4c1f5bf9f493e170b2bda2d9df
pawel123789/practice
/31.py
132
3.59375
4
a = 120 b = 150 for n in range(1, 121): if a / n is int and b / n is int: print(n) else: print('co jest?')
24d60afed921cc62828d98b87050fbd956f69b39
hudhaifahz/LING447
/ClassWork/newfriend.py
158
3.890625
4
name = 'Emma' number = 3 #print ('My new friend is ',name,' who speaks ',number,' languages.') print 'My new friend is',name,'who speaks',number,'languages.'
af03a1f0bc4dbe3c6c50828c3176ddc1903f614f
ZuuVOKUN/Python_learning
/PycharmProjects/hillel_python/src/sample_lists.py
423
3.921875
4
import random a = ['a', 'b', 'c'] b = ['a', 2, 'c', [0, 10, [4, 'z']]] # # print(type(a)) # print(type(b)) # print(b[0]) # print(b[0:2]) # print(len(b)) # # for i in range(len(b)): # print(b[i]) # # print(b[3][2][1]) n = 3 random_list = [] for i in range(n+1): random_list.append(random.random()) print(random_list) print(len(random_list)) # реализовать все методы из модуля list
aae067d02ddea0f028d42ad2689e2de69d2a254c
yyyuaaaan/pythonfirst
/crk/1.5h.py
1,559
3.796875
4
""" __author__ = 'anyu' Implement a method to perform basic string compression using the counts of repeated characters aabcccccaa would become a2blc5a3. do nothing if this would not make the string smaller. """ def str_compress(strinput): """ very tricky question, border conditions, be careful 0(N) time and 0(N) space. """ str_comp=[] count = 1 for i in range(len(strinput)-1): if strinput[i] != strinput[i+1] : # because have to consider the i+1 element, may array overflow str_comp.append(strinput[i]+str(count)) count = 1 else: count += 1 str_comp.append(strinput[-1]+str(count)) # an-1 = an; an-1 != an; two condition same if len(str_comp) >= len(strinput): return ''.join(strinput) else: return ''.join(str_comp) def str_compress2(strinput): """ another way: simple, use index as pointer! use 2 pointer p1 p2, use while use count anyway, pointer is complex """ if len(strinput) <= 1: return strinput tempoutput = [] starter = 0 rider = 1 while 0 <= starter <=len(strinput)-2: #starter in range(0,len(strinput)-1) wrong , range is a iterator while 1 <= rider <= len(strinput)-1: if strinput[starter] == strinput[rider]: rider+=1 tempoutput.append(strinput[starter]+rider-starter) starter = rider rider +=1 print "dd" break print str_compress2("abc") print str_compress2("aabc") print str_compress2("aabcccccabbdssssd")
ba0fe41d8ca02223d6d09ce232bc16449a0616d9
stahl/adventofcode
/2017/day10/b.py
746
3.53125
4
from functools import reduce from operator import xor def rotate(lst, i): """Rotates the list lst i steps to the left.""" lst[:] = lst[i:] + lst[:i] s = '106,16,254,226,55,2,1,166,177,247,93,0,255,228,60,36' lengths = [ord(x) for x in s] + [17, 31, 73, 47, 23] xs = list(range(256)) pos = 0 skip = 0 for r in range(64): for length in lengths: rotate(xs, pos) xs[:length] = reversed(xs[:length]) rotate(xs, -pos) pos = (pos + length + skip) % len(xs) skip += 1 def chunk(lst, i, size=16): """Extracts chunk #i from the given list.""" return lst[i * size:i * size + size] dense_hash = (reduce(xor, chunk(xs, x)) for x in range(16)) print(''.join(f'{x:02x}' for x in dense_hash))
e905060f51c26c112e52bb6dd8d25dd17af56b34
ellyzyaory/Exercise-1-Part-2
/studentgroups.py
921
4
4
class1 = 32 class2 = 45 class3 = 51 print("Number of students in each group: ") class1_group = int(input("Class 1: ")) while class1_group <= 0: class1_group = int(input("Class 1: ")) class2_group = int(input("Class 2: ")) while class2_group <= 0: class2_group = int(input("Class 2: ")) class3_group = int(input("Class 3: ")) while class3_group <= 0: class3_group = int(input("Class 3: ")) students_each_group1,class1_leftover = divmod(class1,class1_group) students_each_group2,class2_leftover = divmod(class2,class2_group) students_each_group3,class3_leftover = divmod(class3,class3_group) print("Number of students in each group: ") print("Class 1: ", students_each_group1) print("Class 2: ", students_each_group2) print("Class 3: ", students_each_group3) print("Number of students leftover: ") print("Class 1: ", class1_leftover) print("Class 2: ", class2_leftover) print("Class 3: ", class3_leftover)
7d8811709dbee2e2e71ae3b88a06a53be2c461b5
JavierFSS/MySchoolProject
/URI_Online/1019.py
195
3.5625
4
totalWaktu = int(input()) Jumlah = [3600, 60, 1] hasil = [] for item in Jumlah : jumlah2 = (totalWaktu / item) hasil.append(str(jumlah2)) totalWaktu -= item * jumlah2 print(":".join(hasil))
20ac203a74026648339d8417538c6abb15a53979
AlexKohanim/ICPC
/ostgotska.py
212
3.53125
4
s = input() #print((len([x for x in s.split() if "ae" in x]),len(s.split()))) print("dae ae ju traeligt va" if (len([x for x in s.split() if "ae" in x]) / len(s.split())) >= 0.4 else "haer talar vi rikssvenska")
c40df77c0c92769521cee63e11f92e29ea41f7f8
SarveshSiddha/Demo-repo
/assignment1/palindrome.py
195
4.03125
4
a=int(input("enter the number")) demo=a rev=0 while(a>0): dig=a%10 rev=rev*10+dig a=a//10 if(demo==rev): print("number is palindrome") else: print("number is not palindrome")
111f515714aa14ba964fee38c3c488ced6952a2c
mrblack10/tamrin
/jadi/azmon3_3.py
210
3.78125
4
n = input() n = int(n) x = 1 a = 1 while (x>0): ###### for i in range(1,x+1): print("*",end ='') x = x + a print("") ###### or -> print("*" * x) if x == n: a = -1
0a9ef68cd9050e3e72c4d48779c1272934e8bf2b
Ishita-Tiwari/Dynamic-Programming
/14. Shortest Common SuperSequence.py
605
3.609375
4
def shortestCommonSupersequence(s1, s2, n1, n2): dp = [[0 for i in range(n2 + 1)] for j in range(n1 + 1)] ''' Length of shortest common supersequence: max possible length - length of max common subsequence ''' for i in range(1, n1 + 1): for j in range(1, n2 + 1): if s1[i - 1] == s2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return (n1 + n2 - dp[-1][-1]) s1 = input() s2 = input() n1, n2 = len(s1), len(s2) print(shortestCommonSupersequence(s1, s2, n1, n2))
29e34f165d7df8b23589360b0c0ecf8cde7ab38e
junhao69535/pycookbook
/chapter3/round_of_digits.py
554
3.765625
4
#!coding=utf-8 """ 数字的四舍五入 """ # 想对浮点数执行指定精度的舍入运算 # 对于简单的舍入运算,使用内置的round(value, ndigits)即可 print round(1.23, 1) # 保留一位 print round(1.27, 1) # 会进行四舍五入 print round(-1.27, 1) print round(1.25361, 3) # 保留三位 # 传给ndigits参数可以是负数,这时,舍入运算会作用在十位、百位、千位等上面 a = 1627731 print round(a, -1) print round(a, -2) print round(a, -3) # 如果不允许小误差,需要使用decimal模块
40a6074b2cef8de13b43327a90c9e28ac3d61cc9
alvaronaschez/amazon
/basics/knapsack_01.py
1,530
4.1875
4
""" https://rosettacode.org/wiki/Knapsack_problem/0-1 https://rosettacode.org/wiki/Knapsack_problem """ import unittest from math import inf def knapsack_01(weights, values, max_weight): """ dynamic programming algorithm based on the following recursive definition: knapsack(i, w) = -inf if w<0 knapsack(i, w) = 0 if i=-1 or w=0 knapsack(i, w) = max( v[i] + knapsack(i-1, w-w[i]), knapsack(i-1, w) otherwise where i is the last explored item and w the remaining capacity of the knapsack """ n = len(weights) aux = [[0]*(max_weight+1) for _ in range(n)] def read(i, w): if w < 0: return -inf elif i == -1 or w == 0: return 0 else: return aux[i][w] for i in range(n): for j in range(max_weight+1): aux[i][j] = max( read(i-1, j-weights[i]) + values[i], read(i-1, j) ) return read(n-1, max_weight) class TestKnapsack01(unittest.TestCase): def test_knapsack_01(self): weights = [9, 13, 153, 50, 15, 68, 27, 39, 23, 52, 11, 32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30] values = [150, 35, 200, 160, 60, 45, 60, 40, 30, 10, 70, 30, 15, 10, 40, 70, 75, 80, 20, 12, 50, 10] max_weight = 400 expected_result = 1030 result = knapsack_01(weights, values, max_weight) self.assertEqual(result, expected_result) if __name__ == "__main__": unittest.main(verbosity=2)
eb0b73df3629688a2cfeb7c274987a1d5c2a765f
yipcrystalp/Tech-Basics-1
/greet.py
537
3.828125
4
#define 'greet()' def greet(): print ("Hey there!") name = raw_input("Please type your name: ") print ("Nice to meet you " + name) country = raw_input("So where are you from? ") print ("Interesting, so you're from " + country) print ("I'd love to visit there someday! :)") choice = raw_input("Can I sing a song for you? yes or no? ") if choice == "yes": s = open("birds.txt", "r") song = s.read() print song else: print("Okay, no problem, goodbye! :)") greet();
c6bc53ecd6e7f994b9ad5a87e37fc8a467e4ccc5
LStokes96/Python
/Code/ISBN.py
273
3.6875
4
def isbn(digits): digit_list = list(map(int, str(digits))) print(digit_list) isbn = [9,7,8,0,3,0,6,4,0,6,1,5] even = sum(isbn[::2]) * 3 odd = sum(isbn[1::2]) total = even + odd last_digit = 10-(total/10) print(int(last_digit)) print(even) print(odd) isbn(12345)
782288b5640350abc23e5442fcf3544537835c54
sp0002/cp2019
/p03/q6_display_matrix.py
202
3.921875
4
from random import randint def print_matrix(n): for i in range(1,n+1): for p in range(1, n+1): print("{} ".format(randint(0, 1)), end="") print(" ") print_matrix(int(input("Input number: ")))
844c00ef3d28df6d115cbc095c5781cc2ae6e708
packerbacker8/PythonNeuralNetwork
/SimplePerceptron/training.py
761
3.515625
4
from random import uniform def line_func(x): # y = mx + b return 0.3 * x + 0.2 class Point: def __init__(self, x = None, y=None, size = 8): if x is None: self.x = uniform(-1,1) else: self.x = x if y is None: self.y = uniform(-1,1) else: self.y = y self.label = 1 if self.y > line_func(self.x) else -1 self.size = size self.px = width / 2 + self.x * width / 2 self.py = height / 2 - self.y * height / 2 self.bias = 1 def show(self): stroke(0) if(self.label == 1): fill(255) else: fill(0) ellipse(self.px, self.py, self.size, self.size)
38dd117c3e56885018d2cab408aa2a49d3731e42
sensve/ClientServer
/Server/Server.py
882
3.53125
4
import socket # Set the server address SERVER_ADDRESS = ('127.0.0.1', 5000) # Configure the socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(SERVER_ADDRESS) server_socket.listen(10) print('[server]: server is running, please, press ctrl+c to stop') # Listen to requests while True: connection, address = server_socket.accept() try: print("[server]: new connection from {address}".format(address=connection)) while True: data = connection.recv(1024).decode("utf-8") print("[server]: received from client: `{}` sending same message back.".format(data)) connection.send(bytes(data, encoding='UTF-8')) # if str(data) == "exit": # break connection.close() except Exception as ex: print ("[server]: {exception}".format(exception=ex))
4f2f828c09c55be980b888f05a0d951aa06e67da
JiahangGu/leetcode
/All Problems/1584-min-cost-to-connect-all-points.py
2,285
3.546875
4
#!/usr/bin/env python # encoding: utf-8 # @Time:2020/9/15 9:57 # @Author:JiahangGu from typing import List class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: """ 大体思路是,首先构造出一个全联通图,然后得到最小生成树。 :param points: :return: """ class Node: def __init__(self, x, y, dis): self.x = x self.y = y self.dis = dis def __lt__(self, other): return self.dis < other.dis def find(x): if fa[x] == x: return x else: fa[x] = find(fa[x]) return fa[x] def union(x, y): fax, fay = find(x), find(y) if fax != fay: fa[fax] = fay import heapq edges = [] fa = [i for i in range(len(points))] for i in range(len(points)-1): for j in range(i+1, len(points)): d = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]) heapq.heappush(edges, Node(i, j, d)) ans = 0 cnt_e = 0 while cnt_e < len(points)-1: node = heapq.heappop(edges) x, y, dis = node.x, node.y, node.dis if find(x) != find(y): union(x, y) ans += dis cnt_e += 1 return ans """ 这里记录使用Prim算法实现的方案。Prim从已有点出发,寻找和MST联通分量相邻的最小权值边。 """ # from queue import PriorityQueue as PQ # visit = set([i for i in range(len(points))]) # cal_dis = lambda x, y: abs(x[0] - y[0]) + abs(x[1] - y[1]) # ans = 0 # q = PQ() # q.put((0, 0)) # while visit: # weight, pos = q.get() # if pos not in visit: # continue # visit.remove(pos) # ans += weight # for i in visit: # q.put((cal_dis(points[i], points[pos]), i)) # return ans s = Solution() points = [[-8,14],[16,-18],[-19,-13],[-18,19],[20,20],[13,-20],[-15,9],[-4,-8]] print(s.minCostConnectPoints(points))
2cdcba478f1478c548573b047c36c58da40dd20c
tjschweitzer/CSCI136
/Homework3/2-1-2.py
219
3.921875
4
def odd(a,b,c): count = 0 if a: count+=1 if b: count+=1 if c: count+=1 if count%2: return True else: return False #test code #print(odd(False,False,True))
4f04948364a224ef475d037bac5948c2675fb327
dedx/3DTracker
/SpacePoint.py
1,180
4.15625
4
########################################### # # Class defining a SpacePoint # # J.L. Klay # 14-May-2012 # ########################################### import math class SpacePoint(object): """represents a point in 3-D space in cartesian coordinates in centimeters""" def __init__(self,x=0.0,y=0.0,z=0.0,wgt=1.0): self.x = x self.y = y self.z = z self.wgt = wgt self.mag = math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z) def __str__(self): return '(%.2f, %.2f, %.2f, %.2f) \t%.2f' % (self.x, self.y, self.z, self.wgt, self.mag) def distance(self,other): return math.sqrt((self.x-other.x)**2+(self.y-other.y)**2+(self.z-other.z)**2) def dot(self,other): return self.x*other.x+self.y*other.y+self.z*other.z def subtract(self,other): res = SpacePoint(self.x-other.x,self.y-other.y,self.z-other.z,self.wgt) return res def add(self,other): res = SpacePoint(self.x+other.x,self.y+other.y,self.z+other.z,self.wgt) return res def scale(self,val): res = SpacePoint(self.x*val,self.y*val,self.z*val,self.wgt) return res
c5f9e38a9f3ba0081b5e8ae96cdf281044d7630e
songzi00/python
/Pro/基础/02数据类型/列表.py
1,363
3.953125
4
""" #获取列表的平均值 list = [12,34,56,87,23] n1 = 0 n2 = 0 while n1 < 3: n2 += list[n1] n1 += 1 print("平均值 = %d" % (n2 / 5)) list3 = [1,2,3,4] print(3 in list3) list5 = [1,2,3,4,5,6,7,8,9] print(list5[2:5]) list6 = [1,2,3,4,5,6] list6.insert(3,280) print(list6) list7 = [1,2,3,4,5,6,7] print(list7.pop(2)) list8 = [1,23,45,61,58] list8.remove(58) print(list8) list9 = [1,2,3,4,5,6] list9.clear() print(list9) list10 = [1,2,3,4,5] list11 = list10.index(4) print(list11) list12 = [1,66,37,357,357,2,4,657,34] print(len(list12)) list13 = [633,456,62,66,4357,686,24,75] print(min(list13)) list14 = [1,2,3,4,1,3,5,5,6,3,6] print(list14.count(3)) list15 = [1,2,6,4,6,7,6,4,6] p = 0 all = list15.count(6) while p < all: list15.remove(6) p += 1 print(list15) list16 = [1,2,3,4,5,6] list16.reverse() print(list16) list17 = [2,5,7,3,6,8,9] list17.sort() print(list17) list18 = [1,2,3,4,5,6] list19 = list18 list19[2] = 36 print(list19,list18) list20 = [1,2,3,4,5] list21 = list20.copy() list21[2] = 49 print(list20,list21) list = [1,5,3,8,4,6,2,9] list.sort() count = list.count(list[len(list) - 2]) c = 0 while c < count: list.pop() c += 1 print(list[len(list) - 2]) """ num = int(input()) i = 2 while num != 0: if num % i == 0: print(i) num //= i else:i += 1
c894dd00e23346434c848955febabe70ff5c731b
Nickruti/Automation
/Input_data_from_file.py
231
3.71875
4
import itertools with open("input.txt") as textfile1, open("input.txt") as textfile2: for x, y in itertools.zip_longest(textfile1, textfile2): x = x.strip() y = y.strip() print("{0}\t{1}".format(x, y))
54b352c358a6384bbb9cec5dffea7bfb378a2439
MDomanski-dev/MDomanski_projects
/Python_Crash_Course_Eric_Matthes/keys.py
541
3.5625
4
favourite_lang = { 'janek': 'python', 'sara': 'c', 'edward': 'ruby', 'paweł': 'python', } friends = ['edward','sara'] for imie in favourite_lang.keys(): print(imie.title()) if imie in friends: print("Witaj, " + imie.title() + "! Widzę, że twoim ulubiony" " językiem programowania jest " + favourite_lang[imie].title() + "!") if 'malgorzata' not in favourite_lang.keys(): print("Malgorzata, weź udział w ankiecie") for imie in sorted(favourite_lang.keys()): print(imie.title() + " dziękuje za udział w ankiecie")
dc40642e002eea4b1dd358080949bca6667575d7
zzhyzzh/Leetcode
/leetcode-algorithms/101. Symmetric Tree/isSymmetric.py
1,249
3.890625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True head = 0 queue = [root] while True: temp = head i, j = temp, len(queue) - 1 while i < j: if not queue[i]: if queue[j]: return False elif not queue[j]: i += 1 j -= 1 elif not queue[j] or queue[i].val != queue[j].val: return False else: i += 1 j -= 1 noneCount = 0 for i in range(temp, len(queue)): head += 1 if not queue[i]: noneCount += 1 continue else: queue.append(queue[i].left) queue.append(queue[i].right) if noneCount == len(queue) - temp: return True
81eb4f2dcbbd12985f98475ac0ba537463083e03
Weeeendi/Python
/类(Dog,Car,Restaurant).py
5,297
4.09375
4
#!/usr/bin/env python # coding: utf-8 # # 类 # ## 创建和使用类 # 与C++的类雷同,都是面向对象编程 # ### 创建Dog类 # In[8]: #dog.py class Dog(): """The attempt to simulate a puppy""" def __init__(self,name,age): """Initialization function""" self.name = name self.age =age def sit(self): """模拟小狗蹲下""" print(self.name.title() + " is now sitting.") def roll_over(self): """模拟小狗打滚""" print(self.name.title() + " is now rolling over.") # ### 根据类创建实例 # In[15]: my_dog = Dog('willie',6) print("My dog's name is " + my_dog.name.title() + '.') print("My dog is " + str(my_dog.age) + ' years old.') # In[17]: my_dog.sit() my_dog.roll_over() # In[18]: your_dog = Dog("lucy",3) # In[19]: your_dog.sit() # ### trying # In[28]: class Restaurant(): def __init__(self,restaurant_name,cuisine_type): self.name = restaurant_name self.type = cuisine_type self.number_served = 0 def incretment_number(self,numbers): if self.number_served + numbers < 0: print("The number of guests is wrong!") else: self.number_served += numbers def set_number_served(self): print("At present, the number of people eating in the restaurant is: " + str(self.number_served)) def describe_restaurant(self): print("It's a " + self.type + " restuarant named " + self.name + '.') # In[30]: New_restaurant = Restaurant("Blue","beef noodle") New_restaurant.incretment_number(20) #New_restaurant.incretment_number(-30) New_restaurant.describe_restaurant() New_restaurant.set_number_served() # ## 使用类和实例 # ### Car.py # In[4]: class Car(): """一次模拟汽车的简单测试""" def __init__(self,make,model,year): """初始化描述汽车的属性""" self.make = make self.model = model self.year = year def get_desciptive_name(self): """return the clearly desciptive message""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() my_new_car = Car('audi','A6',2010) print(my_new_car.get_desciptive_name()) # ### 给属性指定默认值 # In[21]: class Car(): """一次模拟汽车的简单测试""" def __init__(self,make,model,year): """初始化描述汽车的属性""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_desciptive_name(self): """return the clearly desciptive message""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """打印一条指出汽车里程的信息""" print("This car has " + str(self.odometer_reading) + " mile on it.") def update_odometer(self,milage): """将里程表读数设置为指定的值""" """禁止将里程表读数进行回调""" if milage >= self.odometer_reading: self.odometer_reading = milage else: print("You can't roll back the odometer!") def increment_odometer(self,miles): if miles < 0: print("You can't roll back the odometer!") else: self.odometer_reading += miles my_new_car = Car('audi','A6',2010) print(my_new_car.get_desciptive_name()) my_new_car.read_odometer() # ### 修改属性的值 # #### 1.直接修改属性值 # In[22]: my_new_car = Car('audi','A6',2010) print(my_new_car.get_desciptive_name()) my_new_car.odometer_reading = 23 my_new_car.read_odometer() # #### 2.通过方法修改属性的值 # In[23]: my_new_car.update_odometer(16) my_new_car.read_odometer() # >可对方法update_odometer()进行扩展,使其在修改里程表读数是做些额外得工作,比如禁止任何人将表里的里程读数进行回调 # # In[24]: my_new_car.update_odometer(10) # #### 3.通过方法对属性值进行递增 # In[25]: my_new_car.increment_odometer(2500) my_new_car.read_odometer() # ## trying # In[34]: class User(): """记录客户的姓名即其他基本信息""" def __init__(self,frist_name,last_name,gender,age): self.frist_name = frist_name self.last_name = last_name self.gender = gender self.age = age self.login_attempts = 0 def descirptive_user(self): formatted_name = self.frist_name + ' ' + self.last_name print("Formatted_name: " + formatted_name + "\tGender: " + self.gender + "\tAge: " + str(self.age)) def increment_login_attempts(self): self.login_attempts += 1 def check_login_attempts(self): print("The number of user logins :" + str(self.login_attempts)) def reset_login_attempts(self): self.login_attempts = 0 Guest1 = User('David','Brewn','female',24) Guest1.descirptive_user() Guest1.increment_login_attempts() Guest1.check_login_attempts() Guest1.reset_login_attempts() Guest1.check_login_attempts() # In[ ]:
53f2f7b11acad8a6713ea2daec946b551aeb3c96
abdullahmehboob20s/Python-learning
/chapter-12-advanced-python/9-enumerate.py
179
3.8125
4
import os os.system("cls") # if you want to access the "index" in for loop list1 = [3,12,32,True,"abdullah mehboob"] for index,item in enumerate(list1) : print(f"{index+1}) {item}")
a34841d403c7efcf789f73e5f0e1c9ab0295271d
RaviPrakashMP/Python-programming-practise
/S01Q01.py
65
3.703125
4
name = input("Enter the user name:") print("Hello",name,"!!!")
2c9a7484835e765d1a96d0358e7c5d40dab48512
nikhilsanghi/CNN_Codes
/Keras_Tutorial_v2a.py
15,970
4.03125
4
# coding: utf-8 # # Keras tutorial - Emotion Detection in Images of Faces # # Welcome to the first assignment of week 2. In this assignment, you will: # 1. Learn to use Keras, a high-level neural networks API (programming framework), written in Python and capable of running on top of several lower-level frameworks including TensorFlow and CNTK. # 2. See how you can in a couple of hours build a deep learning algorithm. # # #### Why are we using Keras? # # * Keras was developed to enable deep learning engineers to build and experiment with different models very quickly. # * Just as TensorFlow is a higher-level framework than Python, Keras is an even higher-level framework and provides additional abstractions. # * Being able to go from idea to result with the least possible delay is key to finding good models. # * However, Keras is more restrictive than the lower-level frameworks, so there are some very complex models that you would still implement in TensorFlow rather than in Keras. # * That being said, Keras will work fine for many common models. # ## <font color='darkblue'>Updates</font> # # #### If you were working on the notebook before this update... # * The current notebook is version "v2a". # * You can find your original work saved in the notebook with the previous version name ("v2"). # * To view the file directory, go to the menu "File->Open", and this will open a new tab that shows the file directory. # # #### List of updates # * Changed back-story of model to "emotion detection" from "happy house." # * Cleaned/organized wording of instructions and commentary. # * Added instructions on how to set `input_shape` # * Added explanation of "objects as functions" syntax. # * Clarified explanation of variable naming convention. # * Added hints for steps 1,2,3,4 # ## Load packages # * In this exercise, you'll work on the "Emotion detection" model, which we'll explain below. # * Let's load the required packages. # In[1]: import numpy as np from keras import layers from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D from keras.models import Model from keras.preprocessing import image from keras.utils import layer_utils from keras.utils.data_utils import get_file from keras.applications.imagenet_utils import preprocess_input import pydot from IPython.display import SVG from keras.utils.vis_utils import model_to_dot from keras.utils import plot_model from kt_utils import * import keras.backend as K K.set_image_data_format('channels_last') import matplotlib.pyplot as plt from matplotlib.pyplot import imshow get_ipython().magic('matplotlib inline') # import numpy as np # from keras import layers # from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D # from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPool2D, GlobalAveragePooling2D # from keras.models import Model # from keras.preprocessing imprt image # from keras.utils import layer_utils # from keras.utils.data_utils import get_file # from keras.application.imagenet_utils import preprocess_input # import pydot # from IPython.display import SVG # from keras.utils.vis_utils import model_to_dot # from keras.utils import plot_model # from kt_utils import * # import keras.backend as K # **Note**: As you can see, we've imported a lot of functions from Keras. You can use them by calling them directly in your code. Ex: `X = Input(...)` or `X = ZeroPadding2D(...)`. # # In other words, unlike TensorFlow, you don't have to create the graph and then make a separate `sess.run()` call to evaluate those variables. # ## 1 - Emotion Tracking # # * A nearby community health clinic is helping the local residents monitor their mental health. # * As part of their study, they are asking volunteers to record their emotions throughout the day. # * To help the participants more easily track their emotions, you are asked to create an app that will classify their emotions based on some pictures that the volunteers will take of their facial expressions. # * As a proof-of-concept, you first train your model to detect if someone's emotion is classified as "happy" or "not happy." # # To build and train this model, you have gathered pictures of some volunteers in a nearby neighborhood. The dataset is labeled. # <img src="images/face_images.png" style="width:550px;height:250px;"> # # Run the following code to normalize the dataset and learn about its shapes. # In[2]: X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset() # Normalize image vectors X_train = X_train_orig/255. X_test = X_test_orig/255. # Reshape Y_train = Y_train_orig.T Y_test = Y_test_orig.T print ("number of training examples = " + str(X_train.shape[0])) print ("number of test examples = " + str(X_test.shape[0])) print ("X_train shape: " + str(X_train.shape)) print ("Y_train shape: " + str(Y_train.shape)) print ("X_test shape: " + str(X_test.shape)) print ("Y_test shape: " + str(Y_test.shape)) # **Details of the "Face" dataset**: # - Images are of shape (64,64,3) # - Training: 600 pictures # - Test: 150 pictures # In[ ]: # ## 2 - Building a model in Keras # # Keras is very good for rapid prototyping. In just a short time you will be able to build a model that achieves outstanding results. # # Here is an example of a model in Keras: # # ```python # def model(input_shape): # """ # input_shape: The height, width and channels as a tuple. # Note that this does not include the 'batch' as a dimension. # If you have a batch like 'X_train', # then you can provide the input_shape using # X_train.shape[1:] # """ # # # Define the input placeholder as a tensor with shape input_shape. Think of this as your input image! # X_input = Input(input_shape) # # # Zero-Padding: pads the border of X_input with zeroes # X = ZeroPadding2D((3, 3))(X_input) # # # CONV -> BN -> RELU Block applied to X # X = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X) # X = BatchNormalization(axis = 3, name = 'bn0')(X) # X = Activation('relu')(X) # # # MAXPOOL # X = MaxPooling2D((2, 2), name='max_pool')(X) # # # FLATTEN X (means convert it to a vector) + FULLYCONNECTED # X = Flatten()(X) # X = Dense(1, activation='sigmoid', name='fc')(X) # # # Create model. This creates your Keras model instance, you'll use this instance to train/test the model. # model = Model(inputs = X_input, outputs = X, name='HappyModel') # # return model # ``` # In[ ]: # #### Variable naming convention # # * Note that Keras uses a different convention with variable names than we've previously used with numpy and TensorFlow. # * Instead of creating unique variable names for each step and each layer, such as # ``` # X = ... # Z1 = ... # A1 = ... # ``` # * Keras re-uses and overwrites the same variable at each step: # ``` # X = ... # X = ... # X = ... # ``` # * The exception is `X_input`, which we kept separate since it's needed later. # #### Objects as functions # * Notice how there are two pairs of parentheses in each statement. For example: # ``` # X = ZeroPadding2D((3, 3))(X_input) # ``` # * The first is a constructor call which creates an object (ZeroPadding2D). # * In Python, objects can be called as functions. Search for 'python object as function and you can read this blog post [Python Pandemonium](https://medium.com/python-pandemonium/function-as-objects-in-python-d5215e6d1b0d). See the section titled "Objects as functions." # * The single line is equivalent to this: # ``` # ZP = ZeroPadding2D((3, 3)) # ZP is an object that can be called as a function # X = ZP(X_input) # ``` # **Exercise**: Implement a `HappyModel()`. # * This assignment is more open-ended than most. # * Start by implementing a model using the architecture we suggest, and run through the rest of this assignment using that as your initial model. * Later, come back and try out other model architectures. # * For example, you might take inspiration from the model above, but then vary the network architecture and hyperparameters however you wish. # * You can also use other functions such as `AveragePooling2D()`, `GlobalMaxPooling2D()`, `Dropout()`. # # **Note**: Be careful with your data's shapes. Use what you've learned in the videos to make sure your convolutional, pooling and fully-connected layers are adapted to the volumes you're applying it to. # In[3]: # GRADED FUNCTION: HappyModel def HappyModel(input_shape): """ Implementation of the HappyModel. Arguments: input_shape -- shape of the images of the dataset (height, width, channels) as a tuple. Note that this does not include the 'batch' as a dimension. If you have a batch like 'X_train', then you can provide the input_shape using X_train.shape[1:] """ X_input= Input(input_shape) X= ZeroPadding2D((3,3))(X_input) X=Conv2D(32,(7,7),strides=(1,1),name="conv0")(X) X=BatchNormalization(axis=3,name="bc0")(X) X=Activation("relu")(X) X=MaxPooling2D((2,2),name="maxPool0")(X) X=Flatten()(X) X=Dense(1,activation='sigmoid',name='fc0')(X) model=Model(inputs=X_input, outputs=X ,name='HappyModel') # return model # Returns: # model -- a Model() instance in Keras """ ### START CODE HERE ### # Feel free to use the suggested outline in the text above to get started, and run through the whole # exercise (including the later portions of this notebook) once. The come back also try out other # network architectures as well. ### END CODE HERE ### """ return model # You have now built a function to describe your model. To train and test this model, there are four steps in Keras: # 1. Create the model by calling the function above # # 2. Compile the model by calling `model.compile(optimizer = "...", loss = "...", metrics = ["accuracy"])` # # 3. Train the model on train data by calling `model.fit(x = ..., y = ..., epochs = ..., batch_size = ...)` # # 4. Test the model on test data by calling `model.evaluate(x = ..., y = ...)` # # If you want to know more about `model.compile()`, `model.fit()`, `model.evaluate()` and their arguments, refer to the official [Keras documentation](https://keras.io/models/model/). # #### Step 1: create the model. # **Hint**: # The `input_shape` parameter is a tuple (height, width, channels). It excludes the batch number. # Try `X_train.shape[1:]` as the `input_shape`. # In[4]: # print(X_train.shape[1:]) # In[5]: ### START CODE HERE ### (1 line) happyModel = HappyModel(X_train.shape[1:]) ### END CODE HERE ### # #### Step 2: compile the model # # **Hint**: # Optimizers you can try include `'adam'`, `'sgd'` or others. See the documentation for [optimizers](https://keras.io/optimizers/) # The "happiness detection" is a binary classification problem. The loss function that you can use is `'binary_cross_entropy'`. Note that `'categorical_cross_entropy'` won't work with your data set as its formatted, because the data is an array of 0 or 1 rather than two arrays (one for each category). Documentation for [losses](https://keras.io/losses/) # In[6]: ### START CODE HERE ### (1 line) happyModel.compile(optimizer="adam",loss='binary_crossentropy',metrics=["accuracy"]) ### END CODE HERE ### # #### Step 3: train the model # # **Hint**: # Use the `'X_train'`, `'Y_train'` variables. Use integers for the epochs and batch_size # # **Note**: If you run `fit()` again, the `model` will continue to train with the parameters it has already learned instead of reinitializing them. # In[ ]: ### START CODE HERE ### (1 line) happyModel.fit(x=X_train,y=Y_train,epochs=10,batch_size=16) ### END CODE HERE ### # #### Step 4: evaluate model # **Hint**: # Use the `'X_test'` and `'Y_test'` variables to evaluate the model's performance. # In[10]: ### START CODE HERE ### (1 line) preds = happyModel.evaluate(x=X_test,y=Y_test) ### END CODE HERE ### print() print ("Loss = " + str(preds[0])) print ("Test Accuracy = " + str(preds[1])) # #### Expected performance # If your `happyModel()` function worked, its accuracy should be better than random guessing (50% accuracy). # # To give you a point of comparison, our model gets around **95% test accuracy in 40 epochs** (and 99% train accuracy) with a mini batch size of 16 and "adam" optimizer. # #### Tips for improving your model # # If you have not yet achieved a very good accuracy (>= 80%), here are some things tips: # # - Use blocks of CONV->BATCHNORM->RELU such as: # ```python # X = Conv2D(32, (3, 3), strides = (1, 1), name = 'conv0')(X) # X = BatchNormalization(axis = 3, name = 'bn0')(X) # X = Activation('relu')(X) # ``` # until your height and width dimensions are quite low and your number of channels quite large (≈32 for example). # You can then flatten the volume and use a fully-connected layer. # - Use MAXPOOL after such blocks. It will help you lower the dimension in height and width. # - Change your optimizer. We find 'adam' works well. # - If you get memory issues, lower your batch_size (e.g. 12 ) # - Run more epochs until you see the train accuracy no longer improves. # # **Note**: If you perform hyperparameter tuning on your model, the test set actually becomes a dev set, and your model might end up overfitting to the test (dev) set. Normally, you'll want separate dev and test sets. The dev set is used for parameter tuning, and the test set is used once to estimate the model's performance in production. # ## 3 - Conclusion # # Congratulations, you have created a proof of concept for "happiness detection"! # ## Key Points to remember # - Keras is a tool we recommend for rapid prototyping. It allows you to quickly try out different model architectures. # - Remember The four steps in Keras: # # # 1. Create # 2. Compile # 3. Fit/Train # 4. Evaluate/Test # ## 4 - Test with your own image (Optional) # # Congratulations on finishing this assignment. You can now take a picture of your face and see if it can classify whether your expression is "happy" or "not happy". To do that: # # # 1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub. # 2. Add your image to this Jupyter Notebook's directory, in the "images" folder # 3. Write your image's name in the following code # 4. Run the code and check if the algorithm is right (0 is not happy, 1 is happy)! # # The training/test sets were quite similar; for example, all the pictures were taken against the same background (since a front door camera is always mounted in the same position). This makes the problem easier, but a model trained on this data may or may not work on your own data. But feel free to give it a try! # In[18]: ### START CODE HERE ### img_path = 'images/1.jpg' ### END CODE HERE ### img = image.load_img(img_path, target_size=(64, 64)) imshow(img) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) print(happyModel.predict(x)) # ## 5 - Other useful functions in Keras (Optional) # # Two other basic features of Keras that you'll find useful are: # - `model.summary()`: prints the details of your layers in a table with the sizes of its inputs/outputs # - `plot_model()`: plots your graph in a nice layout. You can even save it as ".png" using SVG() if you'd like to share it on social media ;). It is saved in "File" then "Open..." in the upper bar of the notebook. # # Run the following code. # In[19]: happyModel.summary() # In[20]: plot_model(happyModel, to_file='HappyModel.png') SVG(model_to_dot(happyModel).create(prog='dot', format='svg')) # In[ ]:
8dba0d63ed7ab6023c248297d43650eaa758a36f
ShamanKNG/Wizualizacja-Danych
/Lista10/4.py
314
3.640625
4
import matplotlib.pyplot as plt import numpy as np x = np.arange(1, 31, 0.1) plt.plot(x,np.sin(-x),"orange", label='sin(x)') plt.plot(x,np.sin(x)+2,"blue", label='sin(x)') plt.axis([1, 31, -1.5, 3.5]) plt.xlabel('x') plt.ylabel('sin(x)') plt.title("Sinus i Sinus") plt.legend() plt.grid() plt.show()
10b030c17ce0099a259d6f468aefa307d01f15d9
Shilpa-T/Python
/pythonprog/removeduplicate.py
1,136
3.90625
4
""" Given an array of integers, 1 <= a[i] <=n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. """ def removeDuplicates(nums): """ this function returns list of duplicate delement :param nums: :return: list of duplicate element """ a_dict ={} l_list = [] for i in nums: a_dict[i]=a_dict.get(i,0)+1 for k,v in a_dict.items(): if v > 1: l_list.append(k) else: l_list.append(k) return l_list def removeduplicate(nums): s = [] for i in nums: if i not in s: s.append(i) return s #HW--write s code to remove duplicate in i/p list def removeduplicates_ip(nums): nums = set(nums) return list(nums) def removeduplicates_dict(nums): print dict.fromkeys(nums).keys() nums = [5,3,2,5,6,2,1] print removeDuplicates(nums) print removeduplicate(nums) print removeduplicates_ip(nums) removeduplicates_dict(nums) print "**************************************" seq = [1,2,3,'a', 'a', 1,2] print dict.fromkeys(seq).keys()
583fe103b6fa2e7c76aeec03b2e47460f07a91a8
fawwazbf24/Tutorial-python-mongga
/tutorial2.py
427
3.859375
4
#Fawwaz Byru Fitrianto #program tutorial angka dan boolean #2-11-2020 import math a=24 b=24.5 print(type(a)) a=float(a) print(a) print(type(a)) print() b=int(b) print(b) print() c=a/b print(int(c)) print(a is b) print(a == b) print() counter=0 string = "saya suka kue coklat" print("saya" in string) for f in string: if(f=="s"): counter+=1 print(counter) print() aa=3 bb=2.0 cc=aa**bb dd=math.pow(aa,bb) print(cc) print(dd)
8e707074646e76b014a965160726b353ecad0d0f
imalikova/PythonLearn
/MODULE 1/What time is it?.py
412
4.15625
4
input_time = int(input("What time is it? ")) if input_time > 0 and input_time <= 3: print("Good night") elif input_time > 3 and input_time < 12: print("Good morning") elif input_time >= 12 and input_time <= 16: print("Good afternoon") elif input_time > 16 and input_time <= 24: print("Good evening") elif input_time <= 0 or input_time > 24: print("Error") else: print('Bad input')
dbb58953c8a20c20c2f6ccf796a2cd29595515fe
Leonardo612/Entra21_Leonardo
/Aula04/exercicios/print/exercicio02.py
256
3.5
4
# Exercicio 2 # # Imprima o menu de uma aplicação de cadastro de pessoas # # O menu deve conter as opções de Cadastrar, Alterar, listar pessoas, alem da opção sair print("Cadastrar: ") print("Alterar: ") print("Listar pessoas: ") print("Sair")
c6cfe916d73b73c2f9a82c5b74dd2fd170b1c0c6
FernCarrera/Localization
/test_study.py
511
3.6875
4
import study import unittest import numpy as np class TestStudy(unittest.TestCase): def test_normalize_angle(self): test_num = 3*np.pi value = study.normalize_angle(test_num) # about 370deg #while test_num > np.pi: # test_num -= 2.0*np.pi test_num = test_num % (2.0*np.pi) if (test_num<0): test_num+= (2.0*np.pi) print(test_num) self.assertEqual(value,test_num) if __name__ == '__main__': unittest.main()
023d33682cc14cf1917b0f0c2ab9169b264879df
kartikhans/competitiveProgramming
/Number_compliment.py
207
3.65625
4
def findComplement(num): kaim=bin(num)[2:] sup="" for i in kaim: if(i=='0'): sup+='1' else: sup+='0' return(int(sup,2))
317bef442d3550f09c61d797357378244e1b107b
jawid-mirzad/inlaming
/python/pythonuppgift.py
2,252
3.796875
4
import csv print("Hej och välkommen kontakt information") Val = True Val1 = 0 while Val: Val1 = input(''' Förname [0] Eftername [1] Gmail [2] Mobilnummet [3] Födesldag [4] Välj en av talet !''') if Val1 >= "5": print("Välj ett tal mellan 0 till 5") if Val1 == "0": with open("information.csv" , "r") as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: print(line[0]) val2 = input('''Vill du avsluta eller förtsätta: n för avsluta [n] y för förtsätta [y]''') if val2 == "n": Val = False elif Val1 == "1": with open("information.csv" , "r") as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: print(line[1]) val2 = input('''Vill du avsluta eller förtsätta: n för avsluta [n] y för förtsätta [y]''') if val2 == "n": Val = False elif Val1 == "2": with open("information.csv" , "r") as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: print(line[2]) val2 = input('''Vill du avsluta eller förtsätta: n för avsluta [n] y för förtsätta [y]''') if val2 == "n": Val = False elif Val1 == "3": with open("information.csv" , "r") as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: print(line[3]) val2 = input('''Vill du avsluta eller förtsätta: n för avsluta [n] y för förtsätta [y]''') if val2 == "n": Val = False elif Val1 == "4": with open("information.csv" , "r") as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: print(line[4]) val2 = input('''Vill du avsluta eller förtsätta: n för avsluta [n] y för förtsätta [y]''') if val2 == "n": Val = False
9beb4384c5145d6225a29ab79ce57c44406051fd
mdmohsinalikhan/others
/ProjectEuler/94.py
652
3.640625
4
import math #340000000 perimeters = set() sums = 0 for i in range(2,340000000): if i % 10000000 == 0: print("Finished" + str(i)) if 3*i + 1 <= 1000000000: x = math.sqrt(i*i - ((i+1)/2)*((i+1)/2)) # if x == round(x): x = round(x) if (x-1)*(x-1) + ((i+1)/2)*((i+1)/2) == i*i: print("i+1: " + str(i+1) + " x: " + str(x-1) ) sums = sums + 3*i + 1 elif (x)*(x) + ((i+1)/2)*((i+1)/2) == i*i: print("i+1: " + str(i+1) + " x: " + str(x) ) sums = sums + 3*i + 1 elif (x+1)*(x+1) + ((i+1)/2)*((i+1)/2) == i*i: print("i+1: " + str(i+1) + " x: " + str(x+1) ) sums = sums + 3*i + 1 #print(perimeters) print(sums)
cbe86414dd78bc2223863b104c61979a9137e4d1
AaronWenYang/Principle_pf_Programming
/Assignment/Assignment_1/factorial_base.py
1,329
3.59375
4
from math import factorial as fact import sys try: A = int(input('Input a nonnegative integer :')) if A < 0: raise ValueError except ValueError: print('Incorrect input , giving up . . . ') sys.exit() copyA = A list_n = [] k = 1 n = 0 if A >0: while k in range(1,A): if fact(k) < A < fact(k +1): while k>= 1 and A >= 0 and n in range(0,10) : if fact(k) * n < A < fact(k) * (n+1): A = A - fact(k) * n k = k -1 list_n.append(n) n = 0 elif fact(k) * n == A : list_n.append(n) for num_of_zeros in range(k-1): list_n.append(0) A = A - fact(k) * n k = k - 1 elif A == 0: break else: n += 1 elif fact(k) == A: list_n.append(1) for num_of_zeros in range(k-1): list_n.append(0) break else : k += 1 elif A == 0 : list_n = [0] result_num = '' for idx_list_n in range(len(list_n)): result_num += str(list_n[idx_list_n]) print('Decimal {} reads as {} in factorial base .'.format(copyA,result_num))
647931178701414357995ce455e9c39907ba64c9
NAMARIKO/YasashPython_book
/Lesson5.2_1.2.3.py
301
3.5
4
""" listの基本 """ # %% # Sample_1 print("\n[Sample_1]") list = [80, 60, 22, 50, 75] print(list) # %% # Sample_2 print("\n[Sample_2]") print(list[0]) print(list[1]) print(list[3]) print("listの長さは、", len(list)) # %% # Sample_3 print("\n[Sample_3]") for item in list: print(item)
6685a451f3ee32b9aeb3f507b40b426e9f018ab0
litichevskiydv/PythonStudies
/matrix_v2.py
1,324
3.828125
4
class Matrix: def __init__(self, values): self.values = [[x for x in row] for row in values] self._rows_count = len(self.values) self._columns_count = 0 if self._rows_count == 0 \ else len(self.values[0]) def __str__(self): return '\n'.join('\t'.join(str(x) for x in row) for row in self.values) def __add__(self, other): return Matrix( map( lambda self_row, other_row: map(lambda x, y: x + y, self_row, other_row), self.values, other.values ) ) def __mul__(self, number): return Matrix([[number * x for x in row] for row in self.values]) def __rmul__(self, number): return self.__mul__(number) def size(self): return self._rows_count, self._columns_count def main(): # Task 2 check 1 m = Matrix([[10, 10], [0, 0], [1, 1]]) print(m.size()) # Task 2 check 2 m1 = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) m2 = Matrix([[0, 1, 0], [20, 0, -1], [-1, -2, 0]]) print(m1 + m2) # Task 2 check 3 m = Matrix([[1, 1, 0], [0, 2, 10], [10, 15, 30]]) alpha = 15 print(m * alpha) print(alpha * m) if __name__ == '__main__': main()
aafa57c9e000f8a4c93b094fbe911c8717cd3cc2
alpsarigul/cardiovascular-disease-predictor
/heart_disease_predictor.py
5,207
3.671875
4
# Importing libraries import streamlit as st import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression import os print(os.getcwd()) os.chdir("/Users/mani/Desktop/heart-disease-predictor/app") print(os.getcwd()) # Linking the CSS file def local_css(filename): with open(filename) as f: st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True) local_css("style.css") # Sidebar st.sidebar.title("Input Descriptions") st.sidebar.markdown( "Resting ECG: common procedure used by doctors to check for signs of heart disease. Below are the corresponding numbers and what they mean." ) st.sidebar.markdown("* 0 - Normal") st.sidebar.markdown("* 1 - ST-T wave abnormality") st.sidebar.markdown("* 2 - Probable or definite left ventricular hypertrophy") # Title and project description st.title("Heart Disease Predictor") st.write("Using the Heart Disease Dataset from the University of California Irvine Machine Learning Repository, we trained a logistic regression model that predicts the probability of an individual having heart disease. Below are the respective attributes that were used when training the model.") # Directions st.subheader("Directions:") st.write("Fill in the input fields below to get a prediction") # Age input age = st.number_input(label="Enter your age:", value=0) # Sex input sex = st.selectbox(label="Select your sex:", options=['',"Male", "Female"], format_func=lambda x: 'Select an option' if x == '' else x) # Mapping sex to 1 or 0 if sex == 'Male': sex = 1 else: sex = 0 # Fbs input fbs = st.selectbox('Is your fasting blood sugar above 120 mg/dl?', ['', 'Yes', 'No'], format_func=lambda x: 'Select an option' if x == '' else x) # Mapping fbs to the appropriate value if fbs == 'Yes': fbs = 1 else: fbs = 0 # Ecg input ecg = st.radio(label="What is your resting ECG value(Please refer to the side bar for explanations on what each value represents)?", options=[0, 1, 2]) # Thalach input thalach = st.number_input(label="Enter your maximum heart rate(bpm):", value=0) # Exang input exang = st.selectbox('Do you experience chest pain when exercising?', ['', 'Yes', 'No'], format_func=lambda x: 'Select an option' if x == '' else x) # Mapping exang to the appropriate value if exang == 'Yes': exang = 1 else: exang = 0 # Oldpeak input oldpeak = st.number_input(label="What is your st depression value induced by exercise relative to rest?") # Chest pain input cp = st.selectbox('Do you have chest pain? If so, which option best describes your chest pain?', ['', 'No chest pain', 'Typical angina', 'Atypical angina', 'Non-anginal pain'], format_func=lambda x: 'Select an option' if x == '' else x) if cp == 'Typical angina': cp = 1 elif cp == 'Atypical angina': cp = 2 elif cp == 'Non-anginal pain': cp = 3 elif cp == 'No chest pain': cp = 4 # Ca input ca = st.radio(label='How many major arteries do you have blocked(stained with fluoroscopy)?', options=[0, 1, 2, 3]) # Thal input thal = st.selectbox('Do you have thalassaemia? If so, is it reversible or a fixed defect?', ['', 'I do not have thalassaemia', 'Reversible', 'Fixed defect'], format_func=lambda x: 'Select an option' if x == '' else x) if thal == 'I do not have thalassaemia': thal = 3 elif thal == 'Fixed defect': thal = 6 elif thal == 'Reversible': thal = 7 # Creating a function that will train the model and cache it @st.cache def train_model(): """ Trains the logistic regression model and caches it return: A trained logistic regression model """ # Importing the Cleveland data df_cleveland = pd.read_csv("../data/cleveland_data.csv", index_col=0) # Removing the unnecessary features df_cleveland.drop(['trest', 'chol', 'slope'], axis=1, inplace=True) # Separting the data into features and labels X = df_cleveland.loc[:, df_cleveland.columns != "num"] y = df_cleveland["num"] # Creating a logistic regression model lr_classifier = LogisticRegression(tol=1e-6, solver='liblinear', max_iter=200,) # Training the model lr_classifier.fit(X, y) # Return the model return lr_classifier model = train_model() # Putting the user input in an array to pass to the predict function input = [[ age, sex, cp, fbs, ecg, thalach, exang, oldpeak, ca, thal ]] # Only getting a prediction if all inputs fields have been completed # Counter that keeps track of the number of completed input fields is_empty = 0 for inner in input: for value in inner: if value != '': is_empty += 1 #st.write(is_empty) #st.write(input) # Button for form submission button = st.button(label='Submit') # Getting a prediction from the model based on the user input if is_empty == 10 and button: prediction = model.predict_proba(input) proba = 100 * round(prediction[0][1], 2) proba = str(proba) st.write("The probability of having heart disease is " + proba + "%") elif is_empty != 10 and button: st.write("Error: Please make sure all the input fields are filled in.")
afcf2857e7c70eae703b3e124ca229a11ef576da
lingzt/PythonPractice
/week3/E5.py
520
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 16 20:35:18 2017 @author: lingtoby """ def applyEachTo(L, x): result = [] for i in range(len(L)): #print(L[i](x)) l 里面是所有公式 result.append(L[i](x)) return result def square(a): return a*a def halve(a): return a/2 def inc(a): return a+1 print(applyEachTo([inc, square, halve, abs], -3)) print(applyEachTo([inc, square, halve, abs], 3.0)) print(applyEachTo([inc, max, int], -3))
a8d1090a9cf76f9f2fc2dd1a5ccb93049a36c238
Eric-Lingren/sandboxes
/bryan-sandbox/afs-200/setup/week-1/morning/main.py
841
3.609375
4
#! Week 1 #* Overview of Python (10m) #* Walkthrough of installing and using Python with VS Code (10-15m) #* Introduction to Python variables and input/output (20m) #* Introduction to Python basic operators (arithmetic, comparison and logical) (10m) #* Introduction to if then else statements in Python (10m) #* Why Python ? # Web Development # Scripting # Games (Pygame) - Civ IV, Battlefield 2 # Web Scraping # Data Science # Machine Learning # Mobile Apps (Kivy) #* Output/Running code: #* Variables/Inputs: #* Data Types: # Strings # Numbers - float, int # Booleans # Lists # Tuples # Dicts #* Mathematical Operators: # + # - # / # * # % #* Comparison Operators # == # != # > # < # >= # <= #* Logical Operators # and # or # not #* Identity Opperators # is # is not #* Membership Opperators # in # not in #* If else
ccfe89c011750e1e5511eb1fcca6712fc4fcd4d8
Liam30acre/astr-119-hw-1-Liam-Thirtyacre
/variables_and_loops.py
531
4.1875
4
import numpy as np def main(): i = 0 #integer n = 10 x = 119.0 #floating point num declared w a "." # we use numpy to declare arrays quickly y = np.zeros(n,dtype=float) #declares 10 zeros as floats using np #we can iterate through the elements of y by passing an index for i in range(n): #i in range [0, n-1] y[i] = 2.0 * float(i) + 1.0 # set y = 2i+1 as float #we can also iterate through an array for y_element in y: print(y_element) #execute the main function if __name__ == "__main__": main()
0ef244642d3b906216e1af08b2f007015a79847e
jaquelinepeluzo/Python-Curso-em-Video
/aula06a.py
273
3.765625
4
#n1 = input('digite um valor: ') #print(type(n1)) #n2 = int(input('digite um valor: ')) #print(type(n2)) n3 = int(input('digite um número: ')) n4 = int(input('digite outro numero: ')) soma = int(n3+n4) print('a soma entre {} e {} é: {}'.format(n3, n4, soma))
e77736c228f5be996b31710ec8b3b982d1226e4d
L-omit/Python-basics
/assignment10.py
220
4.09375
4
def reverse(x): x = x[::-1] # alku ja loppuarvoja ei ole maaritelty ja koska luku on negatiivinen niin komento ::-1 tulostaa koko listan mutta menee yksi kerrallaan takaperin return x x = reverse([1,2,3,4,5]) print(x)
090fb9c46d6118bb29b11ca9c0b4d329e00526d6
RainFZY/LeetCode-Practice
/125.验证回文串.py
1,020
3.609375
4
# # @lc app=leetcode.cn id=125 lang=python3 # # [125] 验证回文串 # # @lc code=start class Solution: def isPalindrome(self, s: str) -> bool: res = "" for char in s: # 字母 if char.isalpha(): res += char.lower() # 数字 if char.isdigit(): res += char # if ''.join(reversed(res)) == res return True if res[::-1] == res else False # 双指针 class Solution: def isPalindrome(self, s: str) -> bool: left, right = 0, len(s) - 1 while left < right: # 跳过其他非字母/数字字符,排除干扰 # isalnum: num + alpha while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True # @lc code=end
969f6558289917df5034fb88cf3435c191b72491
connergriffin/personal
/cse1284/printname.py
187
4.0625
4
# asks for name input and then displays name name = input('hello what is your name? ') # requests users input print('hello', name, 'nice to meet you') # prints their name
4fde32b356caa85f0420fbda38b877122c246c0d
Rajmeet/Python-Folder-Hack
/Main Virus.py
413
3.515625
4
import os #Creating Multiple folders def createFolder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print("Making Directory..." + directory) #Virus Creation """ i = 1 while True: if(i > 0): print("Hello") """ a = range(0,10) for x in a: print(str(x)) createFolder(x) No newline at end of file
45d1df16fc22ae87dd92c8b1f16c1b1b8ba17336
tomlxq/ps_py
/leetcode/test_RecursiveDemo.py
685
3.515625
4
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest from RecursiveDemo import RecursiveDemo class TestRecursiveDemo(unittest.TestCase): def test_predict_the_winner(self): self.assertFalse(RecursiveDemo.PredictTheWinner(self, [1, 5, 2])) self.assertTrue(RecursiveDemo.PredictTheWinner(self, [1, 5, 233, 7])) self.assertFalse(RecursiveDemo.PredictTheWinner4(self, [1, 5, 2])) self.assertTrue(RecursiveDemo.PredictTheWinner4(self, [1, 5, 233, 7])) if __name__ == '__main__': # verbosity=*:默认是1;设为0,则不输出每一个用例的执行结果;2-输出详细的执行结果 unittest.main(verbosity=1) assert False
bea5e73cef5008ac0c3ea82b87b0a04872632f15
aquilesC/experimentor
/experimentor/models/properties.py
13,357
3.640625
4
""" Properties ========== Every model in Experimentor has a set of properties that define their state. A camera has, for example, an exposure time, a DAQ card has a delay between data points, and an Experiment holds global parameters, such as the number of repetitions a measurement should take. In many situations, the parameters are stored as a dictionary, mainly because they are easy to retrieve from a file on the hard drive and to access from within the class. We want to keep that same approach, but adding extra features. Features of Properties ---------------------- Each parameter stored on a property will have three values: new_value, value, old_value, which represent the value which will be set, the value that is currently set and the value that was there before. In this way it is possible to just update on the device those values that need updating, it is also possible to revert back to the previously known value. Each value will also be marked with a flag to_update in case the value was changed, but not yet transmitted to the device. This allows us to collect all the values we need, for example looping through a user interface, reading a config file, and applying only those needed whenever desired. The Properties have also another smart feature, achieved through linking. Linking means building a relationship between the parameters stored within the class and the methods that need to be executed in order to get or set those values. In the linking procedure, we can set only getter methods for read-only properties, or both methods. A general apply function then allows to use the known methods to set the values that need to be updated to the device. Future Roadmap -------------- We can consider forcing methods to always act on properties defined as new/known/old in order to use that information as a form of cache and validation strategy. :license: MIT, see LICENSE for more details :copyright: 2021 Aquiles Carattino """ import warnings from typing import List from experimentor.lib.log import get_logger from experimentor.models import BaseModel from experimentor.models.exceptions import LinkException, PropertyException class Properties: """ Class to store the properties of models. It keeps track of changes in order to monitor whether a specific value needs to be updated. It also allows to keep track of what method should be triggered for each update. """ def __init__(self, parent: BaseModel, **kwargs): self._parent = parent self._properties = dict() self._links = dict() self.logger = get_logger() if kwargs: for key, value in kwargs.items(): self.__setitem__(key, value) def __setitem__(self, key, value): if key not in self._properties: self._properties.update({ key: { 'new_value': value, 'value': None, 'old_value': None, 'to_update': True } }) else: self._properties[key].update({ 'new_value': value, 'to_update': True, }) def __getitem__(self, item): if isinstance(item, int): key = list(self._properties.keys())[item] return {key: self._properties[key]['value']} if item in self._properties: return self._properties[item]['value'] if item in self._parent._features: return None raise KeyError(f'Property {item} unknown') def all(self): """ Returns a dictionary with all the known values. Returns ------- properties : dict All the known values """ p = dict() for key, value in self._properties.items(): if key: p.update({ key: value['value'], }) return p def update(self, values: dict): """Updates the values in the same way the update method of a dictionary works. It, however, stores the values as a new value, it does not alter the values stored. For updating the proper values use :func:`self.upgrade`. After updating the values, use :func:`self.apply_all` to send the new values to the device. """ for key, value in values.items(): self.__setitem__(key, value) def upgrade(self, values, force=False): """This method actually overwrites the values stored in the properties. This method should be used only when the real values generated by a device are known. It will change the new values to None, it will set the value to value, and it will set the ``to_update`` flag to false. Parameters ---------- values: dict Dictionary in the form {property: new_value} force: bool If force is set to True, it will create the missing properties instead of raising an exception. """ for key, value in values.items(): if key not in self._properties: if not force: raise PropertyException(f'Trying to upgrade {key} but is not a listed property') self.__setitem__(key, value) self._properties[key].update({ 'new_value': None, 'value': value, 'to_update': False, }) def fetch(self, prop): """ Fetches the desired property from the device, provided that a link is available. """ if prop in self._links: getter = self._links[prop][0] if callable(getter): value = getter() else: value = getattr(self._parent, getter) self.logger.debug(f'Fetched {prop} -> {value}') return value else: # It may be a Model Property that has not been linked yet if prop in self._parent._features: self._links.update({prop: [prop, prop]}) return self.fetch(prop) self.logger.error(f'{prop} is not a valid property') raise KeyError(f'{prop} is not a valid property') def fetch_all(self): """ Fetches all the properties for which a link has been established and updates the value. This method does not alter the to_update flag, new_value, nor old_value. """ self.logger.info(f'Fetching all properties of {self._parent}') keys = {key for key in self._links} | {key for key in self._parent._features} for key in keys: value = self.fetch(key) self.upgrade({key: value}, force=True) def apply(self, property, force=False): """ Applies the new value to the property. This is provided that the property is marked as to_update, or forced to be updated. Parameters ---------- property: str The string identifying the property force: bool (default: False) If set to true it will update the propery on the device, regardless of whether it is marked as to_update or not. """ if property in self._links: if property in self._properties: property_value = self.get_property(property) if property_value['to_update'] or force: setter = self._links[property][1] if setter is not None: property_value['old_value'] = property_value['value'] new_value = property_value['new_value'] if callable(setter): value = setter(new_value) else: self._parent.__setattr__(setter, new_value) value = None if value is None: value = self.fetch(property) self.upgrade({property: value}) else: self.logger.warning(f'Trying to change the value of {property}, but it is read-only') else: self.logger.info(f'{property} will not be updated') else: raise PropertyException('Trying to update a property which is not registered') else: # The property may have been defined as a Model Property, we can add it to the links if property in self._parent._features: self._links.update({property: [property, property]}) self.apply(property) else: raise LinkException(f'Trying to update {property}, but it is not linked to any setter method') def apply_all(self): """ Applies all changes marked as 'to_update', using the links to methods generated with :meth:~link """ values_to_update = self.to_update() for key, values in values_to_update.items(): self.apply(key) def get_property(self, prop): """Get the information of a given property, including the new value, value, old value and if it is marked as to be updated. Returns ------- prop : dict The requested property as a dictionary """ return self._properties[prop] def to_update(self): """Returns a dictionary containing all the properties marked to be updated. Returns ------- props : dict all the properties that still need to be updated """ props = {} for key, values in self._properties.items(): if values['to_update']: props[key] = values return props def link(self, linking): """Link properties to methods for update and retrieve them. Parameters ----------- linking : dict Dictionary in where information is stored as parameter=>[getter, setter], for example:: linking = {'exposure_time': [self.get_exposure, self.set_exposure]} In this case, ``exposure_time`` is the property stored, while ``get_exposure`` is the method that will be called for getting the latest value, and set_exposure will be called to set the value. In case set_exposure returns something different from None, no extra call to get_exposure will be made. """ for key, value in linking.items(): if key in self._links and self._links[key] is not None: raise LinkException(f'That property is already linked to {self._links[key]}. Please, unlink first') if not isinstance(value, list): value = [value, None] else: if len(value) == 1: value.append(None) elif len(value) > 2: raise PropertyException(f'Properties only accept setters and getter, trying to link {key} with {len(value)} methods') getter = getattr(self._parent, value[0]) getter = getter if callable(getter) else value[0] setter = getattr(self._parent, value[1]) if value[1] else None setter = setter if callable(setter) else value[1] self._links[key] = [getter, setter] def unlink(self, unlink_list): """ Unlinks the properties and the methods. This is just to prevent overwriting linkings under the hood and forcing the user to actively unlink before linking again. Parameters ---------- unlink_list : list List containing the names of the properties to be unlinked. """ for link in unlink_list: if link in self._links: self._links[link] = None else: warnings.warn('Unlinking a property which was not previously linked.') def autolink(self): """ Links the properties defined as :class:`~ModelProp` in the models using their setters and getters. """ for prop_name, prop in self._parent._features.items(): if prop.fset: self.link({ prop_name: [prop.fget.__name__, prop.fset.__name__] }) else: self.link({ prop_name: prop.fget.__name__ }) @classmethod def from_dict(cls, parent, data): """Create a Properties object from a dictionary, including the linking information for methods. The data has to be passed in the following form: {property: [value, getter, setter]}, where `getter` and `setter` are the methods used by :meth:~link. Parameters ---------- parent : class to which the properties are attached data : dict Information on the values, getter and setter for each property """ parameters = dict() links = dict() for key, values in data.items(): parameters.update({ key: values[0] }) links.update({ key: values[1:] }) props = cls(parent, **parameters) props.link(links) return props def __repr__(self): return repr(self.all())
81f906cf5a253e12d47f11d650288e75119fd63e
The-bug-err/ProjectEuler
/LargestPrimeFactor.py
688
4.03125
4
""" Author: Vivek Rana Usage : Just run the script in a Python enabled computer. Date : 12-Aug-2016 """ def findPrime(N): while( N%2 == 0): N = N//2 if N == 1: return 2 i = 3 sqrtN = int(N**0.5) while(i<=sqrtN and i<N): if (N%i == 0): N = N//i i = 3 else: i += 2 if N > 2: return N else: return i def main(): for T in range(int(input("Test cases : "))): N = int(input("Number "+str(T+1)+" : ")) print(findPrime(N)) return if __name__ == '__main__': #IF the script is called from cmd or directly executed main() input('Press any key to exit.')
d143b11586c271b9d2fa10071cfb1d3f63ab380a
sunRainPenguin/Python-samples
/threeBodyGuards.py
426
3.5
4
import urllib2 import re def getHtmlPage(url): return urllib2.urlopen(urllib2.Request(url)).read() def getSmallLetters(src): matchList = re.findall('[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]',src) return ''.join(matchList) url = "http://www.pythonchallenge.com/pc/def/equality.html" page = getHtmlPage(url) rstList = re.findall('<!--\s+(.*)\s+-->',page,re.S) ss = rstList[0] result = getSmallLetters(ss) print result
df8dd163768355cf1d1e938d75aea1944d03ca10
domishana/Domi
/humanplayer.py
2,356
3.75
4
import player class HumanPlayer(player.Player): def __init__(self, game): super().__init__(game) self.isHuman = 1 def what_coin_play(self): number = int(input()) if number == -1: return -1 self.playcard(number, 'right') return False def what_action(self): number = int(input()) if number == -1: self.phaseend() return self.playcard(number, 'right') def what_buy(self): number = int(input()) if number == -1: self.phaseend() return self.buycard(number) def answer_yn(self): print("y/n") flag = 1 while flag: answer = input() flag = self.input_y_or_n(answer) return answer def input_y_or_n(self, answer): if answer == 'y' or answer == 'n': return 0 print("yまたはnで答えてください") return 1 def what_gain_undercost(self, number): print("{0}コスト以下のカードを獲得します".format(number)) flag = 1 while flag: answer = int(input()) place = self.gameinfo.get_supply(answer) flag = self.is_cost_gainable(answer, place, number) def what_gain_undercost_treasure(self, number): print("{0}コスト以下の財宝カードを獲得します".format(number)) flag = 1 while flag: answer = int(input()) place = self.gameinfo.get_supply(answer) if not hasattr(place, 'istreasure'): print("財宝カードを選んでください") continue flag = self.is_cost_gainable(answer, place, number) def is_cost_gainable(self, answer, place, number): if place.cost <= number: self.gaincard(answer) return 0 print("コストが高すぎます") return 1 def pop_from_hand(self): self.print_hand() answer = int(input()) if answer == -1: return -1 card = self.hand_pop(answer) return card def choose_from_hand(self): self.print_hand() answer = int(input()) if answer == -1: return -1 card = self.pickup_from_hand(answer) return card
50a8db7185b45e85c3800aed3e7329f4abc52aac
BryanLinton/Python_Dojo
/flask/flask_fundamentals/understanding_routing/routing.py
1,247
3.953125
4
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/dojo') def dojo(): return 'Dojo!' @app.route('/say/<name>') def say_name(name): return 'Hi ' + name + '!' @app.route('/repeat/<i>/<word>') def repeat(i, word): print('words') return word * int(i) if __name__=="__main__": app.run(debug=True) Understanding Routing tc 7/2019 2789-understanding-routing README.md understanding_routing.py from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "Hello World" @app.route('/dojo') def dojo(): return "Dojo" @app.route('/say/<name>') def say_name(name): if type(name) == str: return "Hi {}".format(name) else: return "Strings Only" @app.route('/repeat/<num>/<word>') def repeat(num, word): if num.isdigit() and type(word) == str: return word * int(num) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return 'Sorry! No response. Try again.' if __name__ == '__main__': app.run(debug=True)
a52075e7505651413559dac6aa1cb2d330ebc77c
archDeaconstructor/cs4660-fall-2017
/cs4660/files.py
1,326
3.640625
4
"""Files tests simple file read related operations""" import os import csv class SimpleFile(object): """SimpleFile tests using file read api to do some simple math""" def __init__(self, file_path): self.numbers = [] selfparse = csv.reader(os.path.abspath(file_path),delimiter='/') for row in self reader: self.append(row) return self """ TODO: reads the file by path and parse content into two dimension array (numbers) """ def get_mean(self, line_number): """ get_mean retrieves the mean value of the list by line_number (starts with zero) """ return sum(self[0:line_number])/(len(self[0:line_number])) def get_max(self, line_number): """ get_max retrieves the maximum value of the list by line_number (starts with zero) """ return max(self[0:line_number]) def get_min(self, line_number): """ get_min retrieves the minimum value of the list by line_number (starts with zero) """ return min(self[0:line_number]) def get_sum(self, line_number): """ get_sum retrieves the sumation of the list by line_number (starts with zero) """ return sum(self[0:line_number])
664dd8d5bf6c1181edca5f1cc2a3a3d748d63bca
DenverRenGuy/python
/avgList.py
90
3.546875
4
a = [1,2,5,10,255,3] b = 0 for element in a: b = b + element else: print b/len(a)
a78fe3252001ad9cd51f6e0ca62c0611ceef9681
nsa5953/PythonScripts
/Building_interfaces/tk_window.py
763
4.34375
4
# Python script to building interfaces # Python script with statement to make the "tkinter" module GUI method # and attributes available from tkinter import * # Statement to call upon a constructor to create window object window = Tk() # Statement to specify a title for this window window.title('Label Example') # Statement to call upon constructor to create label object label = Label(window, text = 'Hello World !') # Use the packer to add the label to window with horizontal and verical padding for positioning label.pack(padx = 200, pady = 20) # Mandatory statement to maintain the window by capturing events window.mainloop() # @Note:: Widgets will not appear in the window when running the program unless they have been added # with geometry manager
2d81a76293ca9231d554a09a1d36b99acbad1dcd
sravyabejugam/PythonPrograms
/school_administration.py
1,347
4.0625
4
import csv def write_into_csvfile(student_info): with open("Student_info.txt",'a',newline='') as student_file: writer=csv.writer(student_file) if student_file.tell()==0: writer.writerow(["Name", "Age", "Contact_info", "E-mail_ID"]) writer.writerow(student_info) if __name__ == "__main__": condition= True student_no=1 while(condition): student_info=input("enter the student #{} information in format [name age contact_info email]:\n".format(student_no)) student_info_list=student_info.split() print("Details that you have entered: \n name: {}\n age: {}\n contact_info: {}\n email: {}".format(student_info_list[0],student_info_list[1],student_info_list[2], student_info_list[3])) check_info=input("Please check what you have entered type (yes/no): ").lower() if check_info == "yes": write_into_csvfile(student_info_list) student_no+=1 condition=eval(input("Do you want to enter more student details? type (true/false)").capitalize()) elif check_info == "no": print("please re-enter the details of student #{}".format(student_no))
4e1c7341a0cd7a11083919d61855b6a92ee4f16c
siarhiejkresik/Epam-2019-Python-Homework
/final_task/pycalc/matcher/matcher.py
674
3.5
4
""" Matchers class. """ from collections import namedtuple from .creator import MatcherCreator Matcher = namedtuple("Matcher", ("token_type", "matcher")) class Matchers: """ Matchers is an iterable container for matchers with methods for creating matchers from literals list or regex. """ def __init__(self): self.matchers = [] self.create_from = MatcherCreator def __iter__(self): for matcher in self.matchers: yield matcher def register_matcher(self, token_type, matcher): """Register a matcher with a corresponding token type.""" self.matchers.append(Matcher(token_type, matcher))
9a02fc0b5e2394b20799e75191555c5744e6c546
TianyaoHua/LeetCodeSolutions
/Palindrome Pairs.py
902
3.546875
4
class Solution(object): def palindromePairs(self, words): """ :type words: List[str] :rtype: List[List[int]] """ dict = {c:i for i,c in enumerate(words)} answer = [] for word in words: n = len(word) candidate = word[::-1] if candidate in dict and candidate != word: answer.append([dict[word],dict[candidate]]) for i in range(1, n+1): if candidate[i:] in dict and word+candidate[i:] == (word+candidate[i:])[::-1]: answer.append([dict[word], dict[candidate[i:]]]) if candidate[0:n-i] in dict and candidate[0:n-i]+word == (candidate[0:n-i]+word)[::-1]: answer.append([dict[candidate[0:n-i]], dict[word]]) return answer solution = Solution() words = ["aba", "a"] print(solution.palindromePairs(words))
e13d5076c4e6124cb916f6738ff7140b21e25fdf
L-Q-K/C4TAdHW
/Test/test7.py
158
3.9375
4
print('Hi there, this is our sequence: 1, 5, -9, 3') inte = input('So can them: ') s = 'Hi there, this is our sequence: ' + inte + ', 1, 5, -9, 3, ' print(s)
0320ef14a7d046e5165502803e94fcc796532cd9
zeeshan495/Python_programs
/DataStructures/Banking.py
2,166
3.96875
4
from Queue import * from Utility import * class Banking: global que,utility utility = Utility() que = Queue(10, 100000) print("\t***welcome to our bank***") print("first add in queue...then go for transactions :\n") def counter(): print("Enter the 1 amount to deposit \nEnter the 2 amount to withdraw\n") choice = utility.input_int_data() if(choice == 1) and (que.bank_cash>=0): print("enter amount to deposit : ") deposit = utility.input_int_data() que.bank_cash = que.bank_cash + deposit print("present bank cash "+str(que.bank_cash)) que.dequeue() operation() elif(choice == 2) and (que.bank_cash>=0): print("enter amount to withdraw : ") withdraw = utility.input_int_data() que.bank_cash = que.bank_cash - withdraw if(que.bank_cash < 0): print("insufficient balance ") que.bank_cash = que.bank_cash + withdraw counter() print("present cash bank '"+str(que.bank_cash)+"'") que.dequeue() operation() elif(choice != 1) and (choice !=2): print("enter a valid cash ") else: print("bank balance is insufficient") que.dequeue() operation() def operation(): print("enter 1 to add in a queue \nEnter 2 for transaction \nEnter 3 for present customers in queue \nEnter 4 for Bank balance\n") choice = utility.input_int_data() if(choice == 1): result = que.enqueue(1) if(result == False): print("queue was full,go for transaction") else: print("you are added in queue ") operation() elif(choice == 2): var_isempty=que.is_empty() if(var_isempty): print("queue was empty,first add in queue") operation() else: counter() elif(choice == 3): print("present customers in queue : "+str(que.queue_size)) operation() elif(choice == 4): print("present cash bank '" + str(que.bank_cash)+"'") operation() else: print("invalid number....try again") operation() operation()
17a4945155a5cf0f8ff27d95bf8fefc42493d606
jvanarnhem/PythonBC1
/day2.py
1,987
4.09375
4
# i = 1 # while i <= 5: # what follows while must be boolean expression # print(i) # i = i + 1 # necessary to eventually terminate loop # print("Done") # # adjective = "great" # person = "Jeff" # print(f""" Can I do multiline formatted strings? # That is a {adjective} question. Please ask # {person}""") # names = ['Jeff', 'Samantha', 'Monica', 'Brooke'] # print(names) # print(type(names)) # print(names[0]) # names[2] = 'Isabel' # change an item # print(names) # # scores = [92, 93.5, 89, 93] # print(scores[-1]) # print(scores[1:4]) # print(len(scores)) # # mixed_list = ["Jeff", 52, "Brooke", 19] # names = ['Jeff', 'Samantha', 'Monica', 'Brooke'] # iterable # for name in names: # iterate over list, name is next element # print(name) # # this is a handy loop format # # a loop that you can run a specific number of times # for i in range(10): # print(i) # total = 0 # for num in range (5, 100, 5): # total += num # print(total) # nested loops # for x in range(4): # for y in range(3): # print(f'({x},{y})') # # defining a function # def print_stuff(): # print("Hello World!") # print("Mr. V. is awesome.") # # # print("This will print first.") # print_stuff() # print("Program execution continues here.") # import math # # # def quadratic_formula(a, b, c): # x1 = (-b + math.sqrt(b ** 2 - 4 * a * c))/(2 * a) # x2 = (-b - math.sqrt(b ** 2 - 4 * a * c))/(2 * a) # print(f"x = {x1} or x = {x2}") # # # quadratic_formula(1, -1, -6) # # Default parameters -- must come after non-default parameters # def greet_user(first_name, middle_name="John", last_name="Doe"): # print(f"Hello {first_name} {middle_name} {last_name}!") # # # greet_user("Jeff", "Alan", "VanArnhem") # greet_user("Jeff", "Alan") # greet_user("Jeff") # greet_user("Jeff", last_name="VanArnhem") def square1(num): print(num * num) def square2(num): return num * num print(square1(3)) # By default functions return 'None' print(square2(3))
7dccfd6dece2c16aa6e456b53030eb0dd55f49ca
shills112000/django_course
/PYTHON/OBJECT_ORIENTATED_PROGRAMING/dunder.py
926
4.03125
4
#!/usr/local/bin/python3.7 # __ = double underscore called special methods or magic or dunder mylist= [1,2,3] print (len(mylist)) class Sample(): pass mysample= Sample() #len(mysample) # get error as sample has no length currently print (mysample) # get the object print (mylist) class Book(): def __init__(self,title,author,pages): self.title = title self.author = author self.pages = pages def __str__(self): return f"{self.title} by {self.author}" def __len__(self): return self.pages def __del__(self): print (f"A book object has been deleted: {self.title}") b = Book('Python Rocks', 'Jose', 200) print (b) # because print trys to do a string repersentation it uses the __str__ in the class print (str(b)) # This also calls the __str__ method in the class print (len(b)) # if you wantd to delete a book del b # deletes book b print (b)
2b5faaa1fa8f951c7cb7f19fcbb0bfb2abec76ab
mweser/TraffICK
/MenuNavigation.py
380
3.53125
4
import sys def prompt_menu(menu_list, header=""): user_in = input(populate_menu(menu_list, header)) if user_in == 'q': sys.exit(1) return menu_list[int(user_in) - 1] def populate_menu(menu_list, header=""): output = header + "\n" i = 0 for item in menu_list: i += 1 output += "{}. {}\n".format(str(i), item) return output
5239c228d225006722c2f4298a95c6c7e86f0784
TsukasaAoyagi/Atcoder
/beginar/0829/2.py
317
3.65625
4
n = int(input()) def has_duplicates2(seq): seen = [] unique_list = [x for x in seq if x not in seen and not seen.append(x)] return len(seq) != len(unique_list) list = [] for i in range(n): list.append(input().split()) if has_duplicates2(list)==False: print("No") else: print("Yes")
d1fadd4b0ee743bf16437bced1998f39bbff54ba
acebk/friendly-octo-potato
/my_reverse.py
118
3.6875
4
def my_reverse(l): l1=[] x=len(l)-1 while x>=0: l1.append(l[x]) x-=1 return l1
725549cf4400697308f1bc2da1bd50e7c97b3704
volrath/aigames
/graphics/utils.py
2,477
3.59375
4
from functools import wraps from math import sin, cos, pi from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * def draw_circle(position, radius, color): """ Draw a circle in a 3d space """ glPushMatrix() glTranslatef(0.,0.,0.) glColor3f(*color) glBegin(GL_LINES) x = radius * cos(359 * pi/180.) + position.x z = radius * sin(359 * pi/180.) + position.z for i in range(0,360): glVertex3f(x, position.y, z) x = radius * cos(i * pi/180.) + position.x z = radius * sin(i * pi/180.) + position.z glVertex3f(x, position.y, z) glEnd() glPopMatrix() def rock_bar(character, z_pos): """ Draw a rock bar for the main character """ if character.rock_bar > 20: character.rock_bar = 20 glPushMatrix() glTranslatef(-16.6, 50., z_pos) glColor3f(90/255., 90/255., 90/255.) glBegin(GL_LINES) glVertex3f(0., 0., 0.) glVertex3f(4.5, 0., 0.) glEnd() glBegin(GL_LINES) glVertex3f(4.5, 0., 0.) glVertex3f(4.5, 0., .8) glEnd() glBegin(GL_LINES) glVertex3f(4.5, 0., .8) glVertex3f(0., 0., .8) glEnd() glBegin(GL_LINES) glVertex3f(0., 0., .8) glVertex3f(0., 0., 0.) glEnd() glTranslatef(.07, 0., .07) glColor3f(1., character.rock_bar/30., 0.) glBegin(GL_QUADS) glVertex3f(0., 0., 0.) glVertex3f(4.38 * character.rock_bar / 20., 0., 0.) glVertex3f(4.38 * character.rock_bar / 20., 0., .68) glVertex3f(0., 0., .68) glEnd() glPopMatrix() def life_bar(character, z_pos): """ Draw a life bar for the especified character """ if character.energy < 0: character.energy = 0 glPushMatrix() glTranslatef(-16.6, 50., z_pos) glColor3f(120/255., 120/255., 120/255.) glBegin(GL_LINES) glVertex3f(0., 0., 0.) glVertex3f(4.5, 0., 0.) glEnd() glBegin(GL_LINES) glVertex3f(4.5, 0., 0.) glVertex3f(4.5, 0., .8) glEnd() glBegin(GL_LINES) glVertex3f(4.5, 0., .8) glVertex3f(0., 0., .8) glEnd() glBegin(GL_LINES) glVertex3f(0., 0., .8) glVertex3f(0., 0., 0.) glEnd() glTranslatef(.07, 0., .07) glColor3f(1-character.energy/50., character.energy/50., 0.) glBegin(GL_QUADS) glVertex3f(0., 0., 0.) glVertex3f(4.38 * character.energy / 100., 0., 0.) glVertex3f(4.38 * character.energy / 100., 0., .68) glVertex3f(0., 0., .68) glEnd() glPopMatrix()
3cf56fba205ee9ebba5e85944ce062b674d6418e
HersheyChocode/Python---Summer-2018
/npointstar.py
770
4.59375
5
import turtle # Allows us to use turtles wn = turtle.Screen() # Creates a playground for turtles alex = turtle.Turtle() # Create a turtle, assign to alex point = int(input("How many points do you want your star to have? Enter an odd positive integer: ")) # This is taking the input of the user and making it an integer inAngle = 180/point #Calculates the inside angle to turn outAngle = 180 - inAngle #Calculates outside angle alex.penup() #Makes sure that there it doesn't draw alex.back(40) #Just moves it back to go in center alex.pendown()#Goes back to drawing alex.left(inAngle)#Makes original angle alex.forward(70)#Goes forward for i in range(point-1): #Repeats alex.right(outAngle)#Second angle and so on alex.forward(70)
d6169b8f757143bb26b79c7972e1826d6726e50a
TKSanthosh/tutorial-programme
/Specialized collection data types/defaultdict.py
226
3.96875
4
from collections import defaultdict d= defaultdict(int) d[1]="san" d[2]="tho" d[3] = "sh" print(d) print(d[4]) a={1:"san", 2:"tho", 3:"sh"} print(a[4]) #it will show error - keyError: 4 this is how it differs from defaultdict
52505735f383176e81c9a11e1ad005457d664c44
trieuhl/python-basic
/introductory/lesson2_math_operators.py
1,133
3.578125
4
if __name__ == '__main__': a = 1 b = 2 c = 3 d = 4 e = 5 f = 6 # phep cong t1 = a + b print("phep cong hai so") print(a) print(b) print(t1) print("ket qua = ", t1) # phep tru print() print("phep tru hai so") t2 = c - d print(c, "-", d, "=", t2) # phep nhan print() print("phep nhan") print(e, f, e * f) # phep chia print() print("phep chia") t3 = d / c print(d, "/", c, " = ", t3) # phep gan print() print("phep gan") g = 7 print("g = ", g) g = g + 1 print("g = ", g) print() g = 7 print("g = ", g) g += 1 print("g = ", g) print() h = 8 print("h = ", h) h *= 2 print("h = ", h) """ # ------------- OUTPUT ------------- phep cong hai so 1 2 3 ket qua = 3 phep tru hai so 3 - 4 = -1 phep nhan 5 6 30 phep chia 4 / 3 = 1.3333333333333333 phep gan g = 7 g = 8 g = 7 g = 8 h = 8 h = 16 # ------------- OUTPUT ------------- """
ff72f947fa29388537bfd0ccabdc172f28569e83
Aasthaengg/IBMdataset
/Python_codes/p02422/s761969353.py
583
3.78125
4
def print_ab(s, a, b): print(s[a:b+1]) def reverse_ab(s, a, b): s_f = s[:a] s_m = s[a:b+1] s_l = s[b+1:] return s_f+s_m[::-1]+s_l def replace_ab(s, a, b, p): s_f = s[:a] s_l = s[b+1:] return s_f+p+s_l s = input() q = int(input()) for i in range(q): option = input().split() if option[0] == "print": print_ab(s,int(option[1]),int(option[2])) elif option[0] == "reverse": s = reverse_ab(s, int(option[1]), int(option[2])) elif option[0] == "replace": s = replace_ab(s, int(option[1]), int(option[2]), option[3])
f16bebc62b17dcdeaeb820c25473d9ab2dec7bd1
Abknave/Algorithms-core
/SelectionSort.py
552
3.828125
4
def SelectionSort(l): array=[0 for i in range(len(l))] maximum=(2**32)-1 aux=0 for i in range(len(l)): pivot=l[0] for j in range(1,len(l)): if (pivot>=l[j]): pivot=l[j] aux=j array[i]=pivot l[aux]=maximum print l return array l=[5,4,3,2,1,5,4,3,2,1] print SelectionSort(l)
15e376cd3adb7ba42f61f9da84dde1a0ea258bc7
eur-nl/bootcamps
/zzzzz_archive/eshcc/scripts/notjustalabel/not_just_a_label.py
3,671
3.5625
4
import sys import csv import os import requests import time from bs4 import BeautifulSoup URL = 'https://www.notjustalabel.com/designers?page=%s' DETAIL_URL = 'https://www.notjustalabel.com/designer/%s' def fetch_listing_page(page_number): url = URL % page_number print('fetching listing page %s' % page_number) response = requests.get(url) if response.status_code != 200: print('Error fetching listing %s' % page_number) sys.exit(1) soup = BeautifulSoup(response.content, 'html.parser') designers = soup.find_all('div', class_='views-row') designer_urls = [] for designer in designers: url = designer.find_all('a')[-1].attrs['href'] designer_urls.append(url) return designer_urls def fetch_detail_page(page_id): print('fetching detail: %s' % page_id) url = DETAIL_URL % page_id response = requests.get(url) if response.status_code != 200: print('Error fetching detail %s' % page_id) sys.exit(1) soup = BeautifulSoup(response.content, 'html.parser') name = soup.find_all('h1')[0].text.strip() location_field = soup.find_all('div', class_='field-content')[0] city, country = [f.text for f in location_field.find_all( 'div', class_='content')] return dict(id=page_id, name=name, city=city, country=country) """ This is where the main part of program kicks in and where we should start reading. The first block starting with "if not ..." populates the file 'designers.txt' which hold the information to access the individual designers pages later on in the program. The second block starting with "writer = ..." prepares the csv file for writing content into it """ if __name__ == '__main__': if not os.path.isfile('designers.txt'): # If the file is not already there urls = [] # Initialize an empty list called 'urls' for page_number in range(402): # Loop through the range 0-402 # Calls the function above with each of the numbers from the range urls.extend(fetch_listing_page(page_number)) time.sleep(1) # Be nice to the server: One call per second # Write the results of the calls to the file open('designers.txt', 'w').write('\n'.join(urls)) writer = csv.writer(open('designers.csv', 'w')) # Prepare the output file # Names of the columns in the csv file in a list called 'cols' cols = ['id', 'name', 'city', 'country'] writer.writerow(cols) # Write the header to the file # The next line uses the result of the first function stored in the file # designers.txt in a list of urls (one per line) detail_urls = open('designers.txt').read().splitlines() count = 0 # Initialze a variable called count and set it to 0 # Loop, we use one url at a time from our list detail_urls for url in detail_urls: # We call our second function defined above passing in the last part # of the URL we scraped using our first function. We collect the # results in a variable 'details' that we use underneath to fill in # the rows of the csv file. # The actual contents of details is the dict or dictionary returned # by our second function. details = fetch_detail_page(url.split('/')[-1]) time.sleep(1) # Always be nice to the server at the other end # Here we fill the rest of the csv file we setup earlier row = [] for col in cols: row.append(details[col].encode('utf8')) writer.writerow(row) # Just for the workshop, you would want all the results count += 1 if count == 10: break
ab09ddc84dad1409d2c908169f080089fef47c54
nabinn/DS_and_Algorithms
/SearchingAlgorithms/binary_search.py
2,080
4.1875
4
def binary_search(num_list, item): """ :param num_list: sorted list of numbers :param item: item to search :return: boolean found This takes O(log n) """ low = 0 high = len(num_list) - 1 found = False while low <= high and not found: mid = (low + high) // 2 if item == num_list[mid]: found = True elif item > num_list[mid]: low = mid + 1 else: high = mid - 1 return found def recursive_binary_search(num_list, item): """recursively passes the chopped-off list to itself""" if len(num_list) == 0: return False else: mid = len(num_list) // 2 if item == num_list[mid]: return True else: if item > num_list[mid]: return recursive_binary_search(num_list[mid + 1:], item) else: return recursive_binary_search(num_list[:mid], item) def recursive_binary_search_v2(num_list, item): """alternate version of recursive binary search. This invokes the local function rec_bin_search() which does the actual work. """ def rec_bin_search(number_list, key, low, high): if low > high: return False else: mid = (low + high) // 2 if number_list[mid] == key: return True else: if key > number_list[mid]: return rec_bin_search(number_list, key, mid + 1, high) else: return rec_bin_search(number_list, key, low, mid - 1) return rec_bin_search(num_list, item, 0, len(num_list)-1) if __name__ == "__main__": list_of_numbers = [-34, -8, 0, 23, 50, 56, 78, 100] print(binary_search(list_of_numbers, 23)) print(binary_search(list_of_numbers, 101)) print(recursive_binary_search(list_of_numbers, 23)) print(recursive_binary_search(list_of_numbers, 101)) print(recursive_binary_search_v2(list_of_numbers, 23)) print(recursive_binary_search_v2(list_of_numbers, 101))
97769ca680c6bd93a831a53cfb63eb6bfc2dbda9
PaxtonCorey/First-Projects
/DiceRollingSimulator.py
951
4.34375
4
#This is my first attempt at writing a dice rolling simulator #using one six sided die import random def OneDie(roll): rollAgain="yes" while rollAgain=="yes": print("Okay, rolling!") print( "The die is " + str(random.randint(1,6))) rollAgain = input("Would you like to roll again? ") return "Goodbye!" def TwoDie(roll): rollAgain="yes" diceValue=[] values=[1,2,3,4,5,6] while len(diceValue)<2: random.shuffle(values) diceValue.append(random.choice(values)) diceValue.append(random.choice(values)) while rollAgain=="yes": print("Okay, rolling the die!") print("The die is " + str(diceValue)) rollAgain=input("Would you like to roll again? ")
1a8a47d39b94671309319be5fe73f36e4c314a36
mu71l473d/PublicPythonScripts
/rotstring.py
1,990
3.71875
4
#!/usr/bin/python3 from itertools import product from string import ascii_lowercase as alphabet uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] for eachLetter in realText: if eachLetter in ' ': outText.append(' ') elif eachLetter in uppercase: index = uppercase.index(eachLetter) crypting = (index + step) % 26 cryptText.append(crypting) newLetter = uppercase[crypting] outText.append(newLetter) elif eachLetter in lowercase: index = lowercase.index(eachLetter) crypting = (index + step) % 26 cryptText.append(crypting) newLetter = lowercase[crypting] outText.append(newLetter) return ''.join(outText) def caesar_encrypt(realText, offset): return realText.translate(str.maketrans(alphabet, alphabet[offset:] + alphabet[:offset])) def caesar_decrypt(cipherText, offset): outText = [] decryptText = [] for letter in alphabet: if letter in ' ': outText.append(' ') else: index = alphabet.index(letter) decrypting = (cipherText - offset) % 26 decryptText.append(decrypting) newLetter = lowercase[decrypting] outText.append(newLetter) return ''.join(outText) def caesar_brutusforce(cipherText): # # cutting edge bruteforce for caesar ciphers. I'm just taking a stab at this. for i in range(1, 26): result = caesar_decrypt(cipherText, i) temp = str(i) + ': ' + result + '\n' print(temp) print(caesar_decrypt("vet", 4)) def caesar_brutusforce(realText): ## cutting edge bruteforce for caesar ciphers. I'm just taking a stab at this. for i in range(1, 26): result = caesar_decrypt(realText, i) temp = str(i) + ": " + result +"\n" print(temp) brutusforce = caesar_brutusforce('qPbqr EBG Nhgb')
4d33ee6f48638fdd84d49015c3433fc65c625dc1
Justyouso/python_data_structure
/my_sort/shellSort.py
1,096
3.703125
4
# -*- coding: utf-8 -*- # @Author: wangchao # @Time: 19-9-3 上午10:07 def shellSort(alist): """ 功能:希尔排序,希尔排序是插入排序的变种,只需要计算出增量和开索引,再调用插入排序即可 :param alist: :return: """ # 计算增量 sublistcount = len(alist) // 2 while sublistcount > 0: # 调用插入排序 for startposition in range(sublistcount): gapInsertionSort(alist, startposition, sublistcount) sublistcount = sublistcount // 2 def gapInsertionSort(alist, start, gap): """ 功能:加有增量的插入排序 :param alist: :param start: :param gap: :return: """ for index in range(start + gap, len(alist), gap): currentvalue = alist[index] position = index while position >=gap and alist[position - gap] > currentvalue: alist[position] = alist[position - gap] position = position - gap alist[position] = currentvalue alist = [54, 26, 93, 17, 77, 31, 44, 55, 20] shellSort(alist) print(alist)
965f102c69e2cef4a7f3daf6428b3b9cf0c25644
jjcrab/code-every-day
/day25_capitalizeFirstLetter.py
650
3.53125
4
# https: // www.lintcode.com/problem/936 /?_from = ladder & fromId = 184 def capitalizesFirst(s): # s_list = list(s) # print(s) # print(s_list) # if s_list[0] and s_list[0].isalpha(): # s_list[0] = s_list[0].capitalize() # for i in range(1, len(s_list)): # if s_list[i-1].isspace(): # s_list[i] = s_list[i].capitalize() # return "".join(s_list) s_change = "" for i in range(len(s)): if i == 0 and s[i].isalpha() or s[i-1].isspace(): s_change += s[i].capitalize() else: s_change += s[i] return s_change print(capitalizesFirst(" i love you "))
96fa45618d803bacaf4da1df889d4590556f95ad
lfvelascot/Analysis-and-design-of-algorithms
/PYTHON LOG/PYTHON ADVANGE/ORDENAMIENTO/selectionSort.py
591
3.578125
4
def selectionSort(lista,tam): for i in range(0,tam-1): min=i for j in range(i+1,tam): if lista[min] > lista[j]: min=j aux=lista[min] lista[min]=lista[i] lista[i]=aux return lista def imprimeLista(lista,tam): for i in range(0,tam): print (lista[i]) def leeLista(): lista=[] cn=int(input("Cantidad de numeros a ingresar: ")) for i in range(0,cn): lista.append(int(input("Ingrese numero %d : " % i))) return lista A=leeLista() A= selectionSort(A,len(A)) imprimeLista(A,len(A))
e28c20918a1ed7bab51399afe603c482f1ebcdf5
FranckNdame/leetcode
/problems/136. Single Number/solution.py
214
3.5625
4
class Solution: # Time complexity: O(n) || Space Complexity: O(1) def singleNumber(self, nums: List[int]) -> int: result = 0 for num in nums: result ^= num return result
467e9ac64a115cca28d8eb4633c427bdf0e96e60
sparkg/Leetcode
/初级算法/树/验证二叉搜索树.py
1,614
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ bool_, _, __ = self.ValidBST(root) if bool_ is True: return True else: return False def ValidBST(self, root): """ :type root: TreeNode :rtype: bool minVal maxVal """ if root is None: return True, None, None if root.left is None and root.right is None: return True, root.val, root.val if root.left is None: bool_, min_, max_ = self.ValidBST(root.right) if bool_ is False: return False, None, None if root.val < min_: return True, root.val, max_ else: return False, None, None if root.right is None: bool_, min_, max_ = self.ValidBST(root.left) if bool_ is False: return False, None, None if max_ < root.val: return True, min_, root.val else: return False, None, None bool_, min_, max_ = self.ValidBST(root.left) bool__, min__, max__ = self.ValidBST(root.right) if bool_ is False or bool__ is False: return False, None, None if max_ < root.val and root.val < min__: return True, min_, max__ else: return False, None, None
5b7fb3dc13d3897a87cd0748e4d8ceba6dd352fd
rafaelperazzo/programacao-web
/moodledata/vpl_data/36/usersdata/96/12786/submittedfiles/questao2.py
470
3.84375
4
# -*- coding: utf-8 -*- from __future__ import division n1 = int(input('Digite o primeiro número:') n2 = int(input('Digite o segundo número:') n3 = int(input('Digite o terceiro número:') n4 = int(input('Digite o quarto número:') b = 0 or 3 or 5 or 7 or 9 v = 1 or 6 p = 4 or 8 if n1n2n3n4==bvbp or n1n2n3n4==vbpb or n1n2n3n4==bpbv or n1n2n3n4==pbvb: print('V') elif n1n2n3n4==bvpb or n1n2n3n4==vpbv or n1n2n3n4==pbvp: print('F') else: print('N')
e89007289920c60d4dd19c7a56cf3fdebcb9183b
ericyeung/PHY407
/Lab1/lab1_q1c.py
1,535
3.90625
4
#!/usr/bin/env python from __future__ import division from math import * '''lab1_q1c.py: Determining and plotting the scattering angle distribution''' __author__ = "Eric Yeung" __email__ = "eric.yeung@mail.utoronto.ca" import matplotlib.pyplot as plt import numpy as np N = 2000 # number of particles z = np.random.uniform(-1,1,N) # create a random array with N elements t = map(lambda z:pi-2*asin(z), z) # apply our formula to the random values of height tr = np.array(t) # make t into an array # Count the values in our tr array for both ranges specified FirstRange = ((170*pi/180 < tr) & (tr < 190*pi/180)).sum() SecondRange = ((90*pi/180 < tr) & (tr < 110*pi/180)).sum() print "%s scattering angles lie between 170 degrees and 190 degrees." % FirstRange print "%s scattering angles lie between 90 degreesand 110 degrees." % SecondRange relativeprob1 = FirstRange/N relativeprob2 = SecondRange/N print "The relative probability of finding the particle in the range(170,190) is %s for N = %s" % (relativeprob1, N) print "The relative probability of finding the particle in the range(90,110) is %s for N = %s" % (relativeprob2, N) import scipy.stats as stats # Plot a gaussian to compare to uniform dist. gaussian = stats.norm.pdf(sorted(tr), np.mean(sorted(tr)), np.std(sorted(tr))) plt.plot(sorted(tr), gaussian, color = 'red', ls = '-', linewidth = '1.5') # Plot the histogram with 100 bins plt.hist(tr, bins = 100, color='b', normed = True) plt.xlabel('Scattering Angle ($\Theta$)') plt.title('Distribution of $\Theta$') plt.show()
a97caaec8d269543a589b412eee4e1bc850123d2
bhushan-borole/Sorting-Algorithms
/shell_sort.py
546
4.0625
4
''' The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. Time Complexity Best : O(n log(n)) Average : O(n(log(n))^2) Worst : O(n(log(n))^2) ''' def SHELL_SORT(A): length = len(A) #initalize gap to mid of the array gap = length // 2 while gap > 0: for i in range(gap, length): temp = A[i] j = i while j >= gap and A[j - gap] > temp: A[j] = A[j - gap] j -= gap A[j] = temp gap = gap // 2 A = [9, 8, 7, 6, 5, 4, 3, 2, 1] SHELL_SORT(A) print(A)
ebce54f9544768a1cd5b60c96e3ffabb8a3a4c52
sofiazenzola/Python-INFO1-CE9990
/NYC_Water_Consumption.py
1,050
3.90625
4
""" NycWaterConsumption.py Reads csv from NYC Open Data URL Puts fields in a list of strings Outputs the water consumption per capita (gallons per person per day) for a given year """ import sys import csv import urllib.request year=input("Select a year from 1979-2016: ") url = "https://data.cityofnewyork.us/api/views/ia2d-e54m/rows.csv" \ "?accessType=DOWNLOAD" try: lines = urllib.request.urlopen(url) except urllib.error.URLError as error: print("urllib.error.URLError", error) sys.exit(1) hopLines = [] for line in lines: try: s = line.decode("utf-8") except UnicodeError as unicodeError: print(unicodeError) sys.exit(1) r = csv.reader([s]) #[s] is a list containing one string fields = next(r) #fields is a list of strings if fields[0] == year: hopLines.append(fields) lines.close() for line in hopLines: print("In", line[0], "the water consumputer per capita was", line[3], "gallons per person per day") sys.exit(0)