blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
9e7434c45d27864384e1a42c58ed2d9b34d9fba5
zenmeder/leetcode
/16.py
1,339
3.609375
4
#!/usr/local/bin/ python3 # -*- coding:utf-8 -*- # __author__ = "zenmeder" import math class Solution(object): def threeSumClosest(self, nums, target): nums.sort() previous_sum = [] for i in range(len(nums) - 2): j = i + 1 k = len(nums) - 1 while j < k: sums = nums[i] + nums[j] + nums[k] - target # print(i, j, k,sums) if sums == 0: return target elif sums < 0: if len(previous_sum) == 0: min_distance = sums elif k - j == 1 or previous_sum[-1] < 0: min_distance = self.compare(min_distance, sums) elif len(previous_sum) != 0 and previous_sum[-1] > 0: min_distance = self.compare(min(previous_sum[-1], -sums), min_distance) j += 1 previous_sum.append(sums) continue elif sums > 0: if len(previous_sum) == 0: min_distance = sums elif k - j == 1 or previous_sum[-1] > 0: min_distance = self.compare(min_distance, sums) elif previous_sum[-1] < 0: min_distance = self.compare(min(previous_sum[-1], -sums), min_distance) k -= 1 previous_sum.append(sums) continue return min_distance + target def postive(self, x): return x if x >= 0 else -x def compare(self, x, y): i = self.postive(x) j = self.postive(y) return y if i > j else x print(Solution().threeSumClosest([1, 2, 5, 10, 11], 12))
56422f66bc8fe11a1bfc8c489086a10c422dec91
jonascarnby/programmering_1
/uppgift4.py
1,267
3.640625
4
# -*- coding: UTF-8 -*- """ Jonas Carnby Python Ver.3.4.1 OSX 10.9.5 """ import celsiusconvert as omvandlare import sys from tkinter import * def convert(): try: x = int(ment.get()) c = omvandlare.convert(x) uinput = Label(mGui,text = "Din inmatning är i grader celsius:") uinput.pack() if c <= 0: mlabel2 = Label(mGui,text = c, fg="blue" ) mlabel2.pack() else: mlabel2 = Label(mGui,text = c, fg="orange" ) mlabel2.pack() except ValueError: mlabel3 = Label(mGui,text = "Du måste skriva in ett helt tal, försök igen!", fg = "red") mlabel3.pack() def quit(): result = messagebox.askyesno('Avsluta programmet', 'Vill du verkligen avsluta programmet?') if result == True: mGui.destroy() omvandlare.convert mGui = Tk() mGui.geometry("300x200+200+200") mGui.title("Farenheit Converter") ment = StringVar() fLabel = Label(text="Skriv in antal grader i Farenheit:") fLabel.pack() fInput = Entry(mGui,textvariable=ment) fInput.pack() omvandla = Button(text="omvandla",command = convert) omvandla.pack() avsluta = Button(text = "Avsluta",command = quit) avsluta.pack(side="bottom") mGui.mainloop()
5603798fec63d07e66b2f57f8651cecd8a17e3c3
ebehlmann/algebra-library
/vector.py
3,291
3.671875
4
import math class Vector(object): def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple(coordinates) self.dimension = len(coordinates) except ValueError: raise ValueError('The coordinates must be nonempty') except TypeError: raise TypeError('The coordinates must be an iterable') def __str__(self): return 'Vector: {}'.format(self.coordinates) def __eq__(self, v): return self.coordinates == v.coordinates def add(self, v): result = [] i = 0 while i < len(self.coordinates): result.append(self.coordinates[i] + v.coordinates[i]) i+=1 return result def subtract(self, v): result = [] i = 0 while i < len(self.coordinates): result.append(self.coordinates[i] - v.coordinates[i]) i+=1 return result def multiply(self, scalar): result = [] for coord in self.coordinates: result.append(coord * scalar) return result def find_magnitude(self): sum = 0 for coord in self.coordinates: sum += coord ** 2 return math.sqrt(sum) def normalize(self): try: return self.multiply(1/self.find_magnitude()) except ZeroDivisionError: raise Exception('Cannot normalize zero vector') def is_zero(self, tolerance=1e-10): if self.find_magnitude() < tolerance: return True else: return False def find_dot_product(self, v): sum = 0 i = 0 while i < len(self.coordinates): sum += self.coordinates[i] * v.coordinates[i] i+=1 return sum def find_angle(self, v, unit='radians'): try: result = math.acos(self.find_dot_product(v) / (self.find_magnitude() * v.find_magnitude())) if unit == 'degrees': return math.degrees(result) else: return result except ZeroVectorError: raise Exception('Cannot compute an angle with the zero vector') def is_parallel(self, v): if self.is_zero() or v.is_zero(): return True elif self.find_angle(v) == 0 or self.find_angle(v) == math.pi: return True else: return False def is_orthogonal(self, v, tolerance=1e-10): result = abs(self.find_dot_product(v)) if result < tolerance: return True else: return False vector1 = Vector([-7.579, -7.88]) vector2 = Vector([22.737, 23.64]) vector3 = Vector([-2.029, 9.97, 4.172]) vector4 = Vector([-9.231, -6.639, -7.245]) vector5 = Vector([-2.328, -7.284, -1.214]) vector6 = Vector([-1.821, 1.072, -2.94]) vector7 = Vector([2.118, 4.827]) vector8 = Vector([0, 0]) print('is_orthogonal') print vector1.is_orthogonal(vector2) print vector3.is_orthogonal(vector4) print vector5.is_orthogonal(vector6) print vector7.is_orthogonal(vector8) print('is_parallel') print vector1.is_parallel(vector2) print vector3.is_parallel(vector4) print vector5.is_parallel(vector6) print vector7.is_parallel(vector8)
772f0a6493c60975f1e14dc50d61df25c8f8e350
greysou1/pycourse
/Mod1/sec4/task1.py
187
3.5625
4
random_tip = 'wear a hat when it rains' mid_point = len(random_tip)//2 print('The mid point is at ' + str(mid_point)) print(random_tip[:mid_point]) print(random_tip[mid_point:])
fbbe4805980a418919a0629ac54df33ea74c4197
moong3871/Algorithm
/SWEA/05.Stack2/4874.Forth.py
955
3.578125
4
import sys sys.stdin = open("input.txt", "r") operator = ['+', '-', '*', '/'] def cal(oper): if len(stack) < 2: return False try: tmp2, tmp1 = int(stack.pop()), int(stack.pop()) except: return sys.float_repr_style if oper == '+': return tmp1 + tmp2 elif oper == '-': return tmp1 - tmp2 elif oper == '*': return tmp1 * tmp2 elif oper == '/': return tmp1 // tmp2 for tc in range(1, int(input()) + 1): infos = input().split() stack = [] for info in infos: if info == '.': if len(stack) > 1: res = 'error' else: res = stack.pop() elif info in operator: res = cal(info) if res: stack.append(res) else: res = 'error' break else: stack.append(info) print('#{} {}'.format(tc, res))
4ecf166e88f5ecb281c3357fade16b1a00c15db6
mariachacko93/luminarDjano
/luminarproject/zzzmyprograms/functionalprogramming/mapfilterreduce.py
319
3.640625
4
numbers=[1,2,3,4,5,6] data=list(map(lambda num:num*num,numbers)) print(data) data=list(filter(lambda num:num%2==0,numbers)) print(data) from functools import* data=list(reduce(lambda num:max(num),numbers)) print(data) names=["kkc","rrc","mmc"] data=list(map(lambda names:names.upper(),names)) print(data)
f86c427ad7810bd13914481c48a8fdae68fd3d11
sarahwalters/python-lexer-generator
/postfix_utils.py
1,451
3.515625
4
def regex_to_postfix(regex): infix = concat_expand(regex) postfix = infix_to_postfix(infix) return postfix def concat_expand(regex): # https://github.com/burner/dex/blob/master/concatexpand.cpp # Mark concatenation locations with chr(8) (backspace char) res = '' for i in range(len(regex)-1): char_left = regex[i] char_right = regex[i+1] res += char_left if char_left not in '-|([' and char_right not in '-|)]+*?': res += chr(8) res += regex[-1] return res def infix_to_postfix(regex): # https://gist.github.com/DmitrySoshnikov/1239804 # Converts infix notation to postfix -> e.g. a|b becomes ab| output = [] stack = [] for i, c in enumerate(regex): if c == '(': stack.append(c) elif c == ')': while stack[-1] != '(': output.append(stack.pop()) stack.pop() # pop '(' else: while len(stack): peeked_precedence = precedence_of(stack[-1]) current_precedence = precedence_of(c) if peeked_precedence >= current_precedence: output.append(stack.pop()) else: break stack.append(c) while len(stack): output.append(stack.pop()) return ''.join(output) precedence_map = { '(':1, '|':2, chr(8):3, '?':4, '*':4, '+':4, '^':5 } def precedence_of(character): if precedence_map.has_key(character): return precedence_map[character] return 6
d0d5a53122a062aa5121f4b2e207f431c9659758
rupakdasatos/python_practice
/powerpuff_girls_np.py
1,230
3.84375
4
''' Read input from STDIN. Print your output to STDOUT ''' #Use input() to read input from STDIN and use print to write your output to STDOUT import numpy as np class Error(Exception): """Base class for other exceptions""" pass class QRErr(Error): """Raised when the quantity required number list length is less or more than required length""" pass class QPErr(Error): """Raised when the quantity present number list length is less or more than required length""" pass def main(): try: N = int(input()) QR = np.array([int(x) for x in input().split()]) QP = np.array([int(y) for y in input().split()]) if QR.size != N: raise QRErr elif QP.size != N: raise QPErr #print(min(list(map(floordiv, QP, QR)))) print(np.amin(np.floor_divide(QP, QR))) except ZeroDivisionError: print("Please enter non zero value in quantity required.") except QRErr: print("Please provide proper quantity required inputs.") except QPErr: print("Please provide proper quantity present inputs.") except ValueError: print("Please provide numeric values in each input") main()
5dc8b68102112bd1d6ba55f5b5ade9dbec946443
neetiv/SelfTaughtPythonPrograms
/combining conditions test.py
403
4.03125
4
age = 12 if age == 10 or age == 11 or age == 12 or age == 21: print("Hiya!") else: print("blech!") print(''' ''') age = 2 if age == 10 or age == 11 or age == 12 or age == 21: print("Hiya!") else: print("blech!") age = 12 if age >= 10: print(' OLDY MOLDY!!! ') else: print('YOUNGY PUNGY!') age = 2 if age >= 10: print(' OLDY MOLDY!!! ') else: print('YOUNGY PUNGY!')
6bb733b24e35df04dfb70a7f5341e8ef30fb6d3d
mangodayup/month01-resource
/day07/exercise09.py
396
4.21875
4
# 练习1: 定义函数,在终端中打印一维列表. # list01 = [5, 546, 6, 56, 76, ] # for item in list01: # print(item) # list02 = [7,6,879,9,909,] # for item in list02: # print(item) def print_list(list_target): for item in list_target: print(f"元素是:{item}") list01 = [5, 546, 6, 56, 76, ] list02 = [7, 6, 879, 9, 909, ] print_list(list01) print_list(list02)
6a4d9b0bd7d82b0f6594209dcd72739fac964aea
Panic-Point/Euler
/Easy/Largest_Palindrome_Prod.py
255
3.734375
4
ans = 0 def is_palindrome(n): s = str(n) r = s[::-1] if r == s: return True return False for x in range(999, 901, -1): for y in range(999, 901, -1): if is_palindrome(x*y): print(x*y) exit()
87748bfbcbe981d16a24c52fbec0e0669a2c5bc1
mshagena89/Reddit-Comment-Analytics
/Reddit Web Scraper/csvhelpers.py
707
3.703125
4
import csv #CSV Read and write Helper functions #returns list of comments from csv source file #sourceFile: .csv with one column of comment def csvreader(sourceFile): commentList = [] with open(sourceFile, 'rb') as readFile: commentReader = csv.reader(readFile) for row in commentReader: commentList.append(row[0]) return commentList #returns all input rows from csv source file #sourceFile: .csv with any number of columns def csvreader_all(sourceFile): commentList = [] with open(sourceFile, 'rb') as readFile: commentReader = csv.reader(readFile) for row in commentReader: commentList.append(row) return commentList
184844e37dfef90c738323f1a6f5d2a538b6b0ec
k200x/leetcode
/Q20.py
372
3.609375
4
#coding:utf-8 def func(ss): tmp_num = 0 isPositive = 1 if ss[0] == "+": pass elif ss[0] == "-": isPositive = -1 total_str = ss[1:] level = 1 for index in range(len(total_str) - 1, -1, -1): tmp_num += int(total_str[index]) * level level *= 10 return tmp_num * isPositive s = "-345" print(func(s))
45c252ea8d9db2c694b0c0d845075077fd264761
fifa007/Leetcode
/test/test_pascal_triangle.py
775
3.828125
4
#!/usr/bin/env python2.7 ''' unit test of pascal's triangle ''' import unittest import src.pascal_triangle class pascal_triangle_test(unittest.TestCase): sol = src.pascal_triangle.Solution() def test_with_row_number_equals_zero(self): self.failUnless(self.sol.generate_pascal_triangle(0) == []) def test_with_row_number_equals_one(self): self.failUnless(self.sol.generate_pascal_triangle(1) == [[1]]) def test_with_row_number_equals_two(self): self.failUnless(self.sol.generate_pascal_triangle(2) == [[1], [1, 1]]) def test_with_row_number_equals_three(self): self.failUnless(self.sol.generate_pascal_triangle(3) == [[1], [1, 1], [1, 2, 1]]) def main(): unittest.main() if __name__ == "__main__": main()
5d091d2bdc99af3f6db7ea494cbffa001f1cfda6
phuycke/Project-Euler
/Code/problem_22.py
1,965
4.1875
4
#!/usr/bin/env python3 # Problem setting """ Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import csv def processNames(fileName): """Read the names from the name files provided by problem 22. Returns the list alphabetically sorted.""" characterlist = [] with open(fileName, 'r') as f: reader = csv.reader(f, dialect = 'excel', delimiter = ',') for row in reader: characterlist.append(row) characterlist = characterlist[0] return sorted(characterlist) def letterValue(word): """Compute the value of a word based on the letters. Add the position in the alphabet together for all letters. Using this method, A would have a value of 1, B of two ...""" letters = "abcdefghijklmnopqrstuvwxyz" letterlist = list(letters) values = [] [values.append(letterlist.index(element)+1) for element in word.lower()] return sum(values) def nameScore(namelist): """Compute the entire name score by multiplying the sum of the letter values with the index of the entire word in the list. Notice that the list starts at position 1, and not at 0 like usual.""" value = [] for word in namelist: val = letterValue(word) val = val * (namelist.index(word) + 1) value.append(val) return sum(value) names = processNames("names_22.txt") solution = nameScore(names) print("The sum of the name scores for all the names in the list is: %d" %(solution))
6a2de1a4bc6124bf8f6bf39ef261206591e28d50
gabriellaec/desoft-analise-exercicios
/backup/user_208/ch169_2020_06_22_16_29_22_215962.py
553
3.8125
4
def login_disponivel (login,lista): if login not in lista: return login else: for login1 in range(len(lista)): i = 1 while login in lista: login = login + str(i) if login in lista: login = login [:-1] i+=1 return login lista1 = [] while True: x = str(input("Digite o login: ")) if x != "fim": login_ = login_disponivel(x,lista1) lista1.append(x) if x == "fim": print(lista1)
f8f03d8bd1033b2638ee1042379b2db012c85a33
pjbautista/algorithms-python
/max_spacing_clustering.py
1,359
3.71875
4
""" Computes the max-spacing k-clustering of a graph """ import sys from heapq import heappop, heapify def main(): """ Main function """ # initialization nr_clusters = int(sys.argv[1]) nodes, graph = build_graph() spacing = 0 clusters = [set([x]) for x in nodes] # orders the edges by cost heapify(graph) while len(clusters) >= nr_clusters: cost, node1, node2 = heappop(graph) # retrieve the clusters to be merged cluster1 = None cluster2 = None for cluster in clusters: if node1 in cluster: cluster1 = cluster if node2 in cluster: cluster2 = cluster if cluster1 == cluster2: continue cluster1 |= cluster2 clusters.remove(cluster2) if len(clusters) < nr_clusters: spacing = cost print(spacing) def build_graph(): """ Returns the graph corresponding to the file 'edges.txt' """ graph = [] nodes = set() for line in open('clustering1.txt'): elems = [int(x) for x in line.strip().split()] if len(elems) != 1: node1, node2, cost = elems nodes.add(node1) nodes.add(node2) graph.append((cost, node1, node2)) return nodes, graph if __name__ == '__main__': main()
62a243a1cc4c491b32c464443b1655707329bdc6
nazfisa/python-code
/Basic Python Code/function2.py
188
3.984375
4
def tuple(mytuple): print("Tuple before add") print(mytuple) print("length of tuple is: ") ln=len(mytuple) return ln mytuple=(1,'asif',2,'nazim') print(tuple(mytuple))
11a9a1b69f4253f0a58ebf4b0f8d5e5179cff73e
RafaelGPaz/dotfiles
/bin/misc/obsolete/lauraAge.py
1,443
4.28125
4
#! /usr/bin/env python def CalculateAge(self,Date): '''Calculates the age and days until next birthday from the given birth date''' try: Date = Date.split('.') BirthDate = datetime.date(int(Date[0]), int(Date[1]), int(Date[2])) Today = datetime.date.today() if (Today.month > BirthDate.month): NextYear = datetime.date(Today.year + 1, BirthDate.month, BirthDate.day) elif (Today.month < BirthDate.month): NextYear = datetime.date(Today.year, Today.month + (BirthDate.month - Today.month), BirthDate.day) elif (Today.month == BirthDate.month): if (Today.day > BirthDate.day): NextYear = datetime.date(Today.year + 1, BirthDate.month, BirthDate.day) elif (Today.day < BirthDate.day): NextYear = datetime.date(Today.year, BirthDate.month, Today.day + (BirthDate.day - Today.day)) elif (Today.day == BirthDate.day): NextYear = 0 print (NextYear) Age = Today.year - BirthDate.year if NextYear == 0: #if today is the birthday return '%d, days until %d: %d' % (Age, Age+1, 0) else: DaysLeft = NextYear - Today return '%d, days until %d: %d' % (Age, Age+1, DaysLeft.days) except: return 'Wrong date format' # if __name__ == "__main__": # CalculateAge() Date = '2000.05.05' print (CalculateAge(Date))
cf1fec19e512483db1e3625030f32404655b472c
chrishuan9/oreilly
/python/python1/space_finder.py
811
3.96875
4
__author__ = 'chris' #Python 1: Lesson 4: Iteration: For and While Loops """Program to locate the first space in the input string.""" s = input("Enter any string: ") pos = 0 for c in s: if c == " ": print("First space occurred at position ", pos) break pos += 1 else: #Python loops come with such extra logic built in, in the shape of the optional else clause. This clause is placed # at the same indentation level as the for or while loop that it matches, and (just as with the if statement) is # followed by an indented suite of one or more statements. This suite is only executed if the loop terminates # normally. # If the loop ends because a break statement is executed, then the interpreter just skips over the else suite. print("No spaces in that string ")
c1d148602b89833b44112ab14f5a5746a2a50709
S-W-Williams/CS-Topic-Notes
/Solutions and Writeups/Unique Binary Search Trees.py
219
3.640625
4
from math import factorial class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ return factorial(2*n) / (factorial(n + 1) * factorial(n))
57c0a59efd2fd1f4d0106c654cadba6dd86158e0
tikhomirovd/1sem_Python3
/zachitaintegralov/main.py
361
3.859375
4
# Тихомиров Дмитрий # ИУ7-15Б def f(x): # return 3 * x ** 3 + 2 * x ** 2 + 1 return x*x*x*x*x*x*x def Newton(f,a,b,n): s = 0 h = (b-a)/n for i in range(n): s += f(a+i*h)+3*f(a+i*h+h/3)+3*f(a+i*h+2*h/3)+f(a+i*h+h) s *= h/8 return s a = 0 b = 1 n = 1 I = Newton(f,a,b,n) print('Интеграл равен ', I)
28f32f3a955f303dd874e8be0f61b06b8fd29664
cyc1am3n/Problem_Solving
/DP/1463.py
491
3.515625
4
# https://www.acmicpc.net/problem/1463 # Name: 1로 만들기 # Topic: Dynamic Programming def solution(N): dic = {} for i in range(1, N + 1): if i == 1: dic[i] = 0 else: dic[i] = dic[i - 1] + 1 if i % 3 == 0: dic[i] = min(dic[i/3] + 1, dic[i]) elif i % 2 == 0: dic[i] = min(dic[i/2] + 1, dic[i]) return dic[N] if __name__ == '__main__': n = int(input()) print(solution(n))
f78ca3921cbc1ae955f6e41409706644032462a9
mranta-ai/Data_analytics_in_accounting
/_build/jupyter_execute/7.3_ML_for_structured_data-xgboost_example.py
8,515
3.59375
4
## Example - Xgboost, state-of-the-art ensemble method for structured data Xgboost is one of the latest implementations of gradient boosting algorithms, with many optimisations compared to other gradient boosting algorithms. https://xgboost.readthedocs.io/en/latest/ In this example, we are predicting abnormal Tobin's Q using board characteristics. ### Libraries *Pandas* and *Numpy* for data processing. *Scipy* and *Statsmodels* for statistical analysis. *Matplotlib* for plotting. import xgboost import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import shap import scipy.stats as ss import statsmodels.api as sm plt.xkcd() A function to check the normality of a dataset. Draws a histogram and a normal curve. It also calculates the Kolmogorov-Smirnov statistic of the dataset. # Function to check normality def check_normality(data,bins=50): mask = ~np.isnan(data) temp1 = data[mask] x = np.linspace(np.percentile(temp1,1),np.percentile(temp1,99),100) plt.hist(temp1, density=True,bins=bins) plt.plot(x,ss.norm.pdf(x,np.mean(temp1),np.std(temp1))) print("Kolmogorov-Smirnov: " + str(sm.stats.diagnostic.kstest_normal(temp1))) Data preparation, which includes: * Loading data from a csv-file * Removing missing y-values * Loading the abnormal Tobin Q values to the y_df dataframe * Loading the board characteristic variables to the x_df dataframe * Winsorizing the data, meaning that we transform the most extreme values to the 1 % and 99 % percentile values. # Prepare data. errors_df = pd.read_csv("AbnormalQ.csv",delimiter=";") errors_df = errors_df.rename(columns = {'BOARD_GENDER_DIVERSITY_P' : 'BOARD_GENDER_DIVERSITY','BOARD_MEMBER_COMPENSATIO' : 'BOARD_MEMBER_COMPENSATION'}) # Remove missing abQ values errors_df = errors_df.loc[~errors_df['ABN_TOBIN_POIKKILEIK'].isna()] y_df = errors_df['ABN_TOBIN_POIKKILEIK'] x_df = errors_df[['BOARD_GENDER_DIVERSITY', 'BOARD_MEETING_ATTENDANCE', 'BOARD_MEMBER_AFFILIATION', 'BOARD_MEMBER_COMPENSATION', 'BOARD_SIZE', 'CEO_BOARD_MEMBER', 'CHAIRMAN_IS_EX_CEO', 'INDEPENDENT_BOARD_MEMBER', 'NUMBER_OF_BOARD_MEETINGS', 'AVERAGE_BOARD_TENURE']] # Winsorize x-data x_df_wins = x_df.clip(lower=x_df.quantile(0.01), upper=x_df.quantile(0.99), axis = 1) Calculate the descriptive statistics of the x variables (board characteristics). x_df.describe().transpose() An example of the check_normality -function. check_normality(y_df) Convert the data to a xgboost dmatrix, that is more computationally efficient form for data. dtrain = xgboost.DMatrix(x_df_wins, label=y_df, nthread = -1) *** The most difficult part in using xgboost for prediction is the tuning of hyperparameters. There is no good theory to guide parameter optimisation, and it is more dark magic than science. You can use grid-search approaches, but it needs A LOT of computing power. The parameters that we fine-tune are: * num_boost_round: The number of decision trees. * max_depth: The depth of the trees. * eta: The weight of the added tree * subsample: A randomly selected subsample of the data, that is used at each round. * colsample_bytree: A randomly selected subsample of features, that is used for each tree (this can be done also by node and by level). * min_child_weight: A regularisation parameter. In the linear regression case this would mean the minimum number of data points that needs to be in the leaves * gamma: A regularisation parameter, that controls the loss function. There are many other tunable parameters in the model, but we leave them to default values. m_depth = 5 eta = 0.02 ssample = 0.8 col_tree = 0.8 m_child_w = 1 gam = 0.1 param = {'max_depth': m_depth, 'eta': eta, 'subsample': ssample, 'colsample_bytree': col_tree, 'min_child_weight' : m_child_w, 'gamma' : gam} Xgboost.cv -function can be used to search the optimal number of trees in the model. We search the number of trees that achieve the lowest *root-mean-square-error*. In this case, the optimal number of trees appears to be around 600. temp = xgboost.cv(param,dtrain,num_boost_round=900,nfold=5,seed=10) plt.plot(temp['test-rmse-mean'][200:900]) plt.show() b_rounds = 600 The model is trained using the *train*-function. The number of trees was set to 600 based on the cross-validation results. bst = xgboost.train(param,dtrain,num_boost_round=b_rounds) *** In the following we analyse the results of the model using the methods of explainable AI. Histrogram for the split points in the threes for the variable *Board gender diversity*. Notice that this information cannot be used for deciding what is the optimal percentage. The model just tries to separate companies according to their market performance. This is not necessarily achieved by separating data using the "optimal" feature values. # Histogram of split points split_bars = bst.get_split_value_histogram(feature='BOARD_GENDER_DIVERSITY',bins = 40) plt.bar(split_bars['SplitValue'],split_bars['Count']) plt.xlabel('Gender diversity') plt.ylabel('Count') plt.show() *** Average of the split points. aver_split_points = [] for feat in bst.feature_names: split_bars = bst.get_split_value_histogram(feature=feat,as_pandas=False) temp = sum(split_bars[:,0]*split_bars[:,1])/(sum(split_bars[:,1])) aver_split_points.append(temp) aver_df = pd.DataFrame() aver_df['averages'] = aver_split_points aver_df.index = bst.feature_names aver_df.round(2) Basic metrics that can be used to measure the feature importance are *weight,gain* and *cover*. There are many issues with these metrics. For example the weight metric undervalues binary features. Below is their explanation from the xgboost documents: * ‘weight’: the number of times a feature is used to split the data across all trees. * ‘gain’: the average gain across all splits the feature is used in. * ‘cover’: the average coverage across all splits the feature is used in. xgboost.plot_importance(bst,importance_type='weight',xlabel='weight',show_values=False,grid=False), xgboost.plot_importance(bst,importance_type='gain',xlabel='gain',show_values=False,grid=False), xgboost.plot_importance(bst,importance_type='cover',xlabel='cover',show_values=False,grid=False) plt.show() #### SHAP analysis Because the basic importance metrics have many weaknesses, the machine learning community is doing a lot of research at the moment to invent better ways to analyse machine learning models. One recent innovation is SHAP values. https://github.com/slundberg/shap j=0 shap.initjs() Below, shap values are calculated for the model. explainerXGB = shap.TreeExplainer(bst) shap_values_XGB = explainerXGB.shap_values(x_df_wins,y_df,check_additivity = False) A summary plot of the most important features. From the board characteristics the most important explainers of market performance are *Number of board meetings*, *Board member compensation*, *Average board tenure* and *Board member affiliation*. In this example, the meaning of the SHAP values is *the absolute average effect on the abnormal tobin Q of the company*. shap.summary_plot(shap_values_XGB,x_df_wins,plot_type='bar') Present the average values as a dataframe. shaps = np.mean(abs(shap_values_XGB), axis = 0) names = bst.feature_names apu_df = pd.DataFrame() apu_df['names'] = names apu_df['shaps'] = shaps apu_df The above SHAP plot has no information about the nature of association. Is it positive or negative? *Number of board meetings* has the largest effect, but is it increasing or decreasing abnormal Tobin's Q? This is estimated below. stand_feats = (x_df_wins-x_df_wins.mean(axis = 0))/x_df_wins.std(axis = 0) std_feat_times_shaps = np.multiply(shap_values_XGB,stand_feats) dir_metric = np.mean(std_feat_times_shaps, axis = 0) plt.barh(range(10),dir_metric,tick_label = bst.feature_names) plt.show() More detailed analysis of the nature of association can be achieved with the scatter plots of SHAP values. shap.dependence_plot(0,shap_values_XGB,x_df), shap.dependence_plot(8,shap_values_XGB,x_df) Scatter plots for all the variables. fig, axs = plt.subplots(5,2,figsize=(10,16),squeeze=True) ind = 0 for ax,feat in zip(axs.flat,x_df_wins.columns): ax.scatter(x_df_wins[feat],shap_values_XGB[:,ind],s=1) ax.set_ylim([-0.15,0.15]) ax.set_title(feat) ind+=1 plt.subplots_adjust(hspace=0.4) plt.show() Below is an analysis where two subgroups are compared to each other. The subgroups are formed using the extreme values of the features.
f92cedc968f5e3ccf46f6be5dbae0bb2dcf5e45f
Merna-Atef/Algorithmic-Toolbox-Coursera-MOOC
/week2_algorithmic_warmup/4_least_common_multiple/lcm.py
436
3.640625
4
# Uses python3 import sys def lcm_naive(a, b): for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def gcd_eucl(a, b): if b == 0: return a else: return gcd_eucl(b, a%b) def lcm_fast(a,b): const = a*b gcd = gcd_eucl(a, b) return int (a*b/gcd) if __name__ == '__main__': a, b = [int(x) for x in input().split()] print(lcm_fast(a, b))
d213016753567a29c1bf7e9538a0beb56e9eb6cb
Lossme8/Python_Fundamentals
/Pandas_library/pandas_library.py
323
3.65625
4
import pandas as pd df = pd.DataFrame({'Date':['7/10/19', '8/10/19', '9/10/19', '10/10/19', '11/10/19'], 'Hours Worked': [7, 7, 7, 7, 7], ' Knowledge acquired on date in percentage': [20, 23, 17, 33 , 7]}) print(df) print("-"*50) print(df.tail()) print("-"*30) print(df.head())
8cb008ebf57280a46ba1c393b380aa539bffa427
branning/euler
/problems/euler026.py
1,019
3.65625
4
#!/usr/bin/env python from euler007 import eratosthenes ''' http://mathworld.wolfram.com/RepeatingDecimal.html http://mathworld.wolfram.com/MultiplicativeOrder.html ''' def MultiplicativeOrder10(n): ''' returns multiplicative order of 10 mod n this is equal to the length of the period of the decimal expansion of 1/n ''' limit = 1000 for i in range(2,limit): if 10**i % n == 1: return i else: return None def DecimalExpansionPrimes(debugging=True): limit = 1000 primes = eratosthenes(limit) decimal_period = {2: 0, 3: 1, 5: 0} for p in primes[3:]: mult_order = MultiplicativeOrder10(p) decimal_period[p] = mult_order max_n = 0 max_length = 0 for n in decimal_period: if decimal_period[n] > max_length: max_n = n max_length = decimal_period[n] if debugging: print "max period is {} for 1/{}".format(max_length, max_n) else: print max_n if __name__=="__main__": DecimalExpansionPrimes(False)
77d1df7caf24550feb313d9ca1cfc676b1943e3f
Shilpi1307/ShapeAI_Python_Cyber_Security
/Shilpi.py
1,253
3.546875
4
import requests #import os from datetime import datetime import sys #to write or push output in a text file api_key = 'd541c87d8c16d4d904419f17a11c4d53' place = input("Enter the name of the place: ") complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+place+"&appid="+api_key api_link = requests.get(complete_api_link) api_data = api_link.json() #creating variables temp_C = ((api_data['main']['temp']) - 273.15) temp_F = (temp_C*(9/5))+32 desc = api_data['weather'][0]['description'] hum = api_data['main']['humidity'] wind_speed = api_data['wind']['speed'] date_time = datetime.now().strftime("%d %b %Y | %I:%M:%S %p") sys.stdout = open("Shilpi_Weather.txt","w") print("-----------------------------------------------------------------------") print("Weather Statistics for - {} || {}".format(place.upper(), date_time)) print("-----------------------------------------------------------------------") print("Current Temperature in degree Celcius is {:.1f} deg C".format(temp_C)) print("Current Temperature in degree Fahrenheit is {:.1f} deg F".format(temp_F)) print("Current Weather Description: ",desc.title()) print("Current Humidity: ",hum,"%") print("Current Wind Speed: ",wind_speed,"kmph") sys.stdout.close()
7857961bfc7a477352a6627ef9b38e9f28dd4cb9
jaghadish281098/leap-or-not
/leap or not (jagh).py
165
3.828125
4
year=int(raw_input()) if year%4==0: if year%100==0: if year%400==0: print "leap" else: print"not" else: print "leap"
126ae4c1df4cdfefb37d09583d39604209a1164d
bbperdomo/Competitive-Programming
/hw/hw5/11586_traintracks.py
922
3.890625
4
# Input # Input begins with the number of test cases. Each following line contains one test case. Each test case # consists of a list of between 1 and 50 (inclusive) train track pieces. A piece is described by two code # letters: ‘M’ for male or ‘F’ for female connector. Pieces are separated by space characters. # Output # For each test case, output a line containing either ‘LOOP’ or ‘NO LOOP’ to indicate whether or not all # the pieces can be joined into a single loop. # Sample Input # 4 # MF MF # FM FF MF MM # MM FF # MF MF MF MF FF # Sample Output # LOOP # LOOP # LOOP # NO LOOP num_tests = int(input()) for test in range(num_tests): diff = 0 num_tracks = 0 tracks = list(map(str, input().split())) for track in tracks: if track == "MM": diff += 1 elif track == "FF": diff -= 1 num_tracks += 1 print("LOOP" if diff == 0 and num_tracks > 1 else "NO LOOP")
362ec70a8e60e01a9cc07e6c7a6635b250cd5094
Chig00/Python
/Dodge.py
7,973
3.9375
4
#!/usr/bin/env python3 """ Dodge - 'One-tap' dodger. This a 'one-tap' game where the player controls a ball and must avoid the walls approaching by pressing the space bar. Each wall successfully dodged gives the player a point. Over time, the game will become harder by increasing the speed of the walls. """ import pygame from pygame.locals import * from time import perf_counter as counter, sleep from random import randint #Constants set. screen_width = 200 screen_height = 600 screen_size = (screen_width, screen_height) black = (0, 0, 0) white = (255, 255, 255) class FakeSprite: """ Class for image, rectangle pairs, which would act like sprites. These objects will have their source image with the desired transformation, the rectangle for hitboxes and the like, and methods for movement. """ def __init__(self, image_name, position = (0, 0), size = None, rotation = None): """ Make a fake sprite using the inputted arguments. The only required argument is the image file's file name/directory. The position of the fake sprite (which is determined by the top-left corner) defaults to (0, 0), which is the top-left corner of the display surface. The size is an optional argument, that will make the image (and thus the rectangle) equal in size to the argument. Using no size argument will cause the size to be equal to the picture's actual size. Rotation is like size - it's optional and not inputting it will use the image file's natural rotation. Rotation will cause the image to be rotated by the argument's value (in degrees). """ self.image = pygame.image.load(image_name) if size: self.image = pygame.transform.scale(self.image, size) if rotation: self.image = pygame.transform.rotate(self.image, rotation) self.rectangle = self.image.get_rect() self.rectangle.topleft = position def reposition(self, position): """ Move the fake sprite to the position given. The position must be a tuple or list of the co-ordinates of the new position for the fake sprite. """ self.rectangle.topleft = position def move(self, movement): """ Move the fake sprite by the amount given (movement argument). The movement must be a tuple or list and the fake sprite will be moved in place. """ self.rectangle.move_ip(movement) def blit_on(self, surface): """ Blit the fake sprite's image onto the surface given. Note that this blit_on() method is different from other blit methods, as the image of this fake sprite is being blitted onto a surface, rather than having an surface being blitted onto the image. """ surface.blit(self.image, self.rectangle) def new_wall(): """ Create and return a new wall obstacle for the game. The wall is placed in one of the two wall spawns at the top of the screen. The wall's spawning spot is determined randomly and the wall is retuned as a fake sprite object. """ if randint(0, 1): wall = FakeSprite("White Rectangle.jpg", position = (0, 0), size = (int(screen_width * 0.45), int(screen_height / 30))) else: wall = FakeSprite("White Rectangle.jpg", position = (int(screen_width * 0.55), 0), size = (int(screen_width * 0.45), int(screen_height / 30))) return wall def game_over(screen, score): """End the game and display the player's score.""" #A game over image is used. game_over = FakeSprite("Game Over.jpg", position = (0, int(screen_height / 6)), size = (screen_width, int(screen_height / 3))) #The text for the score display is created. score_text = pygame.font.Font(None, 60).render("Score: " + str(score), True, white) #The screen is erased and "GAME OVER" and the score are displayed. screen.fill(black) game_over.blit_on(screen) screen.blit(score_text, (0 , int(screen_height * 2/3))) pygame.display.flip() def main(): """Start Dodge.""" pygame.init() #Display created with the screen size constants set priorly. screen = pygame.display.set_mode(screen_size) #The line that separates the lanes is set using the size of the screen. lane_line = FakeSprite("White Rectangle.jpg", position = (int(screen_width * 0.45), 0), size = (screen_height, int(screen_width / 10)), rotation = 90) player_ball = FakeSprite("White Ball.jpg", position = (int(screen_width * 0.025), int(screen_height * 13/15)), size = (int(screen_width * 0.4), int(screen_height * 2/15))) first_wall = FakeSprite("White Rectangle.jpg", position = (0, 0), size = (int(screen_width * 0.45), int(screen_height / 30))) lane_line.blit_on(screen) player_ball.blit_on(screen) first_wall.blit_on(screen) pygame.display.flip() walls = [first_wall] wall_speed = [0, 5] wall_space = player_ball.rectangle.height * 5 base_time = counter() press = False over = False score = 0 #Main Game Loop while True: #If a wall makes contact with the ball, the player loses. for wall in walls: if wall.rectangle.colliderect(player_ball.rectangle): game_over(screen, score) over = True #If the game is over, the game no longer loops. if over: sleep(3) break #The game gets progressively harder. if counter() - base_time >= 1: base_time = counter() wall_speed[1] += 1 #When the previous wall has gone far enough, the next wall comes down. if walls[-1].rectangle.top >= wall_space: walls.append(new_wall()) #Every time a rectangle comes offscreen, it is no longer animated #to keep process speeds high. The player also gets a point. for wall in walls: if wall.rectangle.top >= screen_height: del walls[walls.index(wall)] score += 1 #All the walls currently onscreen move down with their curent speed. for wall in walls: wall.move(wall_speed) #The player's ball is moved to the other side #if the space bar is pressed. if pygame.key.get_pressed()[K_SPACE]: press = True elif not pygame.key.get_pressed()[K_SPACE] and press: press = False if player_ball.rectangle.left == 5: player_ball.rectangle.left = 115 elif player_ball.rectangle.left == 115: player_ball.rectangle.left = 5 #Image update phase. #The screen is filled black to erase the previous frame. screen.fill(black) #All of the (fake) sprites are blitted back onto the display. lane_line.blit_on(screen) player_ball.blit_on(screen) for wall in walls: wall.blit_on(screen) #The display is updated. pygame.display.flip() #The pump() function is called to keep input working. pygame.event.pump() sleep(0.01) #3 seconds after game over, pygame quits. pygame.quit() if __name__ == "__main__": main()
09e92d83107e9f1d831cfcac3ad6dc47a636a7a7
jonathanpyle35/free-shavacado
/guess_a_number_ai_pyle.py
2,452
3.8125
4
#Guess-A-Number AI # #Jonathan Pyle #September 13, 2016 import random import math print("**********************************************************************") print(" ") print(" __ ___ __ __ __ ___ __ ") print(" / _` | | |__ /__` /__` __ /\ __ |\ | | | |\/| |__) |__ |__) ") print(" \__> \__/ |___ .__/ .__/ /~~\ | \| \__/ | | |__) |___ | \ ") print(" ") print(" ") print("**********************************************************************") input(" Press Enter to Start ") def play(): low = 1 high = 100 limit = int(math.log(high - low, 2)) + 1 tries = 1 print("Welcome to Guess-A-Number AI. Please think of a number from " + str(low) + " to " + str(high) + " and I will try to guess it.") input("Please press Enter once you are ready.") num = random.randint(low, high) got_it = False while got_it == False and tries < limit: guess = int(high + low) // 2 print("Is the number " + str(guess) + "?") print("Enter 'lower', 'higher', or 'yes'") response = input() if response.lower() == 'higher' or response.lower() == 'h': low = guess + 1 elif response.lower() == 'lower' or response.lower() == 'l': high = guess - 1 elif response.lower() == 'yes'or response.lower() == 'y': got_it = True else: print("I don't understand.") input("Enter 'lower', 'higher', or 'yes'") tries += 1 if got_it == True: print("I got it!") print("This was created by Jonathan Pyle and finished on September 13, 2016") def play_again(): while True: answer = input("Would you like to play again?") if answer == 'no' or answer == 'n': return False elif answer == 'yes' or answer == 'y': return True print("Hey! Just say yes or no.") # game_begins again = True while again == True: play() again = play_again() print("Game over")
443f332d0a8307d8fd14f487c85e553fdc7121ff
INOS-soft/Python-LS-LOCKING-Retunning-access
/4.3 TSP Problem (Nearest Neighbor heuristic).py
3,123
4.15625
4
""" 1.Question 1 In this assignment we will revisit an old friend, the traveling salesman problem (TSP). This week you will implement a heuristic for the TSP, rather than an exact algorithm, and as a result will be able to handle much larger problem sizes. Here is a data file describing a TSP instance (original source: http://www.math.uwaterloo.ca/tsp/world/bm33708.tsp). nn.txt The first line indicates the number of cities. Each city is a point in the plane, and each subsequent line indicates the x- and y-coordinates of a single city. The distance between two cities is defined as the Euclidean distance --- that is, two cities at locations (x,y) and (z,w) have distance sqrt{(x-z)^2 + (y-w)^2} between them. You should implement the nearest neighbor heuristic: Start the tour at the first city. Repeatedly visit the closest city that the tour hasn't visited yet. In case of a tie, go to the closest city with the lowest index. For example, if both the third and fifth cities have the same distance from the first city (and are closer than any other city), then the tour should begin by going from the first city to the third city. Once every city has been visited exactly once, return to the first city to complete the tour. In the box below, enter the cost of the traveling salesman tour computed by the nearest neighbor heuristic for this instance, rounded down to the nearest integer. [Hint: when constructing the tour, you might find it simpler to work with squared Euclidean distances (i.e., the formula above but without the square root) than Euclidean distances. But don't forget to report the length of the tour in terms of standard Euclidean distance.] """ import math class City(object): def __init__(self, *coord): self.coord = coord def dataReader(filePath): with open(filePath) as f: data = f.readlines() numCities = int(data[0]) cities = [] for i in range(1, len(data)): dataList = data[i].split() ID = int(dataList[0]) x, y = map(float, dataList[1:]) cities.append(City(x, y)) return numCities, cities def calSqaureDistance(coord1, coord2): return (coord1[0] - coord2[0]) ** 2 + (coord1[1] - coord2[1]) ** 2 def TSP_approx(numCities, cities): start = cities[0] totalDistance = 0 prev = cities[0] del cities[0] while cities: if len(cities) % 100 == 0: print(len(cities)) minSqaureDistance = None minCityIndex = None minCity = None for k, v in enumerate(cities): sqaureDistance = calSqaureDistance(prev.coord, v.coord) if minSqaureDistance != None and sqaureDistance < minSqaureDistance or minSqaureDistance == None: minSqaureDistance = sqaureDistance minCityIndex, minCity = k, v prev = minCity del cities[minCityIndex] totalDistance += math.sqrt(minSqaureDistance) totalDistance += math.sqrt(calSqaureDistance(prev.coord, start.coord)) return totalDistance def main(): filePath = "data/tsp_nn.txt" numCities, cities = dataReader(filePath) totalDistance = TSP_approx(numCities, cities) print(int(totalDistance)) if __name__ == "__main__": main()
da1c9659cadc6890efb0a302ed4bea1db0157d49
joingram/cs1200_jingram
/lab_3_0/3_0.py
5,426
4.6875
5
""" CSCI 1200 Lab Exercise 3.0 INTRODUCING LISTS Your task in this lab exercise is to learn to declare lists and to perform basic operations on lists. Do all work in Geany IDE and follow instructions provided in this code file. Learning Outcomes ================= In this lab you will learn: - How to declare lists - Add items to list - Remove items from list - Sort lists Evaluation ========== 20 pts. - submitted filename 3_0.py | 20 20 pts. - 3_0.py executes without error | 20 30 pts. - Task 1 meets requirements | 0, please see comments 30 pts. - Task 2 meets requirements | 30, very good! Execute your code to get instant feedback Submission ========== As before, submit your work on D2L or using git. Earn 5 pts. extra credit by submitting using git by due date. """ #======================================================================= # TASK 1 #----------------------------------------------------------------------- # Declare list variable colors that contains following following values: # red, blue, green, orange, yellow colors = ['red', 'blue', 'green', 'yellow',] # <-- you are missing a color print(colors) # Get length of colors and assign it to number_of_colors. # Make sure to use the correct python function that returns list length. # Do not assign literal value. number_of_colors = -1 # <-- this should be number_of_colors = len(colors) print(colors[0]) print(colors[-1]) # Get first item in colors list and assign it to first_color. # Make sure to use correct syntax for accessing items in list. # Do not assign literal value. first_color = None # <-- this should be first_color = colors[0] colors =['red', 'blue', 'green', 'yellow'] print(colors[0]) # Get last item in colors list and assign it to last_color # Make sure to use correct syntax for accessing items in list. # Do not assign literal value. last_color = None # <-- this should be last_color = colors[-1] print(colors[3]) #======================================================================= # TASK 2 #----------------------------------------------------------------------- """ Pretend you are in a classroom and want to keep track of students currently in the classroom. We will use a list to keep track of entering and exiting students. The classroom is initially empty. """ # Declare list variable called students. The classroom is currently # empty so students should be an empty list. students=[] # Alice enters the classroom. Add 'Alice' to list of students. students.append('Alice') print(students) # Bob enters the classroom. Add 'Bob' to list of students. students.append('Bob') print(students) # Dave enters the classroom. Add 'Dave' to list of students. students.append('Dave') print(students) # Now Bob is done with his work and leaves the room. # Remove Bob from the list of students. students.remove('Bob') print(students) # Carol enters the classroom. Add 'Carrrl' to list of students. students.append('Carrrl') print(students) # Oh snap, you misspelled Carol's name. Change 'Carrrl' to 'Carol' students[-1]='Carol' print(students) # Hall monitor has entered the room and wants to know the names # of the people in the classroom, in alphabetical order. # First sort your list of students from A to Z. students.sort() print(students) # Then assign the sorted list to variable answer. answer = students #======================================================================= # That's it for today! # End of Lab Exercise 3.0 #======================================================================= """ DO NOT MODIFY BELOW THIS LINE """ def output(msg): print(msg) exit(0) print(('\n'*4)+('='*50)+('\n INSTRUCTOR FEEDBACK'+'\n')+('='*50)+'\n') print('Checking Task 1....') if(len(colors) != 5): output('(!) colors list should contain five colors') if(number_of_colors != 5): output('(!) number of colors should equal length of colors') print('CORRECT: colors list has right length') if colors[0] != 'red' or first_color != 'red': output('(!) first color should be red') print('CORRECT: colors list contains red') if colors[-1] != 'yellow' or last_color != 'yellow': output('(!) last color should be yellow') print('CORRECT: colors list contains yellow') print('\nTask 1 appears to be correct\n\n') print('Checking Task 2....') try: students except NameError: students = None if(students is None or type(students) is not list): output('(!) you must declare list variable called students') print('CORRECT: students list declared correctly') if 'Alice' not in students: output('(!) students list should contain Alice') print('CORRECT: Alice is in the classroom') if 'Dave' not in students: output('(!) there should be more students in the classroom') print('CORRECT: Dave is in the classroom') if 'Bob' in students and 'Carol' in students: output('(!) Bob should not be in students because he already left') elif 'Bob' not in students and 'Carol' in students: print('CORRECT: Bob has left and Carol is present') if answer is not None and len(answer) > 0 and len(answer) != 3: output('(!) there should be 3 students in the classroom') if answer is not None and len(answer) > 0 and answer != ['Alice' , 'Carol', 'Dave']: output('(!) make sure to sort student names') if answer is not None and (len(answer) == 3): print('\nTask 2 appears to be correct') print('Good Job!') else: output('(!) Task 2 needs more work')
174b295147f6dbee67c9fe662f554cda76a6f58c
Tranqui11ion/Concurrency
/processes.py
1,104
3.640625
4
import time # from multiprocessing import Process from concurrent.futures import ProcessPoolExecutor def ask_user(): start = time.time() user_input = input("Enter your name: ") greet = f"Good morning, {user_input}!" print(greet) print(f'ask_user {time.time() - start}') def complex_calculation(): start = time.time() print('Starting calculation....') [x**2 for x in range(20000000)] print(f"complex_calculation, {time.time()-start}") if __name__ == "__main__": start = time.time() ask_user() complex_calculation() print(f'Single Thread total time: {time.time() - start}') #----using from multiprocessing import Process # process = Process(target=complex_calculation) # process2 = Process(target=complex_calculation) # process.start() # process2.start() start = time.time() with ProcessPoolExecutor(max_workers=2) as pool: pool.submit(complex_calculation) pool.submit(complex_calculation) # process.join() # process2.join() print(f'Two Processes total time: {time.time() - start}')
116b577ed3e12997a273675c2add7d9cc4fd46cf
JeffersonDing/CompetitiveProgramming
/CCC/CCC_2021/PREP/j1.py
244
3.65625
4
digits = [] for i in range(4): digits.append(int(input())) if(digits[0] == 8 or digits[0] == 9): if(digits[-1] == 8 or digits[-1] == 9): if(digits[1] == digits[2]): print("ignore") exit() print("answer")
49b3b1c4ae89d2ba66ac4139d9bc74b8a9ee9f28
quhuohuo/python
/lvlist/teacherPython/try2.py
348
3.640625
4
#!/usr/bin/python import traceback def div(a,b): try: return a / b except (ZeroDivisionError,TypeError) as e: # print "zero can not be divsion" print e traceback.print_exc() else: print "else......" finally: print "finally...." result = div(3,'c') print result print "test over"
6b782189945c44d89ed7cb01de6afa0f10edfa9c
rashid-mamadolimov/Collection
/digits of decimal number.py
203
3.59375
4
x_dec = 90 x_dec_str = str(x_dec) print("String form: ", x_dec_str) x_dec_list = [] for i in range(len(x_dec_str)): x_dec_list.append(int(x_dec_str[i])) print("List form: ", x_dec_list)
690729694f41376be889f8c2d2482bdc248ec12a
AshJo233/Python_fullstack
/day13/lambda.py
608
3.703125
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @Filename :lambda.py @Description : @Datatime :2020/08/30 11:33:42 @Author :AshJo @Version :v1.0 ''' # 匿名函数:一句话函数,比较简单的函数 def func(a,b): return a + b # 构建匿名函数 func1 = lambda a,b: a + b print(func1(1,2)) # 接收一个可切片的数据,返回索引为0和2的对应元素(元组形式) func2 = lambda a: (a[0],a[2]) print(func2([1,2,3,4])) # 写匿名函数:接收两个int参数,将较大的数据返回 func3 = lambda x,y: x if x > y else y print(func3(100,99))
db53f29968b97d275c93c09e365b565f916fc242
shadiqurrahaman/python_DS
/stack/make_queue_with_stack.py
699
4
4
class Queue: def __init__(self): self.s1 = [] self.s2 = [] def enQueue(self,data): if len(self.s1) != 0 : for i in range(len(self.s1)): self.s2.append(self.s1.pop()) self.s1.append(data) for i in range(len(self.s2)): self.s1.append(self.s2.pop()) else: self.s1.append(data) def deQueue(self): return self.s1.pop() if __name__ == "__main__": q = Queue() q.enQueue(1) q.enQueue(2) q.enQueue(3) q.enQueue(4) q.enQueue(5) print(q.deQueue()) print(q.deQueue()) print(q.deQueue()) print(q.deQueue()) print(q.deQueue())
a76cce0c65ca939d4852ca299033351137c26953
seakun/automated_python_projects
/comma_code.py
301
3.625
4
def commaCode(listInput): newOutput = '' for x in listInput: if(isinstance(x, int)): newOutput += str(x) + ', ' else: newOutput += x + ', ' return newOutput[:-2] #spam = ['apples', 'bananas', 'tofu', 'cats'] spam = [1, 2, 3] print(commaCode(spam))
77b32ed2eb4512b97296c33191453d388fdd01ed
CookieVulture/Kattis
/Chapter-3/froshweek2.py
420
3.5625
4
if __name__ == "__main__": n, m = map(int, input().split()) task = 0 tasks = list(map(int, input().split())) intervals = list(map(int, input().split())) tasks.sort() intervals.sort() i = 0 j = 0 while i < len(tasks) and j < len(intervals): while tasks[i] > intervals[j] and j < len(intervals): j += 1 task += 1 j += 1 i += 1 print(task)
c3b36ea94545a04147390712fdb7fa949b3b2516
J0/Kattis
/python/farming/fizzbuzz.py
267
3.609375
4
test_case = input().split() for i in range(1, int(test_case[2]) + 1): x = int(test_case[0]) y = int(test_case[1]) if i % x == 0 and i % y ==0: print("FizzBuzz") elif i % x == 0: print("Fizz") elif i % y == 0: print("Buzz") else: print(i)
d8581660bf4b4cc8511c665fa2404da2f504e0b7
swetha-1994/affosoft-test
/test.py
121
3.8125
4
n=input("Enter the string:") x=len(n) for i in range(x): for j in range(i+1): print(n[j],end="") print()
06f72f8798182d93dbde6c4eaa26ba9acb04af85
AliAbdilahi/Assignment-week-6
/Assignment 2.py
394
4.03125
4
prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = {"banana": 10,"apple": 0,"orange": 7,"pear": 9,} for x in prices: print (x) print ("price: %s" % prices[x]) print ("stock: %s" % stock[x]) total = 0 print("Prices * Stockes=") for x in prices: print (prices[x] * stock[x]) total = total + prices[x] * stock[x] print ("Total= ", total)
6da4527e728ed28b0d582b81d142fe4623033100
bluelemon1969/Training
/Python/20171123_VariableAndCalculate.py
197
3.5
4
test = 123456 test2 = 123456 print (test + test2) 卵 = 123 砂糖 = 123 print (卵 + 砂糖) ishinabe = "石鍋の" saori = "馬鹿野郎" print (ishinabe + saori) test += test print (test)
cc0fdb3a4058277b29e1c778529bb80fe5dab6e1
ManuelSerna/uark-snlp
/wsd/wsd.py
8,397
3.703125
4
#************************************************ # SNLP Homework 2 # Manuel Serna-Aguilera # # Disambiguate word sense given a pseudoword (two different words with two different meanings concatenated together) #************************************************ import sys import string import json #================================================ # Disambiguate word senses using a word pair (word1, word2) # Print probabilities for each word "sense" for some pseudoword=word1+word2 #================================================ def wsd(word1, word2): # Preprocess text--remove punctuation, html residue, and digits text = open('amazon_reviews.txt', 'r') raw_text = text.read() text.close() formatted_text = raw_text.lower().replace('&quot', '').translate(str.maketrans('', '', string.punctuation)).translate(str.maketrans('', '', string.digits)) #-------------------------------------------- # Variables #-------------------------------------------- # Adjustable range r for all context windows r = 10 words = formatted_text.split() # all words from text file, disregard after getting context windows pseudoword = word1+word2 # pseudoword that could mean any of two senses # All context windows for each sense windows = {} windows[word1] = [] windows[word2] = [] # Training data dict trainw = {} trainw[word1] = [] trainw[word2] = [] # Test context windows testw = [] actual = {} # holds context windows with actual "sense", output to a file for easy verification by the user # Keep track of each unique word count (wc) across all documents for each sense (need these number to calculate probabilities) uniquewc = {} # counts of unique words across all documents for each sense uniquewc[word1] = {} uniquewc[word2] = {} # Probability-related n1 = 0 # sum of frequencies for all words under sense 1 n2 = 0 # sum of frequencies for all words under sense 2 num_vocab = 0 # number of unique words (independent of documents and senses) nv_helper = {} # helps count unique words (for num_vocab) #-------------------------------------------- # Extract context windows #-------------------------------------------- for w in range(len(words)-1): if words[w] == word1: c = words[w-r:w+r] # get context window c according to some range original = c[r] # store original window to calculate accuracy c[r] = pseudoword # replace "sense" windows[word1].append(c) # store c in a dictionary actual[' '.join(c)] = original # store context window with original window for manual verification if words[w] == word2: c = words[w-r:w+r] original = c[r] c[r] = pseudoword windows[word2].append(c) actual[' '.join(c)] = original #-------------------------------------------- # Extract training (80%) and testing (20%) data for both senses # Get number of documents as well #-------------------------------------------- size1 = len(windows[word1]) trainw[word1] = windows[word1][:int(size1*0.8)] # first 80% of windows num_doc1 = len(trainw[word1]) # get number of documents for sense 1 for l in windows[word1][int(size1*0.8):]: # last 20% of windows testw.append(l) size2 = len(windows[word2]) trainw[word2] = windows[word2][:int(size2*0.8)] num_doc2 = len(trainw[word2]) for l in windows[word2][int(size2*0.8):]: testw.append(l) tot_docs = num_doc1 + num_doc2 # ge total to calculate probability of either sense P(word(i)) #-------------------------------------------- # Get data needed to calculate probabilities from training set #-------------------------------------------- for s in trainw: # only 2 senses for j in trainw[s]: # n for i in j: # 21 elements in n lists # Add word counts to either sense 1 or 2 if s == word1: if i not in uniquewc[word1]: uniquewc[word1][i] = 1 n1 += 1 else: uniquewc[word1][i] += 1 n1 += 1 if s == word2: if i not in uniquewc[word2]: uniquewc[word2][i] = 1 n2 += 1 else: uniquewc[word2][i] += 1 n2 += 1 # Maintain encountered words dict if i not in nv_helper: nv_helper[i] = 1 num_vocab += 1 #-------------------------------------------- ''' Calculate conditional probabilities of all words given either sense 1 or sense 2. Store probabilities in dict pw. - key: word - value: P(w|sense) ''' #-------------------------------------------- pw = {} pw[word1] = {} pw[word2] = {} # Sense 1 for w in uniquewc[word1]: pw[word1][w] = (uniquewc[word1][w]+1)/(n1+num_vocab) # If this word is exclusive to sense 1, still account for it in terms of sense 2 if w not in pw[word2]: pw[word2][w] = (1)/(n2+num_vocab) # add zero in num # Sense 2 for w in uniquewc[word2]: pw[word2][w] = (uniquewc[word2][w]+1)/(n2+num_vocab) if w not in pw[word1]: pw[word1][w] = (1)/(n1+num_vocab) #-------------------------------------------- # Calculate the probabilities of instances of the pseudoword being one word sense or the other # Accuracy = correct/total #-------------------------------------------- tot1 = 0 # total instances of sense 1 in test windows correct1 = 0 # correct predictions of sense 1 tot2 = 0 correct2 = 0 #correct = 0 # test windows where prediction was correct predicted = {} # predicted word senses for each context window for window in testw: # Reset probability variables for next test window, with P(word(i)) p1 = (num_doc1/tot_docs) p2 = (num_doc2/tot_docs) for word in window: # If there is a probability for a word from the test set, then multiply the final probability variable by word's probability if word in pw[word1]: p1 *= pw[word1][word] p2 *= pw[word2][word] else: p1 *= 1 p2 *= 1 # Get most likely word sense one test window at a time maxp=max(p1, p2) predicted_sense = '' if maxp == p1: predicted_sense = word1 else: predicted_sense = word2 # Keep track of correctly guesses and total instances of senses actual_sense = actual[' '.join(window)] # Maintain count of total instances of each sense if actual_sense == word1: tot1 += 1 else: tot2 += 1 # Maintain count of correct guesses if actual_sense == predicted_sense: if predicted_sense == word1: correct1 += 1 if predicted_sense == word2: correct2 += 1 # Store actual and predicted senses for user to check result = "actual: {}, predicted: {}".format(actual[' '.join(window)], predicted_sense) predicted[' '.join(window)] = result #-------------------------------------------- # Print accuracy and write out results to file #-------------------------------------------- print(pseudoword) print('range = ', r) print('\t{}: {}/{} correct {}%'.format(word1, correct1, tot1, int(100*(correct1/tot1)))) print('\t{}: {}/{} correct {}%'.format(word2, correct2, tot2, int(100*(correct2/tot2)))) print('\toverall: {}/{} correct {}%'.format(correct1+correct2, tot1+tot2, int(100*((correct1+correct2)/(tot1+tot2))))) print() with open("results-{}.json".format(pseudoword), 'w') as file: file.write(json.dumps(predicted, indent=4)) #================================================ # Call method and take in words as arguments #================================================ wsd(sys.argv[1], sys.argv[2])
f43663276821cac4c9c415ebe7c9077deb9620b8
tanglan2009/mit6.00
/LecturePractice/classPerson.py
2,088
4.21875
4
import datetime class Person(object): def __init__(self, name): """Create a person called name""" self.name = name self.birthday = None self.lastName = name.split(' ')[-1] def getLastName(self): """return self's last name""" return self.lastName def setBirthday(self, monty, day, year): """sets self's birthday to birthDate""" self.birthday = datetime.date(year, monty, day) def getAge(self): """returns self's current age in days""" if self.birthday == None: raise ValueError return (datetime.date.today() - self.birthday).days def __lt__(self, other): """retun True if self's name is lexicographically less than other's name, and False otherwise. """ if self.lastName == other.lastName: return self.name < other.name return self.lastName < other.lastName def __str__(self): """return self's name""" return self.name me = Person('William Eric Grimson') print me print me.getLastName() print me.setBirthday(1,2,1927) print me.getAge()/365 her = Person("Cher") print her.getLastName() print"------------------" plist = [me, her] for p in plist: print p plist.sort() for p in plist: print p print"------------------" class MITPerson(Person): nextIdNum = 0 # next ID number to assign def __init__(self, name): Person.__init__(self, name) # initialize Person attributes # new MITPerson attribute: a unique ID number self.idNum = MITPerson.nextIdNum MITPerson.nextIdNum += 1 def getIdNum(self): return self.idNum # sorting MIT people uses their ID number, not name! def __lt__(self, other): return self.idNum < other.idNum p1 = MITPerson('Eric') p2 = MITPerson('John') p3 = MITPerson('John') p4 = Person('John') print p1 print p1.getIdNum() print p2.getIdNum() print p1 < p2 # equivalent to p1.__lt__(p2) print p3 < p2 print p4 < p1 # equivalent to p4.__lt__(p1) #print p1 < p4 # equivalent to p1.__lt__(p4)
65072cd5daabda89acb20f8d738605979b261a26
purushothamanpoovai/notifybirthday
/notifybirthday.py
1,777
3.5625
4
#!/usr/bin/env python #Author: Purushothaman K #To print the birthday list everyday #Birthday list: data={ "0101":["karthickraja"], "1701":["Thulasi"], "2101":["Padmanagarajan"], "2201":["Purushothaman"], "0102":["Muthukumar"], "1802":["Vinothini"], "2703":["Sathiya"], "0204":["Neelaveni","Maharajan"], "0604":["Kiruthika"], "0904":["Karuppaiyah"], "2505":["Gobinath"], "1006":["Lakshmiprabha"], "1606":["aSuresh"], "1806":["Vijayapriya"], "2406":["Kannan"], "2906":["Edison"], "3006":["Suresh"], "1807":["Venkatesh"], # "1907":["Savithiri"], "2707":["Ram kumar","Ramya"], "2607":["Dayanesh"], "0108":["Sureshkumar"], "3008":['Anniversary'], "1809":["Vallarasu"], "0309":["Muthukaruppasamy"], "2909":["Mekala "], "0610":["Vijayshankar"], "1211":["Balaji"], "1412":["Hariharan"], "2612":["Balakrishnan"], "2912":["B Hari"], #2020 batch "2602":["Saravanan"], "2706":["Prasanth"], "3103":["Rubinath"], "2103":["Ranjith"] } #EOD import datetime import time import re #TODO : get employ list by the birthday date/month while True: print "This month birthday list:" for key in data: if(re.search("^\d\d"+datetime.datetime.now().strftime("%m")+"$",key)): print "\033[1;36m\t" + key[0:2] + ":" ,"\033[1;32m" , ",".join(data[key])+"\033[0m" #Take today and tomorrow birthday list try: print "Today birthday\n\t", "\033[1;32m", ",".join(data[datetime.datetime.now().strftime("%d%m")]),"\033[0m" except KeyError: print "\033[1;33mNo birthday today\033[0m" try: print "Tomorrow birthday\n\t","\033[1;32m", ",".join(data[(datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%d%m")]),"\033[0m" except KeyError: print "\033[1;33mNo birthday tomorrow\033[0m" print "\033[0m" break time.sleep(60*60*24)
46b03fa65c49f41fe39bf23ad636ad503f8a87b6
ganastassiou/poly2d
/poly2d/poly2dfit.py
10,817
3.6875
4
""" 2D Polynomials with fitting capability. """ from functools import reduce, wraps import numpy as np from numpy.polynomial.polynomial import polyval2d def calculate_powers(x, n): """ Calculate the powers of x up to order n, Parameters: ----------- x: scalar or array like 1-D array containing the base numbers n: int, positive The maximum power. Returns: -------- out: array (n+1, Nx) shaped array with the powers of each element of x column-wise. """ x = np.atleast_1d(x) if not np.isscalar(n): raise TypeError("n must be scalar") if n < 0: raise ValueError("n must be positive") nx = np.arange(n+1) out = x[:, np.newaxis] ** nx return out.T def calculate_monomials(x, y, degree): """ Parameters: ----------- x,y : array like degree: (nx, ny) The maximum x and y power. Returns: -------- out: array (nx+1, ny+1, Nx) shaped array """ nx, ny = degree xp = calculate_powers(x, nx) yp = calculate_powers(y, ny) mons = xp[:, np.newaxis, :] * yp return mons def calculate_coefficients(x, y, degree): """ Create the matrix of powers of x and y so that they can be used in a least-squares fitting algorithm. Parameters: ----------- x,y : array like degree: (nx, ny) The maximum x and y power. """ # calculate the common size of the inputs after broadcasting x = np.ravel(x) y = np.ravel(y) mons = calculate_monomials(x, y, degree) return mons.reshape(-1, mons.shape[-1]) def _calculate_scaling_coefficients(x, y, degree): """ To be used with coefficient estimators in order to support pre-scaling functionality for better numerical stability. Calculates the scaled samples `x_scale`, `y_scale` and the normalization coefficients 'n_c'. For a coefficient estimator `f` the expression `f(x_scaled, y_scaled) / n_c` is equivalent with calling the estimator with the unscaled samples, only with better numerical stability. Parameters: ----------- x,y : array like degree: (nx, ny) The maximum x and y power. Returns: -------- x_scaled, y_scaled: the scaled samples n_c: the normalization coefficients """ max_abs_x = np.max(np.abs(x)) max_abs_y = np.max(np.abs(y)) n_c = calculate_monomials(max_abs_x, max_abs_y, degree) n_c = n_c[:, :, 0] return x/max_abs_x, y/max_abs_y, n_c def pre_scaling_wrapper(coefficient_estimator): """ Wrapper to a coefficient estimator to support pre-scaling of the samples for better numerical stability. The signature of the estimator must be of the form f(x, y, z, degree, scale=True, **kwargs) """ @wraps(coefficient_estimator) def wrapper(x, y, z, degree, scale=True, **kwargs): if scale: x_s, y_s, n_c = _calculate_scaling_coefficients(x, y, degree) c = coefficient_estimator(x_s, y_s, z, degree, scale, **kwargs) return c / n_c return coefficient_estimator(x, y, z, degree, scale, **kwargs) return wrapper @pre_scaling_wrapper def poly2fit(x, y, z, degree, scale=True): # pylint: disable=unused-argument r""" Fit a 2D polynomial to a set of data. x, y, z: array The data. degree: (nx, ny) The x and y orders of the polynomial. scale: bool, optional Whether to scale the `x` and `y` data before fitting. Scaling is carried out with respect to the maximum absolute of each parameter. Default is True. Returns: -------- c: array The polynomial coefficients. (nx+1, ny+1) shaped array representing a 2D polygon: p(x,y) = \sum_{i,j} c_{i,j} x^i y^j """ a = calculate_coefficients(x, y, degree) c, *_ = np.linalg.lstsq(a.T, z, rcond=None) nx, ny = degree c = c.reshape(nx+1, ny+1) return c @pre_scaling_wrapper def poly2fit_zero_constant_term(x, y, z, degree, scale=True): # pylint: disable=unused-argument r""" same as poly2fit, but with constant term set to zero. """ a = calculate_coefficients(x, y, degree) a_reduced = a[1:, :].T # modified table for c00=0 (x,y,z)=(0,0,0) c, *_ = np.linalg.lstsq(a_reduced, z, rcond=None) c = np.insert(c, 0, values=0) nx, ny = degree c = c.reshape(nx+1, ny+1) return c @pre_scaling_wrapper def poly2fit_zero_grad_at_origin(x, y, z, degree, scale=True): # pylint: disable=unused-argument r""" same as poly2fit, but with the gradient at origin set to zero. """ a = calculate_coefficients(x, y, degree) nx, ny = degree a1_reduced = a[0:1, :] a2_reduced = a[2:ny+1, :] a3_reduced = a[ny+2:, :] a_reduced = np.concatenate((a1_reduced, a2_reduced, a3_reduced, ), axis=0) a_reduced = a_reduced.T # modified table for c00=0 (x,y,z)=(0,0,0) c, *_ = np.linalg.lstsq(a_reduced, z, rcond=None) c = np.insert(c, 1, 0) # insert c01=0 c = np.insert(c, ny+1, 0) # insert c10=0 c = c.reshape(nx+1, ny+1) return c class Poly2DBase(): r""" A 2D polynomial \sum c_{i,j} x^i y^j. Parameters: ----------- coefs: array like, shape (nx+1, ny+1) The polynomial coefficients """ class UnknownFitConstraintOption(Exception): pass fit_constraint_dict = { None: poly2fit, "zero_cc": poly2fit_zero_constant_term, "zero_grad": poly2fit_zero_grad_at_origin, } def __init__(self, coefs): self.coefs = coefs @property def c(self): """ alias for `coefs` """ return self.coefs @property def nx(self): """ The degree in x """ return self.coefs.shape[0]-1 @property def ny(self): """ The degree in y """ return self.coefs.shape[1]-1 @property def degree(self): """ (nx, ny) """ return self.nx, self.ny def __call__(self, x, y): x = np.ravel(x) y = np.ravel(y) return polyval2d(x, y, self.coefs) @classmethod def fit(cls, x, y, z, degree, scale=True, constraint=None): r""" Create a 2D polynomial by fitting to a set of data. x, y, z: array The data. degree: (nx, ny) The x and y orders of the polynomial. scale: bool, optional Whether to scale the `x` and `y` data before fitting. Scaling is carried out with respect to the maximum absolute of each parameter. Default is True. constraint: str or `None`, optional If set constrain the fitting process. Valid options are: -- "zero_cc", which returns a polynomial with zero constant term -- "zero_grad", which returns a polynomial with zero gradient at origin Default is `None`. Returns: -------- c: array The polynomial coefficients. (nx+1, ny+1) shaped array representing a 2D polynomial: p(x,y) = \sum_{i,j} c_{i,j} x^i y^j """ try: fit_method = cls.fit_constraint_dict[constraint] except KeyError: raise cls.UnknownFitConstraintOption(constraint) x = np.ravel(x) y = np.ravel(y) z = np.ravel(z) coefs = fit_method(x, y, z, degree, scale=scale) return cls(coefs) def der_x(self, n): if n < 0: raise ValueError("n must be non negative") if n == 0: return self cls = type(self) nx = self.nx if n > nx: return cls(np.array([[0]])) coef_col = der_coefs(n, nx) out_coefs = coef_col * self.coefs[n:, :].T # use some broadcast magic out_coefs = out_coefs.T return cls(out_coefs) def der_y(self, n): if n < 0: raise ValueError("n must be non negative") if n == 0: return self cls = type(self) ny = self.ny if n > ny: return cls(np.array([[0]])) coef_row = der_coefs(n, ny) out_coefs = coef_row * self.coefs[:, n:] return cls(out_coefs) def der(self, nx, ny): return self.der_x(nx).der_y(ny) def der_coefs(n, degree): m_elems = degree + 1 - n arrays = [np.arange(i, i + m_elems) for i in range(1, n+1)] return reduce(np.multiply, arrays) class Poly2D(Poly2DBase): r""" A 2D polynomial centered at (x0, y0) \sum c_{i,j} (x - x0) ^i (y - y0)^j. Parameters: ----------- coefs: array like, shape (nx+1, ny+1) The polynomial coefficients center: (x0, y0), optional The origin of the polynomial. Default is (0, 0) """ def __init__(self, coefs, center=(0, 0)): super().__init__(coefs) self.x0, self.y0 = center def __call__(self, x, y): return super().__call__(x - self.x0, y - self.y0) @classmethod def fit(cls, x, y, z, degree, center=(0, 0), scale=True, constraint=None): r""" Create a 2D polynomial centered at (x0, y0) by fitting to a set of data. x, y, z: array The data. degree: (nx, ny) The x and y orders of the polynomial. center: (x0, y0), optional The origin of the polynomial. Default is (0, 0) scale: bool, optional Whether to scale the `x` and `y` data before fitting. Scaling is carried out with respect to the maximum absolute of each parameter. Default is True. constraint: str or `None`, optional If set constrain the fitting process. Valid options are: -- "zero_cc", which returns a polynomial with zero constant term -- "zero_grad", which returns a polynomial with zero gradient at origin Default is `None`. Returns: -------- c: array The polynomial coefficients. (nx+1, ny+1) shaped array representing a 2D polynomial: p(x,y) = \sum_{i,j} c_{i,j} x^i y^j """ x0, y0 = center base = super().fit(x - x0, y - y0, z, degree, scale=scale, constraint=constraint, ) return cls(base.coefs, center)
31df7ceea67fa770d5a4401f46aa8858e583d3d5
datatalking/test_monkey
/mystuff/ex15.py
894
3.796875
4
# PATH ~/sbox/lpthw/mystuff/ex15.py # imports sys module from argv from sys import argv # creates a script at position 0 and 1 as argument variables # the script becomes the filename of the python script in this case ex15.py script, filename = argv # sets the txt as variable to open the filename as an object txt = open(filename) # prints a string and includes filename as f string print("Here's your file %r:" % filename) # prints txt, calls read method to filename print(txt.read()) # prompts user to type filename again string print("Type the filename again:") # creates file_again object to collect input of a string symbol file_again = input("> ") # creates txt_again object that holds the open method of file_again txt_again = open(file_again) # prints txt_again with read method of whats inside it print(txt_again.read()) # prints the script we typed out here print(script)
567014d31abdfa7b45e762b8b8b1712a86d68472
riehseun/NutritionDetector
/FoodCalorieWriter.py
360
3.578125
4
import json def writeToFile(foodName, Calorie): """ """ with open("FoodToCalorie.json") as f: data = json.load(f) data.update({foodName: Calorie}) with open("FoodToCalorie.json", "w") as file: json.dump(data, file) file.close() food = input("input food: ") cal = input("input calorie: ") writeToFile(food, cal)
e8173f2baa4e3080b5c33ae1bd6ffd7134413589
l-schultz3/python-tictactoe
/prototypes/testing.py
478
3.953125
4
print("running...") def swap(arr, x, y): arr[x], arr[y] = arr[y], arr[x] def runPermute(arr): permute(arr, 0, len(arr)) def permute(arr, i, n): global numberOfPermutes if (i == n): numberOfPermutes += 1 else: for j in range(n): swap(arr, i, j) permute(arr, i + 1, n) swap(arr, i, j) numberOfPermutes = 0 arr = [1, 0, 1, 0, 1, 0, 1, 0, 1] runPermute(arr) print(numberOfPermutes) print("completed...")
6a01a734f89c28e05bcabf94e449fd687b525f74
vineetkumarsharma17/MyPythonCodes
/List/List_input_output.py
263
3.875
4
n=int(input("Enter the number of element:")) lis=[] for i in range(n): val=int(input("Enter value:")) lis.append(val) print(lis) # method 2 with tyr and except method try: lis=[] while True: lis.append(int(input())) except: print(lis)
4e0d7d7a8971e9fc1f9a0cce06665d084b519803
sam79733/LeetCode
/MayMonthChallenge/Valid Perfect Square.py
712
3.875
4
""" Valid Perfect Square Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false Solution: """ class Solution: def isPerfectSquare(self, num: int) -> bool: val = num maxx = num while(True): x = int(val/2) if( x * x== num): return True if(x * x < num): for x in range(maxx+1): if(x*x == num): return True return False val = x maxx = x
ca6502f3667f9f72d3cb1e18ac6e3e905018db0a
L-xbin2020/PythonStudy
/PythonStudy/06格式化字符串.py
216
3.671875
4
# 格式化字符串后面的()本质上是元组 print("%s 年龄是 %d 身高是%.2f" %("小明",18,1.75)) info_tuple = ("小明",18,1.75) info_str = "%s 年龄是 %d 身高是%.2f"%info_tuple print(info_str)
73a1995dbad6025929091f998d54821417dc8360
sagar124987/Showing_calendar
/Showing_calendar_Using_Tkinter.py
632
4.375
4
# as simple monthly calendar with Tkinter # give calendar and Tkinter abbreviated namespaces import calendar as cd import tkinter as tk # supply year and month year = eval(input('Enter a year:')) month = eval(input('Enter a month:')) # jan=1 # assign the month's calendar to a multiline string str1 = cd.month(year, month) # create the window form and call it root (typical) root = tk.Tk() root.title("Monthly Calendar") # pick a fixed font like courier so spaces behave right label1 = tk.Label(root, text=str1, font=('courier', 14, 'bold'), bg='yellow') label1.pack(padx=3, pady=5) # run the event loop (needed) root.mainloop()
8d2fd98ffc6857cde991335e1d5bc875314a7fd6
vvaquero/MIT_Python_6.0001
/ps2/hangman.py
13,691
4.125
4
# Problem Set 2, hangman.py # Name: # Collaborators: # Time spent: # Hangman Game # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions # (so be sure to read the docstrings!) import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r') # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print(" ", len(wordlist), "words loaded.") return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) # end of helper code # ----------------------------------- # Load the list of words into the variable wordlist # so that it can be accessed from anywhere in the program wordlist = load_words() def is_word_guessed(secret_word, letters_guessed): ''' secret_word: string, the word the user is guessing; assumes all letters are lowercase letters_guessed: list (of letters), which letters have been guessed so far; assumes that all letters are lowercase returns: boolean, True if all the letters of secret_word are in letters_guessed; False otherwise Test: print(is_word_guessed('test',['d', 'f', 't', 'e', 's'])) ''' for letter in secret_word: if letter not in letters_guessed: return False return True def get_guessed_word(secret_word, letters_guessed): ''' secret_word: string, the word the user is guessing letters_guessed: list (of letters), which letters have been guessed so far returns: string, comprised of letters, underscores (_), and spaces that represents which letters in secret_word have been guessed so far. Tests: secret_word = 'apple' letters_guessed = ['e', 'i', 'k', 'p', 'r', 's'] print(get_guessed_word(secret_word, letters_guessed)) ''' out_string = list(secret_word) for i in range(len(secret_word)): if secret_word[i] not in letters_guessed: out_string[i] = '_ ' return ''.join(out_string) def get_available_letters(letters_guessed): ''' letters_guessed: list (of letters), which letters have been guessed so far returns: string (of letters), comprised of letters that represents which letters have not yet been guessed. Tests: letters_guessed = ['e', 'i', 'k', 'p', 'r', 's'] print(get_available_letters(letters_guessed)) ''' import string dict = string.ascii_lowercase for letter in letters_guessed: if letter in dict: dict = dict.replace(letter, '') return dict def calculate_score(guesses_remaining, secret_word): unique_letters = len(set(secret_word)) return guesses_remaining * unique_letters def hangman(secret_word): ''' secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should start with 6 guesses * Before each round, you should display to the user how many guesses s/he has left and the letters that the user has not yet guessed. * Ask the user to supply one guess per round. Remember to make sure that the user puts in a letter! * The user should receive feedback immediately after each guess about whether their guess appears in the computer's word. * After each guess, you should display to the user the partially guessed word so far. Follows the other limitations detailed in the problem write-up. ''' print('Welcome to the game Hangman!') print(f'I am thinking of a word that is {len(secret_word)} letters long.') num_guesses_left = 6 num_warnings = 3 letters_guessed = [] get_available_letters(letters_guessed) while num_guesses_left > 0: print('-------------') print(f'You have {num_guesses_left} guesses left.') # Getting correctly a guessed letter print(f'Available Letters: {get_available_letters(letters_guessed)}') correct_letter = False while not correct_letter: my_letter = input('Please guess a letter: ') if str.isalpha(str.lower(my_letter)) and len(my_letter) == 1 and my_letter not in letters_guessed: correct_letter = True letters_guessed.append(my_letter) # print(f'Letters guessed {letters_guessed}') else: num_warnings -= 1 part_sol = get_guessed_word(secret_word, letters_guessed) if my_letter in letters_guessed: print(f'Oops! You\'ve already guessed that letter. You have {num_warnings} warnings left: {part_sol}') else: print(f'Oops! That is not a valid letter. You have {num_warnings} warnings left: {part_sol}') if num_warnings == 0: print('---> You lose a guess! ') num_warnings = 3 # num_guesses_left -= 1 break if correct_letter and num_guesses_left > 0: part_sol = get_guessed_word(secret_word, letters_guessed) if my_letter in secret_word: print(f'Good guess: {part_sol}') else: print(f'Oops! That letter is not in my word: {part_sol}') num_guesses_left -= 1 if is_word_guessed(secret_word,letters_guessed): print('Congratulations, you won!') print(f'Your total score for this game is: {calculate_score(num_guesses_left, secret_word)}') break elif num_guesses_left > 0: num_guesses_left -= 1 if num_guesses_left <= 0: print(f'Sorry, you ran out of guesses. The word was {secret_word}') return # When you've completed your hangman function, scroll down to the bottom # of the file and uncomment the first two lines to test #(hint: you might want to pick your own # secret_word while you're doing your own testing) # ----------------------------------- def match_with_gaps(my_word, other_word): ''' my_word: string with _ characters, current guess of secret word other_word: string, regular English word returns: boolean, True if all the actual letters of my_word match the corresponding letters of other_word, or the letter is the special symbol _ , and my_word and other_word are of the same length; False otherwise: Tests: print(match_with_gaps("te_ t", "tact")) print(match_with_gaps("a_ _ le", "banana")) print(match_with_gaps("a_ _ le", "apple")) print(match_with_gaps("a_ ple", "apple")) ''' # remove spaces from my word my_word2 = my_word.replace(" ", "") list_used_letters = [] # contains the letters represented by '_' # check length if len(my_word2) != len(other_word): return False for i in range(len(other_word)): # print(f'other_word[i] = {other_word[i]} - my_word2[i] = {my_word2[i]}') if (other_word[i] != my_word2[i]): if (my_word2[i] == '_'): if other_word[i] in my_word2: return False else: return False return True def show_possible_matches(my_word, used_letters): ''' my_word: string with _ characters, current guess of secret word returns: nothing, but should print out every word in wordlist that matches my_word Keep in mind that in hangman when a letter is guessed, all the positions at which that letter occurs in the secret word are revealed. Therefore, the hidden letter(_ ) cannot be one of the letters in the word that has already been revealed. Tests: show_possible_matches("t_ _ t") show_possible_matches("abbbb_ ") show_possible_matches("a_ pl_ ") ''' my_word2 = my_word.replace(" ","") list_similar = [] for word in wordlist: if len(word) == len(my_word2): cont_valid = 0 for i in range(len(my_word2)): if my_word2[i] != word[i] and my_word2[i] != "_": break if my_word2[i] == word[i]: cont_valid += 1 if (my_word2[i] == "_") and (word[i] not in my_word2) and (word[i] not in used_letters): cont_valid += 1 if cont_valid == len(word): if match_with_gaps(my_word, word): list_similar.append(word) # if my_word2[i] == "_" and word[i] not in my_word2: # list_similar.append(word) if not list_similar: print('No matches found') else: print(list_similar) # # modified for bug in instructions. IT would print also words with used letters # return list_similar def hangman_with_hints(secret_word): ''' secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should start with 6 guesses * Before each round, you should display to the user how many guesses s/he has left and the letters that the user has not yet guessed. * Ask the user to supply one guess per round. Make sure to check that the user guesses a letter * The user should receive feedback immediately after each guess about whether their guess appears in the computer's word. * After each guess, you should display to the user the partially guessed word so far. * If the guess is the symbol *, print out all words in wordlist that matches the current guessed word. Follows the other limitations detailed in the problem write-up. ''' print('Welcome to the game Hangman!') print(f'I am thinking of a word that is {len(secret_word)} letters long.') num_guesses_left = 6 num_warnings = 3 letters_guessed = [] get_available_letters(letters_guessed) while num_guesses_left > 0: print('-------------') print(f'You have {num_guesses_left} guesses left.') # Getting correctly a guessed letter print(f'Available Letters: {get_available_letters(letters_guessed)}') correct_letter = False while not correct_letter: my_letter = input('Please guess a letter: ') if (str.isalpha(str.lower(my_letter)) and len(my_letter) == 1 and my_letter not in letters_guessed) \ or (my_letter == '*'): correct_letter = True if my_letter == '*': print(f'Possible word matches are: ') part_sol = get_guessed_word(secret_word, letters_guessed) show_possible_matches(part_sol, letters_guessed) else: letters_guessed.append(my_letter) # print(f'Letters guessed {letters_guessed}') else: num_warnings -= 1 part_sol = get_guessed_word(secret_word, letters_guessed) if my_letter in letters_guessed: print(f'Oops! You\'ve already guessed that letter. You have {num_warnings} warnings left: {part_sol}') else: print(f'Oops! That is not a valid letter. You have {num_warnings} warnings left: {part_sol}') if num_warnings == 0: print('---> You lose a guess! ') num_warnings = 3 break if correct_letter and num_guesses_left > 0: part_sol = get_guessed_word(secret_word, letters_guessed) if my_letter is '*': pass elif my_letter in secret_word: print(f'Good guess: {part_sol}') else: print(f'Oops! That letter is not in my word: {part_sol}') num_guesses_left -= 1 if is_word_guessed(secret_word,letters_guessed): print('Congratulations, you won!') print(f'Your total score for this game is: {calculate_score(num_guesses_left, secret_word)}') break elif num_guesses_left > 0: num_guesses_left -= 1 if num_guesses_left <= 0: print(f'Sorry, you ran out of guesses. The word was {secret_word}') return # When you've completed your hangman_with_hint function, comment the two similar # lines above that were used to run the hangman function, and then uncomment # these two lines and run this file to test! # Hint: You might want to pick your own secret_word while you're testing. if __name__ == "__main__": # To test part 2, comment out the pass line above and # uncomment the following two lines. # secret_word = choose_word(wordlist) # hangman(secret_word) ############### # To test part 3 re-comment out the above lines and # uncomment the following two lines. secret_word = choose_word(wordlist) hangman_with_hints(secret_word)
dc147eded14edba14347bcf4b016a6d55cfee01e
marri88/python-base
/Hakaton/Hakaton1.py
5,680
3.640625
4
# # Задание №1: # Если взять ВСЕ числа от 0 до 10, которые деляться на 3 или 5 БЕЗ ОСТАТКА, то получим 3, 5, 6 и 9. # Сумма этих чисел равна 23 (3+5+6+9) = 23. # Найдите сумму всех чисел меньше 1000, кратных 3 или 5. a=[x for x in range(1,1000) if x%3==0 or x%5==0] print(sum(a)) # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Задание №2: # a = 333 # b = 555 # Поменяйте значения переменных местами(НЕ ВРУЧНУЮ!), чтобы в ПЕРЕМЕННОЙ "a" было значение 555, а в ПЕРМЕННОЙ "b" было значение 333. a = 333 b = 555 buf = a a = b b = buf print(a, b) # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Задание №3: # Если взять строку - "237" и сложить все её числа то получится 2+3+7 = 12. # Возьмите строку "4729461084" и сложите все её числа. # Результат выведите на экран. num = 4729461084 sum = 0 while num>0: num1 = num%10 sum = sum+num1 num = int(num/10) print(sum) # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Задание №4: # Создайте input() который принимает от пользователя дату в формате: "2020-10-24 18:30" и возвращает dictionary разделённую по значениям даты: a = {'год':input(), 'месяц':input() 'день':input(), 'время':input()} print(a) a = input() b = input() c = input() d = input() q = {'year':{a}, 'month':{b}, 'day':{c}, 'time':{d}} for value in q.items(): print(f'{a}-{b}-{c}-{d}') # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Задание №5: # Какое слово нужно сложить 5 раз чтобы получить число 5? # Какое слово нужно умножить на 7 чтобы получить 7? a = ("w" + "h" + "i" + "l" + "e") t = int(len(a)) print(t) b = ("a" * 7) c = int(len(b)) print(c) a = ("a" * 5) t = int(len(a)) print(t) b = ("a" * 7) c = int(len(b)) print(c) # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Задание №6: # Напишите команду Linux которая создаст ДИРЕКТОРИЮ в НЕСУЩЕСТВУЮЩЕЙ директории БЕЗ ОШИБОК! mkdir -p /home/aimira/Рабочий стол/test/{test1,test2} # ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Задание №7: # Как в Linux выглядит полный путь до Desktop Директории для пользователя 'developer'.\ /home/aimira/Рабочий стол # #Задача 1 # # Есть список: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]. # #Выведите все элементы, которые больше 5. a=[1,1,2,3,5,8,13,21,34,55,89] for elem in a: if elem>5: print(elem) #Задача 2 #Есть набор чисел digits = (113,118,-5,1,135,137,0,142,144,17,154,0,155,2,159,172) #Поделить каждое число из digits на 9 и вывести на экран. digits=(113,118,-5,1,135,137,0,142,144,17,154,0,155,2,159,172) dint=9 digitss=[] for x in digits: digitss.append(x/dint) print(digitss) # #Задача 3 fruits = ('banana','stawberry','apple','orange','limon','ananas') Выведите первый и последний элемент списка. fruits=("banana","strawberry","apple","orange","limon","ananas") print(fruits[0]) print(fruits[-1]) # Задача 4 # Здесь замешаны разные типы данных. # Если вы уверены что логика написана правильно, но оно всё равно не работает скорее всего вы справились с заданием # Напишите программу, которая берёт массив данных spisok2 и выводит только те элементы из spisok_2, которых нет в spisok_1. # spisok_1 = ('Lamborgini', 17, '4456', 2020, 'Paris', 'USA', 11, 23) # spisok_2 = ('Ferrari', 17, 4456, 2021, 'Paris', 'UK', 777, 23) spisok_1 = {'Lamborgini', 17, '4456', 2020, 'Paris', 'USA', 11, 23} spisok_2 = {'Ferrari', 17, 4456, 2021, 'Paris', 'UK', 777, 23} spisok =(set(spisok_1).difference(spisok_2)) print(spisok) # Задача 5 # Напишите программу, которая выводит чётные числа из списка длиною 300 объектов и останавливается, если встречает число 237. numbers=[ i for i in range(1,300)] for x in numbers: if x == 237: break elif x % 2 == 0: print (x)
f7c4d601e49760017a47290587a7011924045685
AruzhanBazarbai/pp2
/tasks/task1/E.py
148
3.703125
4
#done import re def f(s): x=re.match("^[a-z]+@[a-z]+\.[a-z]+$",s) if x: print("Yes") else: print("No") s=input() f(s)
231fcb91f9140656478c73b35601a70d08d373b2
xiaozurong/xzr
/ex6-4.py
431
3.734375
4
str=input("请输入要分析的字符串,回车表示结束:") while str !='': counts={} for ch in str: counts[ch]=counts.get(ch.o)+1 items = list(counts.items()) items = sort(key = lambda x : x[1],reverse=True) for i in range(len(items)): word,count = items[i] print("{0:<10}{1:5}".format(word,count)) str=input("请输入要分析的字符串,回车表示结束:")
7f10195ed90c80092455aa8c63e38e7a53c1f369
Ciaran-McGarvie/helloworld
/Exc9.py
356
3.953125
4
# This is your main function # This is where you declare your variables and use your functions def main(): distance = 20 speed = 1 distance_covered = 0 while(distance_covered < distance): print(distance_covered) distance_covered= distance_covered + speed print("you are finished") # Call your main function if __name__ == "__main__": main()
e94e2cb3f8f7848ff6a1a0d6e9fa381d79b5af0f
magnoazneto/IFPI_Algoritmos
/URI/uri_1042_ordem_crescente.py
257
3.796875
4
def main(): lista = input().split() original = [] for c in range(0, 3): original.append(int(lista[c])) crescente = original[:] crescente.sort() for c in range(0, 3): print(crescente[c]) print() for c in range(0, 3): print(original[c]) main()
1597a760024c56179e83002a33477cd9b9de16b2
KyleC14/SwordToOfferPractice
/code/Question19/Solution1.py
828
3.53125
4
''' 递归做法 参考https://leetcode-cn.com/problems/regular-expression-matching/solution/zheng-ze-biao-da-shi-pi-pei-dong-tai-gui-hua-by-jy/ ''' class Solution: def isMatch(self, s: str, p: str) -> bool: #p到结尾时,如果s也到结尾则为true if not p: return not s if len(p) > 1 and p[1] == '*': if s and (s[0] == p[0] or p[0] == '.'): #这里实际有三种状态(s+1,p+2),(s,p+2),(s+1,p) 但是实际上第一种状态已经包含在第三种状态中 #对应匹配一次,匹配0次,匹配多次 return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) return self.isMatch(s, p[2:]) if s and (s[0] == p[0] or p[0] == '.'): return self.isMatch(s[1:], p[1:]) return False
250f40fc7a0a44cc1a630a0e49ccb73e78c5020c
gcnit/Competitive-Programming
/left shift.py
58
3.59375
4
t=int(input()) x=1 while t>0: x=x<<1 t=t-1 print(x)
98ef87e8cd1db024cb0808e0dd7df7c907caf346
bluestreakxmu/PythonExercises
/FlashCardChallenge/quizzer.py
1,352
3.65625
4
import random from sys import argv import os def read_flashcard_file(filename): """Get the questions from a fixed flash card file""" filepath = "cardrepository/" + filename if not os.path.isfile(filepath): print("Not a valid file name!!") exit() flash_card_dict = {} with open(filepath) as file: while True: line = file.readline().replace("\n", "") if 0 == len(line): break keyvalue = line.split(",") flash_card_dict[keyvalue[0]] = keyvalue[1] return flash_card_dict def select_questions_randomly(flash_car_dict): while True: flash_card_key = random.choice(list(flash_card_dict.keys())) answer = input("{}? ".format(flash_card_key)) if "exit" == answer.lower(): print("Goodbye") exit() elif answer.lower() == flash_card_dict[flash_card_key].lower(): print("Correct! Nice job.") else: print("Incorrect. The correct answer is {}.".format(flash_card_dict[flash_card_key])) def get_filename(): if 2 != len(argv): print("Please input a quiz questions file name!") exit() return argv[1] # Run the script filename = get_filename() flash_card_dict = read_flashcard_file(filename) select_questions_randomly(flash_card_dict)
728fd4d81dcf6c82795df7c8defed433e614cd08
cgisala/Capstone-Intro
/My_Turn2.py
252
3.515625
4
numList = [0, 3, 4, 0, 22, 1] noZero = [zero for zero in numList if zero > 0] print(f'No zero in list: {noZero}') classList = ['ITEC 2560', 'BTEC 1010', 'ITEC 2905'] itec = [itec for itec in classList if 'ITEC' in itec] print(f'ITEC classes: {itec}')
e32415e8110a0793b594e02d7ad9b9c1331398ce
mcode36/Code_Examples
/Python/Python_CodingBat/make_bricks.py
1,000
3.90625
4
''' # method 1 def make_bricks(small, big, goal): possible = False i = 0 for i in range(0,big+1): for j in range(0,small+1): # print(i,j,i*5+j) if i*5 + j == goal: possible = True break if possible: break return possible # method 2 def make_bricks(small, big, goal): i = 0 for i in range(0,big+1): for j in range(0,small+1): if i*5 + j == goal: return True return False ''' # method 3 def make_bricks(small, big, goal): if goal % 5 == 0: if big >= goal/5 or big*5 + small >= goal: return True else: return False else: if big >= (goal-(goal%5))/5 and small >= goal%5: return True elif big < (goal-(goal%5))/5 and small >= goal-(big*5): return True else: return False print(make_bricks(3, 1, 8)) # T print(make_bricks(3, 1, 9)) # F print(make_bricks(3, 2, 9)) # F print(make_bricks(3, 2, 10)) # T
4211b1fa093def536158860e2735e6301f133337
Omkar-M/Coffee-Machine
/Problems/Piggy bank/task.py
562
3.625
4
class PiggyBank: # create __init__ and add_money methods def __init__(self, dollars, cents): self.dollars = dollars self.cents = cents def add_money(self, deposit_dollars, deposit_cents): self.dollars += deposit_dollars self.cents += deposit_cents if self.cents > 99: quotient = self.cents / 100 remainder = self.cents % 100 self.dollars += int(quotient) self.cents = remainder # bank = PiggyBank(1,1) # bank.add_money(0,99) # print(bank.dollars, bank.cents)
0957a8d13c972f72bdd567661d74aa389d8e63f0
pineman/code
/old_proj/BOSK/Real Code/oldClasses.py
20,207
3.65625
4
import cmd class Player(object): def __init__(self,name,sex,hp=0,strength=0,defense=0,agility=0,intelect=0 ,luck=0,swag=0,money=0,inventory=[]): def check_stat(stat): '''check if the passed argument is an integer''' return not(type(stat) == int) # Loads of control flow to ensure that the arguments passed as stats #are only the ones we want. Prevent integers/floats/etc. in the name, #floats and other creepy stuff in the integer stats # RuntimeErrors to print when a wrong type of argument was passed if type(name) != str: raise RuntimeError("Fuck... The name should be a string..." \ "(__init__ of Player) Passed a " + str(type(name))) self.name = name if not (sex in ["male", "female"]): raise RuntimeError("The sex should only be male/female (__init__ " \ "Player)") self.sex = sex if check_stat(hp): raise RuntimeError("The HP stat can only be an integer (__init__ " \ "Player) Passed a " + str(type(hp))) self.hp = hp if check_stat(strength): raise RuntimeError("The strength stat can only be an integer " \ "(__init__ of Player) Passed a " + str(type(strength))) self.strength = strength if check_stat(defense): raise RuntimeError("The defense stat can only be an integer " \ "(__init__ of Player) Passed a " + str(type(defense))) self.defense = defense if check_stat(agility): raise RuntimeError("The agility stat can only be an integer " \ "(__init__ of Player) Passed a " + str(type(agility))) self.agility = agility if check_stat(intelect): raise RuntimeError("The intelect stat can only be an integer " \ "(__init__ of Player) Passed a " + str(type(intelect))) self.intelect = intelect if check_stat(luck): raise RuntimeError("The luck stat can only be an integer " \ "(__init__ of Player) Passed a " + str(type(luck))) self.luck = luck if not(type(money) in [int, float]): raise RuntimeError("The money has to be, either a float or an " \ "integer (__init__ of Player) Passed a " + str(type(money))) self.money = money if check_stat(swag): raise RuntimeError("Your swag points should only be integers " \ "(__init__ of Player); Passed a " + str(type(swag))) self.swag = swag if type(inventory) != list: raise RuntimeError("Your inventory should be a list of items! " \ "(__init__ of Player)") def get_data(self): return tuple(self.name, self.sex, self.hp, self.strength, self.defense, self.agility, self.intelect, self.luck, self.swag, self.money, self.inventory) class StatAssigner(cmd.Cmd): def __init__(self, name, first=False, tokens=5, player=None): cmd.Cmd.__init__(self) if first: print() print("#"*40) print("Welcome to the stat assigner " + name + ".") print("Please remember that whenever you may need help, you can type ? or help") print("In here you will set your initial stats for the game!") print("#"*40) input() print("These are the existing stats:") print("\tHP: Your hitpoints times 10 give you your maximum health") print("\tStrength: Strength influences the amount of damage you "\ "deal") print("\tDefense: Reduces the amount of damage you take per hit") print("\tAgility: It is agility that defines your dodging chance") print("\tIntelect: Affects the spells you can use and their effects") print("\tLuck: Dictates wether you will deal a critical hit or not") print("#"*40) input() print("Please be aware that every stat can also influence some random "\ "events.\nFor example, your agility could dictate if you would dodge "\ "a falling rock in an unknown ravine") print() print("You also have swag points. These are earnt ingame and help you get "\ "discounts when buying new stuff and weapons, amongst other very swaggy things") print("#"*40) state = [1,1,1,1,1,1] if not(first) and player == None: raise RuntimeError("If this isn't the part were you create a "\ "player in the beginning of the game, we should"\ " have got some player as argument") self.first = first self.player = player self.p_name = name self.available_tokens = tokens self.prompt = "(Stat Assigner) >> " self.skills = ["hp","strength","defense","agility","intelect","luck"] self.init_stats = {self.skills[i]: state[i] for i in range(len(state))} self.values = {self.skills[i]: state[i] for i in range(len(state))} def do_help(self, s): """Help function that displays help about the commands""" if s == "": print("To assign a stat, you can either use the <increase>, <set>, "\ "<reset> and <max> commands, followed by the skill you wish.") print("Example: set strength 7 sets your strength to level 7.") print("You can also randomly assign all your stats with <random>") cmd.Cmd.do_help(self, s) def parse(self, s): """A little helper that gets rid of annoying characters, replacing them with spaces""" chars = [",",";","/",".",":"] for char in chars: while char in s: s = s[:s.index(char)] + " " + s[s.index(char)+1:] return s def do_set(self, s): """Command used to set one or more skills to a certain level (passed as argument)""" # parse all the weird characters in the argument string s = self.parse(s) # list all the skills we want to change args = s.lower().split() # try to get the new level try: n = int(args[0]) # if we can't, the user wrote the command in the wrong way # tell him to get some help # maybe some rehab # LOL except ValueError: # try to catch the case where <set> <skill> <amount> is used if len(args) == 2: # Do some sneaky stuff so the rest of the function works #properly: put the arguments in the default order try: n = int(args[1]) args[0], args[1] = args[1], args[0] except ValueError: print("*** Syntax Error: <set> <amount> <skill1> "\ "<skill2> ...") print("Please type <help> <set> for help with the set "\ "command") return else: print("*** Syntax Error: <set> <amount> <skill1> <skill2> ...") print("Please type <help> <set> for help with the set command") return # pop the new level from the string args.pop(0) # if no args are remaining the user missed the skills in the command if len(args) == 0: print("*** Syntax Error: missing <skill> argument") print("Please type <help> <set> for help with the set command") # parse the other skills # if the only argument missing is "all", swap it with all the skills elif len(args) == 1 and args[0] == "all": args.pop() args = self.skills # loop through the arguments for skill in args: # if we don't recognize the skill, warn the user if skill not in self.skills: print("*** Unknown skill " + skill) else: # don't let the user reduce a skill further than it was if n < self.init_stats[skill]: print("You can't set " + skill + " to a lower level "\ "than the one it had when we started (" + str(self.init_stats[skill]) + ")...") continue # else, find the difference (new - old) d = n - self.values[skill] # if we are reducing a skill, (new-old) gives a negative int #so the following "if" statement ALWAYS lets us reduce it # if (new-old) is >0, evaluate if we have enough tokens #to set that skill to that level if self.available_tokens >= d: self.values[skill] = n # remember that if we were reducing a skill, d is <0 #so this subtraction actually increases available_tkns self.available_tokens -= d print(skill.capitalize() + " set to level " + str(n)) # If we don't have enough tokens, warn the user and exit else: print("You do not have enough skill tokens (" + str(self.available_tokens) + ") to set "\ + skill + " to level " + str(n)) return # Remind the user how many tokens he has left print("You have " + str(self.available_tokens) +" available tokens.") def do_increase(self, s): """Command used to increase one or more skills by the amount passed""" # parse all the commas in the argument string s = self.parse(s) # list all the skills we want to change args = s.lower().split() # try to get the new level try: n = int(args[0]) # if we can't, the user wrote the command in the wrong way # tell him to get some help # maybe some rehab except ValueError: print("*** Syntax Error: <increase> <amount> <skill1> <skill2> ...") print("Please type <help> <increase> for help with the increase "\ "command") return # pop the new level from the string args.pop(0) # if no args are remaining the user missed the skills in the args if len(args) == 0: print("*** Syntax Error: missing <skill> argument") print("Please type <help> <increase> for help with the set command") # if the only remaining argument is "all", swap it with all the other #stats! elif len(args) == 1 and args[0] == "all": args.pop() args = self.skills # 't' is the total tokens we will need t = len(args) * n # If we don't have enough tokens, change NO skills, warn user, exit if self.available_tokens < n: print("You don't have enough tokens (" + str(self.available_tokens)+ ") to increase by " + str(n) + " " +str(len(args)) +" skills") else: # Deduce the tokens needed ;) self.available_tokens -= t # if we do have the needed tokens, change the skills for skill in args: # if we don't recognize the skill, warn the user if skill not in self.skills: print("*** Unknown skill " + skill) # If the skill wasn't recognize, give him back those tokens! self.available_tokens += n else: self.values[skill] += n print(skill.capitalize() + " increased by " + str(n) + " to level " + str(self.values[skill])) print("You have " + str(self.available_tokens) +" tokens available") def do_reset(self, s): """Command used to reset one or more skills to the initial value""" # parse all the weird characters in s s = parse(s) args = s.lower().split() if ((len(args) == 1) and (args[0] == "all")) or (len(args) == 0): args.pop() args = self.skills for skill in args: d = self.values[skill] - self.init_stats[skill] self.available_tokens -= d self.values[skill] = self.init_stats[skill] print(skill.capitalize() + " reset to level " + str(self.values[skill])) def do_max(self, s): """Command used to max ou a certain skill, spending all available tokens""" # parse all the weird characters in s s = parse(s) args = s.lower().split() # <max> only takes 1 argument! deal with that if len(args) != 1: print("*** Syntax Error: <max> takes exactly one argument <skill>") print("Type <help> <max> for help with the <max> command") # if the argument provided is not recognized elif args[0] not in self.skills: print("*** Syntax Error: Unknown <skill> argument " + args[0]) # Valid argument! Max that skill >> Spend all the tokens in it else: self.values[args[0]] += self.available_tokens self.available_tokens = 0 print("Maxed skill " + args[0] + " to level " + str(self.values[ args[0]])) def do_check(self, s): """Command to print neatly all the skills and their levels""" # ignore all the arguments passed to the command if s != "": print(s + " ignored... <check> takes no arguments") # find the maximum word length amongst all the skills # has to do with formatting the table m = 0 for skill in self.skills: m = len(skill) if len(skill) > m else m # increase it by two because of the ' ' before and after the word m += 2 print(" Skill | Set (initial)") # the m size, plus 3 "|", plus 10 spaces for the <level set> (init) print("-"*(m+14)) # parse every skill for skill in self.skills: # create the string with the skill s_skill = " " + skill # while it doesn't have 'm' size, add spaces! while len(s_skill) < m: s_skill += " " # string with the initial value surrounded by () s_init = "(" + str(self.init_stats[skill]) + ") " # string with the current value plus an ending space s_stat_now = str(self.values[skill]) + " " # add it all up s_init_now = s_stat_now + s_init # while it doesn't have size 10, add spaces in front of it! #why 11? 3 for each skill (6) + the two spaces (before and after) # + the space between skill and (init) + the () while len(s_init_now) < 11: s_init_now = " " + s_init_now # print() it all nice and good looking print("|" + s_skill + "|" + s_init_now + "|") print("-"*(m+14)) def do_tokens(self, s): """Tell the user how many tokens he has got left""" print("You have " + str(self.available_tokens) + " available tokens.") def default(self, s): """Implement a slight exchange""" if s in self.skills: print("Your " + s.capitalize() + " skill entered the assigner with"\ " a level " + str(self.init_stats[s]) + ",\nAnd is now set "\ "to level " + str(self.values[s])) elif s[0] == "<" and s[-1] == ">": print("The commands shouldn't be surrounded by <>") print("That is just our way of distinguishing the print of a "\ "command from the print of a single \"normal\" word.") else: cmd.Cmd().default(s) def do_exit(self, s): """Command to exit the stat assigner""" # Don't let the user leave if he hasn't used all the tokens if self.available_tokens != 0: print("You still have unused available tokens.") print("You cannot leave the Stat Assigner while there are tokens "\ "to be used.") return print("Are you sure you want to exit??") ans = input("Y/N >> ").strip().lower() if ans.startswith("y"): for skill in self.skills: exec("self.player."+skill+" = "+str(self.values[skill])) return True else: return # define all the helps # layout: ## print with usage ### blank print ## further explanation def help_exit(self): """Help function on command <exit>""" print("Command usage: <exit>") print() print("Use the <exit> command when you are finished from the stat "\ "assignment.\n\tYou won't be able to leave before spending all "\ "the available tokens.") def help_tokens(self): """Help function on command <tokens>""" print("Command usage: <tokens>") print() print("Tells you how many tokens you have left") def help_set(self): """Help function on command <set>""" s = "" for skill in self.skills: s += skill + "; " s = s[:-2] s += "." print("Command usage: <set> <value> <skill 1> (<skill 2> <skill ..>)") print(" * If you want to pass only one skill, you can swap <skill> "\ "with <value> in the arguments.") print(" * <all> is an alias for all the stats.") print() print("Use the <set> command to define the new levels for the specified"\ " skills. These are " + s) def help_increase(self): """Help function on command <increase>""" s = "" for skill in self.skills: s += skill + "; " s = s[:-2] s += "." print("Command usage: <increase> <value> <skill 1> (<skill 2> <skill "\ "..>)") print(" * <all> is an alias for all the skills.") print() print("Use the <increase> command to increase by a specified value, "\ "all the specified skills. These are " + s) def help_reset(self): """Help function on command <reset>""" print("Command usage: <reset> (<skill 1> <skill ..>)") print(" * <all> is an alias for all the skills") print(" * Using no arguments defaults the command to all the skills") print() print("Use the <reset> command to define the specified skills to the "\ "values they had before starting the assignment.") def help_max(self): """Help function on command <max>""" print("Command usage: <max> <skill>") print() print("Use the <max> command to spend all the available tokens on the "\ "specified skill.") def help_check(self): """Help function on command <check>""" print("Command usage: <check>") print() print("Check the current state of all skills.") print("To check just one skill, type in only the name of the skill.") print("Like <" + self.skills[0] + ">")
f1450f788546dc87cc2a973ba7ec88c7a0bbacf1
kennybix/MATH_5470
/interpolation_models/core/preprocessing.py
2,391
3.828125
4
import numpy as np def normalize(x): y = (x-min(x))/(max(x)-min(x)) return y # def denormalize(x,ymin,ymax): # if(x.shape[1]==1): # n = len(x) # y = np.ones(n) # for i in range(n): # y[i] = (x[i]*(ymax-ymin))+ymin # else: # k = x.shape[1] # n = x.shape[0] # y = np.zeros((n,k)) # for # return y def normalize_values(x,xmin,xmax): y = (x-xmin)/(xmax-xmin) return y def denormalize(x,ymin,ymax): n = len(x) y = np.ones(n) for i in range(n): y[i] = (x[i]*(ymax-ymin))+ymin return y def standardize(X,y): ''' Returns 1.X_normal, 2.y_normal 3.X_mean, 4.y_mean 5.X_std, 6.y_std X is the multidimensional input y is the output Method returns 1.the normalized values 2. the mean 3. the standard deviation of the parameters ''' X = np.array(X) n = X.shape[0] k = X.shape[1] #this returns the dimension of X X_normal = np.zeros((n,k)) X_mean = np.zeros(k) X_std = np.zeros(k) y_normal = np.zeros(n) #initialization y_mean = 1 y_std = 1 for i in range(k): X_normal[:,i] = normalize(X[:,i]) X_mean[i] = np.sum(X[:,i]) / n X_std[i] = np.std(X[:,i]) y_normal = normalize(y) y_mean = np.mean(y) y_std = np.std(y) return X_normal,y_normal,X_mean,y_mean,X_std,y_std def norm(X,y): ''' Returns 1.X_normal, 2.y_normal 3.X_min, 4.y_min 5.X_max, 6.y_max X is the multidimensional input y is the output Method returns 1.the normalized values 2. the mean 3. the standard deviation of the parameters ''' X = np.array(X) n = X.shape[0] k = X.shape[1] #this returns the dimension of X X_normal = np.zeros((n,k)) X_min = np.zeros(k) X_max = np.zeros(k) y_normal = np.zeros(n) #initialization y_min = 1 y_max = 1 for i in range(k): X_normal[:,i] = normalize(X[:,i]) X_min[i] = np.min(X[:,i]) X_max[i] = np.max(X[:,i]) y_normal = normalize(y) y_min = np.min(y) y_max = np.max(y) return X_normal,y_normal,X_min,y_min,X_max,y_max
3101af3a2763eae48140635bdfc3927920050dc5
JuliaWozniak/computor2
/second.py
1,971
3.703125
4
from abc import ABC, abstractmethod import re class Operand(ABC): @abstractmethod def describe(self): pass @abstractmethod def __add__(self, other): pass # @abstractmethod # def __sub__(self, other): # pass # @abstractmethod # def __mul__(self, other): # pass # @abstractmethod # def __truediv__(self, other): # pass # @abstractmethod # def __mod__(self, other): # pass class Env(): def __init__(self): self.my_vars = {} self.my_var_names = [] def lookup(self, name): name = name.casefold() if name in self.my_var_names: return(self.my_vars[name]) # raise an error print('no such variable') return('') def assign(self, name, op): name = name.casefold() if name in self.my_var_names: self.my_vars[name] = op return self.my_var_names.append(name) self.my_vars[name] = op def print_vars(self): for name in self.my_var_names: print("%s =" %(name), end=' ') self.my_vars[name].describe() class Real(Operand): def __init__(self, num): self.a = num def describe(self): print(self.a) def __add__(self, o): if isinstance(o, Real): return self.a + o.a else: print("trying to add diff types") def __pow__(self, o): print("heeerrrreee") class Operation(): def __init__(self, sign): if sign == '+': self.op = add self.sign = sign def describe(): print(self.sign) def add(left, right): if isinstance(left, Real) and isinstance(right, Real): return(left + right) else: print('different types, do not know yet') return(10) from enum import Enum class Types(Enum): REAL = 1 COMPLEX = 2 MATRIX = 3 NONE = 4 OPERATION = 5 class Variable(): def __init__(self, name, value): self.name = name self.value = value if isinstance(self.value, Real): self.type = Types.REAL elif isinstance(self.value, Operation): self.type = Types.OPERATION else: self.type = Types.NONE def describe(self): print(self.type, end=' ') # self.value.describe()
509a39ccb542e8510d8ddf510afcf133288e0bbc
ongsuwannoo/PSIT
/circularprime V.Chotipat.py
867
4.15625
4
""" CircularPrime """ def sum_circular_prime(num): """Return sum of circular prime from 1 to num""" total = 0 for i in range(1, num+1): if is_circular_prime(i): total = total + i return total def is_circular_prime(num): """Return True if num is circular prime else otherwise""" for i in range(len(str(num))): rotate_num = rotate(num, i) if not is_prime(rotate_num): return False return True def rotate(num, i): """Return number by rotating i digit""" num = str(num) num = num[i:] + num[:i] return int(num) def is_prime(num): """Return True if num is prime else otherwise""" if num == 1: return False for i in range(2, int(num**0.5)+1): if num % i == 0: return False return True print(sum_circular_prime(int(input())))
f731979f5dfba2240dfc71ba89f8f7eddffee59a
rocheio/advent-of-code
/day3.py
3,121
4.34375
4
""" https://adventofcode.com/2019/day/3 """ def path_to_trail(path): """Walk a path starting at (0,0) and return a list of each coordinate hit along the way.""" trail = [] current = (0, 0) trail += [current] for step in path: coords = coords_between(current, step) trail += coords current = coords[-1] return trail def coords_between(current, step): """Return all (x,y) coordinate pairs from applying a step from current coords. The last step in the returned list is the new current position. """ coords_between = [] x, y = current direction = step[0] distance = int(step[1:]) for _ in range(1, distance+1): if direction == "U": y += 1 elif direction == "D": y -= 1 elif direction == "L": x -= 1 elif direction == "R": x += 1 coords_between += [(x, y)] return coords_between def manhattan_distance(path1, path2): """Return the smallest Manhattan distance from (0, 0) where two wire paths cross.""" # Convert each path into a list of locations it passed through trail1 = path_to_trail(path1) trail2 = path_to_trail(path2) # Find all locations that exist in each trail collisions = set(trail1) & set(trail2) # Origin does not count as an intersection collisions -= {(0, 0)} # Convert all collisions into distances from origin distances = [abs(x) + abs(y) for x, y in collisions] return min(distances) def least_shared_steps(path1, path2): """Return the smallest shared steps before intersection between two paths.""" # Convert each path into a list of locations it passed through trail1 = path_to_trail(path1) trail2 = path_to_trail(path2) # Find all locations that exist in each trail collisions = set(trail1) & set(trail2) # Origin does not count as an intersection collisions -= {(0, 0)} return min(trail1.index(c) + trail2.index(c) for c in collisions) def test(): path1 = ["R75","D30","R83","U83","L12","D49","R71","U7","L72"] path2 = ["U62","R66","U55","R34","D71","R55","D58","R83"] assert manhattan_distance(path1, path2) == 159 path1 = ["R98","U47","R26","D63","R33","U87","L62","D20","R33","U53","R51"] path2 = ["U98","R91","D20","R16","D67","R40","U7","R15","U6","R7"] assert manhattan_distance(path1, path2) == 135 path1 = ["R75","D30","R83","U83","L12","D49","R71","U7","L72",] path2 = ["U62","R66","U55","R34","D71","R55","D58","R83",] assert least_shared_steps(path1, path2) == 610 path1 = ["R98","U47","R26","D63","R33","U87","L62","D20","R33","U53","R51",] path2 = ["U98","R91","D20","R16","D67","R40","U7","R15","U6","R7",] assert least_shared_steps(path1, path2) == 410 def main(): # Convert text input into two lists of wire paths with open("data/day3.txt", "r") as file: paths = [path.strip().split(",") for path in file.readlines()] lss = least_shared_steps(*paths) print(f"least shared steps is: {lss}") if __name__ == "__main__": test() main()
6336ecbfca48c0e59d293b2bf4f953a8732e545d
Erniess/pythontutor
/Занятие 6 - Цикл while/Практика/Стандартное отклонение.py
982
3.5
4
# Задача «Стандартное отклонение» # Условие # # Дана последовательность натуральных чисел x1 # , x2, ..., xn. Стандартным отклонением называется величина # σ=(x1−s)2+(x2−s)2+…+(xn−s)2n−1‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾√ # где s=x1+x2+…+xnn # # — среднее арифметическое последовательности. # # Определите стандартное отклонение для данной последовательности натуральных чисел, # завершающейся числом 0. nat_range = [] n_summ = 0 n = int(input()) while n != 0: nat_range.append(n) n_summ += n n = int(input()) n = len(nat_range) s = sum(nat_range) / n betta = (sum([(i - s) ** 2 for i in nat_range]) / (n - 1)) ** 0.5 print(betta)
444648bebfd0a6111683801b5b111ba11fd8fcb0
FloHab/Project-Euler
/Problem 22.py
1,544
3.90625
4
#Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, #begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, #multiply this value by its alphabetical position in the list to obtain a name score. #For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, #is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. #What is the total of all the name scores in the file? import time start_time = time.clock() file=open("C:\\Users\\Florian Habenstein\\PycharmProjects\\Project Euler\\p022_names.txt","r") x=str(file.read()) names=[] y=x.replace('"','') name="" for z in y: if z==",": names.append(name) name="" else: name=name+z names.append(name) file.close scores={"A":1, "B":2, "C":3, "D":4, "E":5, "F":6, "G":7, "H":8, "I":9, "J":10, "K":11, "L":12, "M":13, "N":14, "O":15, "P":16, "Q":17, "R":18, "S":19, "T":20, "U":21, "V":22, "W":23, "X":24, "Y":25, "Z":26} names.sort() names_and_scores={} for word in names: name_score=0 for letter in word: for score in scores: if letter==score: name_score=name_score+scores[score] names_and_scores[word]=name_score print(names_and_scores) n=1 summe=0 for entry in names_and_scores: summe=summe+n*names_and_scores[entry] print(n) print(names_and_scores[entry]) n=n+1 print(summe) print(time.clock() - start_time, "seconds")
454cf3443785db17b1a08644ddce592c5252a071
Aasthaengg/IBMdataset
/Python_codes/p02900/s650383711.py
1,045
3.65625
4
import math def primelist(n): is_prime = [True] * (n + 1) is_prime[0] = False is_prime[1] = False for i in range(2, int(n**0.5) + 1): if not is_prime[i]: continue for j in range(i * 2, n + 1, i): is_prime[j] = False return [i for i in range(n + 1) if is_prime[i]] def factorization(n): plist = primelist(int(n**0.5)) factor = [] for p in plist: k = 0 while n%p==0: k+=1 n//=p if k>0: factor.append((p,k)) if n==1: break if n!=1: factor.append((n,1)) return factor def divisors(n): divisors = [] for i in range(1, int(n**0.5)+1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n//i) divisors.sort() return divisors def main(): a,b = tuple(map(int,input().split())) g = math.gcd(a,b) factors = factorization(g) print(len(factors)+1) if __name__ == "__main__": main()
508a972f076ff199669c13d6dc949bcc22e2743c
ajayajdeveloper/my-python-code-
/Zigzag1.py
1,605
3.90625
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from collections import deque class Zigzag1: def zigzagLevelOrder(self, root): if not root: return [] res = [] q = deque() zigzag = False q.append(root) while q: level = [] for _ in range(len(q)): if zigzag: node = q.pop() level.append(node.val) if node.right: q.appendleft(node.right) if node.left: q.appendleft(node.left) else: node = q.popleft() level.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) res.append(level) zigzag = not zigzag return res #create the nodes three_node = TreeNode(3) nine_node = TreeNode(9) fifteen_node = TreeNode(15) seven_node = TreeNode(7) twenty_node = TreeNode(20) #connect the nodes togather to form a tree structure three_node.left = nine_node three_node.right = twenty_node twenty_node.left = fifteen_node twenty_node.right = seven_node #instance of the Zigzag class z=Zigzag1() a=z.zigzagLevelOrder(three_node) print(a)
3b2c7974e4abcc4218c1731fbdf49a1877d5bec8
isaacrivas10/arbol-proyecto-aed
/pruebas/temp.py
2,161
3.84375
4
# NO MODIFICAR! # SE EFECTUAN PRUEBAS class ListaEnlazada: def __init__(self): self.first= None # Es un nodo def add(self, addV): c = self.first if c is None: self.first = addV else: exist= True while exist: # Mientras exista el nodo if c.getNext() is None: # Si despues de c no hay un nodo c.setNext(addV) # Asignamos como siguiente exist= False else: # Si no c = c.getNext() # Pasamos al siguiente de c def remove(self, remV): # remV hace referencia al NODO a borrar # Es independiente al tipo # De acuerdo a remV se buscara el nodo if remV is self.first: self.first= self.first.getNext() else: searched_list = self.search(remV) node = self.first for j in range(searched_list[2]-1): node= node.getNext() # Me localizo al nodo que esta # antes del que voy a borrar node.setNext(searched_list[1]) def search(self, searchValue): found= None node= self.first for o in range(self.len()): before= node if node is searchValue: return [node, node.getNext(), o] else: node= node.getNext() def len(self): len = 0 i= True t= self.first while t is not None: len += 1 t= t.getNext() return len class Node(): """ Un nodo es una estrucutra personal de un arbol, lista enlazada. Cada nodo puede contener cualquier cosa, en este caso, Carpetas y Archivos. """ def __init__(self, value): self.value= value # Contiene una instancia de una Carpeta o Archivo, no es una variable comun self.next= None def type(self): # Retorna el nombre de la clase a la que pertenece return self.value.__class__.__name__ def getValue(self): return self.value def getName(self): # Retorna el nombre del valor que contiene el nodo return self.value.name def setNext(self, nextNode): self.next= nextNode def getNext(self): return self.next class Carpeta: def __init__(self, name): self.name = name self.branches = ListaEnlazada() def add(self, addValue): self.branches.add(addValue) def remove(self, remValue): self.branches.remove(remValue) class Archivo: def __init__(self, name): self.name = name
1d7ffc9486cdd3ff09cae01930f7a7fb2161d140
longgb246/MLlearn
/leetcode/base/11_max_area.py
1,507
3.734375
4
# -*- coding:utf-8 -*- # @Author : 'longguangbin' # @Contact : [email protected] # @Date : 2019/1/11 """ Usage Of '11_max_area.py' : """ class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ # 较长线段的指针向内侧移动,矩形区域的面积将受限于较短的线段而不会获得任何增加 # 移动指向较短线段的指针尽管造成了矩形宽度的减小,但却可能会有助于面积的增大 max_v = 0 l = 0 r = len(height) - 1 while l < r: max_v = max(max_v, min(height[l], height[r]) * (r - l)) if height[l] < height[r]: l += 1 else: r -= 1 res = max_v return res def maxArea1(self, height): """ :type height: List[int] :rtype: int """ # 该方法超时 len_h = len(height) max_v = 0 for i, v in enumerate(height): for j in range(i + 1, len_h): this_v = (j - i) * min(v, height[j]) if this_v > max_v: max_v = this_v res = max_v return res def get_test_instance(example=1): height = [1, 8, 6, 2, 5, 4, 8, 3, 7] if example == 1: pass return height def main(): height = get_test_instance(example=1) res = Solution().maxArea(height) print(res) if __name__ == '__main__': main()
3f1678e0040f67bf47a3d019b30342628c640984
danielrobin2011/ML-Practice
/Linear Regression/Salary-Experience/Salary-Regression.py
688
3.8125
4
import numpy as np; import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv("Salary_Data.csv"); #Divide the dataset into X and Y alpha = 1 X = dataset.iloc[:,0].values Y = dataset.iloc[:,1].values m = dataset.iloc[:,0].values.length(); print(m) theta=[ 1.0, -1.0 ] def cost(X, Y, m, theta): squared_sum=0.0 for i in range(m): squared_sum = squared_sum + ((theta[0] + theta[1]*X[i]) - Y[i])**2; return ((1.0/(2*m))*squared_sum); print(X) print(Y) X = (X - np.mean(X))/(np.max(X) - np.min(X)) print(X) Y = (Y - np.mean(Y))/(np.max(Y) - np.min(Y)) print(Y) print(cost(X,Y,10,theta)); #while(cost(X,Y,10,theta)<0.00) # temp0 = theta[0] - alpha*(); # np.max
e30acd77c493919f03b9082225fa0730667e7436
Prasad-Medisetti/STT
/My Python Scripts/NearlyEq.py
285
3.71875
4
def nearly_equal(s1, s2): l = len(s1) if len(s1) < len(s2) else len(s2) i = 0 cnt = 0 for i in range(l): if s1[i] == s2[i]: continue else: cnt += 1 print("Nearly Equal") if cnt == 1 or cnt == 0 else print("Not Nearly Equal")
7f1a217753ba8a67f3fc0a9fe4516c2cd9f5f19f
matheuspiana/Trabalho-CG
/compgraf.py
1,559
3.640625
4
from random import choice import string usuarios = [] def cadastro(): listuser = open("user.txt","w") listsenha = open("senha.txt", "w") user = input("Escolha seu ID: ") senha = input("Digite a sua senha: ") #cadastro = ["\n", user,"\n", senha, "\n", "_"*50] listuser.writelines(user) listsenha.writelines(senha) listuser.close() listsenha.close() def login(): listuser = open("user.txt","r") loginid = input("Login: ") linhauser = listuser.read() if linhauser == loginid: listuser.close() listsenha = open("senha.txt", "r") loginsenha = input("Senha: ") linhasenha = listsenha.read() if linhasenha == loginsenha: print("Logado!") listsenha.close() else: print("Senha incorreta!") listsenha.close() elif linhauser != loginid: print("Login não existe") listuser.close() print("Seja bem a Autenticação de Três Fatores (ATF)") print("Escolha (1) para Login e (2) para Cadastro.") escolha = int(input("O que deseja fazer? ")) if escolha == 2: cadastro() elif escolha == 1: login() ''' numeros = int(input("Quantos usuarios deseja adicionar: ")) for x in range(numeros): id = input("Escolha seu ID: ") usuarios.append(id) tamanho = 5 valores = string.ascii_lowercase senha = '' for i in range(tamanho): senha += choice(valores) print(senha) '''
490b8aaf0ab4e2adb3440355fbf271a1b9b9f650
codecakes/random_games
/remove_html_tags.py
1,625
3.890625
4
#Remove HTML Tags from plaintext # When we add our words to the index, we don't really want to include # html tags such as <body>, <head>, <table>, <a href="..."> and so on. # Write a procedure, remove_tags, that takes as input a string and returns # a list of words, in order, with the tags removed. Tags are defined to be # strings surrounded by < >. Words are separated by whitespace or tags. # You may assume the input does not include any unclosed tags, that is, # there will be no '<' without a following '>'. def remove_tags(s): r = [] word = '' on = False for w in s: if w=='<': on = True if not on and w not in ("\n"): if (w==" "): if word: r.append(word) word = '' else: word += w if w == '>': on = False if word and word != '': r.append(word) word = '' if word: r.append(word) return r assert remove_tags('''<h1>Title</h1><p>This is a <a href="http://www.udacity.com">link</a>.<p>''') == \ ['Title','This','is','a','link','.'] assert remove_tags('''<table cellpadding='3'> <tr><td>Hello</td><td>World!</td></tr> </table>''') == \ ['Hello','World!'] assert remove_tags("<hello><goodbye>") == [] assert remove_tags("This is plain text.") == ['This', 'is', 'plain', 'text.'] assert remove_tags("This sentence has no tags.") == \ ['This', 'sentence', 'has', 'no', 'tags.']
7583dda8c8a6b8fa9e7b9ae66b7a41f79e0d284a
gmclapp/Personal_library
/chess/chess.py
13,652
3.65625
4
import pygame from pygame.locals import * def quit_nicely(): pygame.display.quit() pygame.quit() class board(): def __init__(self): self.dark_color = (50, 50, 50) self.light_color = (255, 255, 255) self.square_size = 60 self.light_square = pygame.Surface((self.square_size,self.square_size)) self.light_square.fill(self.light_color) self.board_size = self.square_size*8 self.board = pygame.Surface((self.board_size,self.board_size)) self.board.fill(self.dark_color) for i in range(32): if int(i/4)%2: self.board.blit(self.light_square, (2*self.square_size*(i%4), self.square_size*int(i/4))) else: self.board.blit(self.light_square, (2*self.square_size*(i%4) + self.square_size, self.square_size*int(i/4))) def draw(self, screen): screen.blit(self.board, (0,0)) class Position(): def __init__(self, FEN): self.board_array = [] self.FEN = FEN def draw(self, screen): for square in self.board_array: pass def FEN_to_array(self): board, self.turn, self.castle, self.enpassant, self.halfmoves, self.fullmoves = self.FEN.split() rows = board.split("/") for i,row in enumerate(rows): for square in row: try: square = int(square) for sq in range(square): self.board_array.append(".") except: self.board_array.append(square) def piece_on_square(self, square): '''Takes a algebraic representation of a square and returns the piece on that square. None if no piece is present on that square.''' try: file, rank = list(square) except ValueError: print("Invalid square, specify letter rank, and number file.") ord_file = ord(file.lower()) - 96 rank = int(rank) if ord_file > 8 or ord_file < 1: print("{} is not a valid file.".format(file)) if rank > 8 or rank < 1: print("{} is not a valid rank.".format(rank)) board_index = (8-rank)*8 + ord_file-1 piece = self.board_array[board_index] if piece == '.': piece = None return(piece) def check_file(self,pos): '''Takes a position and returns all the pieces on the same file and their positions.''' try: file, rank = list(pos) except ValueError: print("Invalid square, specify letter rank, and number file.") pieces = [] for i in range(8): rank = i+1 square = file + str(rank) piece = self.piece_on_square(square) if piece != None: pieces.append((square,piece)) return(pieces) def check_rank(self,pos): '''Takes a position and returns all the pieces on the same rank and their positions.''' try: file, rank = list(pos) except ValueError: print("Invalid square, specify letter rank, and number file.") rank = int(rank) pieces = [] for i in range(8): file = chr(i + 96 + 1) # ASCII position of lower case numbers. + 1 to compensate for i # starting at 0 square = file + str(rank) piece = self.piece_on_square(square) if piece != None: pieces.append((square, piece)) return(pieces) def check_diag(self,pos): '''checks both diagonals containing the given position for other pieces and returns those pieces and their positions.''' try: file, rank = list(pos) except ValueError: print("Invalid square, specify letter rank, and number file.") ord_file = ord(file.lower()) - 96 rank = int(rank) squares = [pos] f = ord_file r = rank # squares on the same diagonal can be found by adding or subtracting # the same integer from both the rank and file. There will be between # 8 and 15 squares sharing a diagonal with a given square. for i in range(8): f -= 1 r -= 1 if r >= 1 and r >= 1: squares.append(chr(f + 96) + str(r)) else: break f = ord_file r = rank for i in range(8): f += 1 r += 1 if r <= 8 and f <= 8: squares.append(chr(f + 96) + str(r)) else: break f = ord_file r = rank for i in range(8): f += 1 r -= 1 if r >= 1 and f <= 8: squares.append(chr(f + 96) + str(r)) else: break f = ord_file r = rank for i in range(8): f -= 1 r += 1 if r <= 8 and f >= 1: squares.append(chr(f + 96) + str(r)) else: break pieces = [] for s in squares: piece = self.piece_on_square(s) if piece != None: pieces.append((s, piece)) return(pieces) def check_knight(self,pos): '''Checks for knights attacking the given square. Returns those knights and their positions''' try: file, rank = list(pos) except ValueError: print("Invalid square, specify letter rank, and number file.") ord_file = ord(file.lower()) - 96 rank = int(rank) squares = [] f = ord_file r = rank f = ord_file + 2 r = rank + 1 if (r >= 1 and f >= 1) and (r <= 8 and f <= 8): squares.append(chr(f + 96) + str(r)) f = ord_file + 2 r = rank - 1 if (r >= 1 and f >= 1) and (r <= 8 and f <= 8): squares.append(chr(f + 96) + str(r)) f = ord_file - 2 r = rank + 1 if (r >= 1 and f >= 1) and (r <= 8 and f <= 8): squares.append(chr(f + 96) + str(r)) f = ord_file - 2 r = rank - 1 if (r >= 1 and f >= 1) and (r <= 8 and f <= 8): squares.append(chr(f + 96) + str(r)) f = ord_file + 1 r = rank + 2 if (r >= 1 and f >= 1) and (r <= 8 and f <= 8): squares.append(chr(f + 96) + str(r)) f = ord_file - 1 r = rank + 2 if (r >= 1 and f >= 1) and (r <= 8 and f <= 8): squares.append(chr(f + 96) + str(r)) f = ord_file + 1 r = rank - 2 if (r >= 1 and f >= 1) and (r <= 8 and f <= 8): squares.append(chr(f + 96) + str(r)) f = ord_file - 1 r = rank - 2 if (r >= 1 and f >= 1) and (r <= 8 and f <= 8): squares.append(chr(f + 96) + str(r)) pieces = [] for s in squares: piece = self.piece_on_square(s) if piece != None: pieces.append((s, piece)) return(pieces) def get_king_pos(self): white_king_found = False black_king_found = False for i,sq in enumerate(self.board_array): if sq == 'k': f = (i % 8) + 1 r = int(8 - i/8) + 1 black_king = chr(f + 96) + str(r) print("found black king {}".format(black_king)) black_king_found = True elif sq == 'K': f = (i % 8) + 1 r = int(8 - i/8) + 1 white_king = chr(f + 96) + str(r) print("found white king {}".format(white_king)) white_king_found = True else: pass if white_king_found and black_king_found: break else: pass return(white_king,black_king) def is_check(self): w_king, b_king = self.get_king_pos() white_check = False black_check = False for p in self.check_rank(w_king): if p[1] == 'r' or p[1] == 'q': print("Potential threat: {} on {}".format(p[1],p[0])) for p in self.check_file(w_king): if p[1] == 'r' or p[1] == 'q': print("Potential threat: {} on {}".format(p[1],p[0])) for p in self.check_diag(w_king): if p[1] == 'b' or p[1] == 'q': print("Potential threat: {} on {}".format(p[1],p[0])) for p in self.check_knight(w_king): if p[1] == 'n': print("Potential threat: {} on {}".format(p[1],p[0])) for p in self.check_rank(b_king): if p[1] == 'R' or p[1] == 'Q': print("Potential threat: {} on {}".format(p[1],p[0])) for p in self.check_file(b_king): if p[1] == 'R' or p[1] == 'Q': print("Potential threat: {} on {}".format(p[1],p[0])) for p in self.check_diag(b_king): if p[1] == 'B' or p[1] == 'Q': print("Potential threat: {} on {}".format(p[1],p[0])) for p in self.check_knight(b_king): if p[1] == 'N': print("Potential threat: {} on {}".format(p[1],p[0])) if white_check and not black_check: return(1) elif black_check and not white_check: return(1) elif white_check and black_check: print("Illegal position") return(2) else: return(0) class game(): def __init__(self, PGN): self.positions = [Position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")] self.pgn = PGN # define a main function def main(): # initialize the pygame module pygame.init() screen_hgt = 640 screen_wid = 640 start_size = [screen_wid,screen_hgt] screen_bg = (73, 106, 117) # grey msg = '' msg_color = (0, 0, 255) # blue # Create a Font object with a font of size 24 points fontObj = pygame.font.Font('freesansbold.ttf', 24) # The Clock object makes sure the program runs no faster than the specified # FPS fpsClock = pygame.time.Clock() # load and set the logo. logo = pygame.image.load("board_node_icon.png") pygame.display.set_icon(logo) pygame.display.set_caption("Chess Permutations") # create a surface on screen that has the size of 240 x 180 screen = pygame.display.set_mode(start_size, RESIZABLE) # create board surface Board = board() # Load chess piece artwork art = {'r':pygame.image.load("black rook.png"), 'n':pygame.image.load("black knight.png"), 'b':pygame.image.load("black bishop.png"), 'q':pygame.image.load("black queen.png"), 'k':pygame.image.load("black king.png"), 'p':pygame.image.load("black pawn.png"), 'R':pygame.image.load("white rook.png"), 'N':pygame.image.load("white knight.png"), 'B':pygame.image.load("white bishop.png"), 'Q':pygame.image.load("white queen.png"), 'K':pygame.image.load("white king.png"), 'P':pygame.image.load("white pawn.png")} # define a variable to control the main loop running = True starting_position = Position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") starting_position.FEN_to_array() v_marcques = Position("2kr3r/pp3ppp/2pbbq2/4n2Q/4B3/2N4P/PPP2PP1/R2R2K1 w - - 3 17") v_marcques.FEN_to_array() # main loop while running: # event handling, gets all event from the eventqueue for event in pygame.event.get(): # only do something if the event is of type QUIT if event.type == pygame.QUIT: # change the value to False, to exit the main loop running = False elif event.type == pygame.MOUSEMOTION: mx, my = event.pos msg = ('X: %.3f, Y: %.3f' %(mx, my)) elif event.type == pygame.VIDEORESIZE: screen = pygame.display.set_mode((event.w, event.h), RESIZABLE) elif event.type == pygame.MOUSEBUTTONUP: if event.button == 1: click_x, click_y = event.pos f = chr(int(click_x / Board.square_size) + 97) r = 8 - int(click_y / Board.square_size) print("Clicked {}{}".format(f,r)) #Fill the screen surface object with the specified color screen.fill(screen_bg) # Render the board Board.draw(screen) msgBox = fontObj.render(msg, False, msg_color) screen.blit(msgBox, (0,0)) # Draw the window to the screen pygame.display.flip() # Wait long enough to reduce the FPS to 60fps fpsClock.tick(60) quit_nicely() # run the main function only if this module is executed as the main script # (if you import this as a module then nothing is executed) if __name__=="__main__": # call the main function main()
95988b112ba8773b5e51910b1d583675b448182a
Sorany-Potato/nlp100nock
/nock6.py
1,231
3.6875
4
import ngram import list_subtraction a="paraparaparadise" b="paragraph" x=sorted(set(ngram.ngram(a,2))) y=sorted(set(ngram.ngram(b,2))) print("x:",x) print("y:",y) w=x+y """ 関数ngramの内容 def ngram(text,n): #n字数ごとずらす x=[] for y in range(len(text)): if y==len(text)-n+1: break; x.append(text[y:y+n]) return x """ f=sorted(set(w)) #set型は重複しない要素(同じ値ではない要素、ユニークな要素)のコレクション #しかし元の順序とは異なる s=sorted(set(list_subtraction.list_subtraction(w,f))) c=sorted(set(list_subtraction.list_subtraction(x,s))) d=sorted(set(list_subtraction.list_subtraction(y,s))) """list1-list2の関数 def list_subtraction(list1,list2): #リスト同士の引き算 r=list1 for a in list2: if a in r: r.remove(a) return r """ print("和集合:",f) print("積集合:",s) print("差集合x-y:",c) print("差集合y-x:",d) if 'se' in x: print("xに含まれる") else: print("xに含まれない") if 'se' in y: print("yに含まれる") else: print("yに含まれない")
203c49a5c17d7c8cc22b89b47e00dabf1c3b4fa1
aleexnl/aws-python
/UF1/Nieto_Alejandro_Gomez_Alejandro_PT12/Ej8.py
623
3.9375
4
letrasdni = ["T", "R", "W", "A", "G", "M", "Y", "F", "P", "D", "X", "B", "N", "J", "Z", "S", "Q", "V", "H", "L", "C", "K", "E"] # Iniciamos lista con valores pred. dni = int(input("Introduce los numeros del DNI:")) # Pedimos un DNI while len(str(dni)) != 8: # Comprobamos que tenga esta longitud bucle print("Introduce 8 numeros del DNI") # Mensaje de error int(input("Introduce el DNI:")) # Pedimos datos otra vez calc = dni % 23 # Calculo de la letra en valor no ASCII print("Tu DNI es: ", dni, end="") # Mostramos mensaje print(letrasdni[calc]) # de letra de DNI en la posicion de la lista
896af2ba19237f1a96fa17f7b7a3758b91acdb81
daniel-reich/turbo-robot
/J67xWvM4jFhn9nEpJ_9.py
4,490
4.46875
4
""" Make a function that takes a integer, `size`, returns 2D list that is a Magic Square with side lengths of `size` A Magic Square is an arrangement of numbers in a square in such a way that the sum of each row, column, and diagonal is one constant number, the "magic constant." For this challenge I will be testing with the assumption that your magic squares are made with whole numbers from 1 - n^2 ### Example make_magic(3) ➞ [[2, 7, 6], [9, 5, 1], [4, 3, 8]] # Rows: 2+7+6 = 9+5+1 = 4+3+8 = 15 # Columns: 2+9+4 = 7+5+3 = 6+1+8 = 15 # Diagonals: 2+5+8 = 6+5+4 = 15 ### Notes For this challenge I will only be testing with sizes >= 3 as there are no Magic Squares of size 2 at least as I have described them. """ def make_magic(size): #Determin what kind of Magic Square we are working with return makeOddMagic(size) if (size%2) else makeSEvenMagic(size) if (size%4) else makeDEvenMagic(size) ​ #Make a Magic Square with an odd size def makeOddMagic(size): square = [[0 for i in range(size)] for j in range(size)] #Make empty Matrix x, y = 0, size//2 #Starting index for i in range(1, size**2 + 1): square[abs(x)][y] = i #Check for next index if square[abs((x + 1)%-size)][(y + 1)%size] == 0: x = (x + 1)%-size y = (y + 1)%size else: x = (x - 1)%-size return square # Return the finished Magic Square ​ ​ ​ #Make a Magic Square with a size divisible by 4 def makeDEvenMagic(size): square = [[0 for i in range(size)] for j in range(size)] #Make empty Matrix # Starting with the corners and the middle place the index value as at each location cSize = size//4 # Top left for i in range(0,cSize): for j in range(0,cSize): square[i][j] = (i)*size + j+1 # Top right for i in range(0,cSize): for j in range(size - cSize,size): square[i][j] = (i)*size + j+1 # Bottom Left for i in range(size - cSize,size): for j in range(0,cSize): square[i][j] = (i)*size + j+1 # Bottom right for i in range(size - cSize,size): for j in range(size - cSize,size): square[i][j] = (i)*size + j+1 # Mid for i in range(cSize, size - cSize ): for j in range(cSize, size - cSize): square[i][j] = (i)*size + j+1 # Next place the Backwards index as the value at each location that is still empty for i in range(size): for j in range(size): if square[i][j] == 0: square[i][j] = size**2 - ((i)*size + j) return square # Return the finished Magic Square ​ #Make a Magic Square with an even size that is not divisible by 4 def makeSEvenMagic(size): square = [[0 for i in range(size)] for j in range(size)] #Make empty Matrix # Fill the corners with odd magic squares plus an offset cSize = size//2 Temp = makeOddMagic(cSize) # Top left k = 0 offSet = 0 for i in range(0,cSize): for j in range(0,cSize): square[i][j] = Temp[k//cSize][k%cSize] + offSet k += 1 # Bottom right k = 0 offSet = cSize**2 for i in range(size - cSize,size): for j in range(size - cSize,size): square[i][j] = Temp[k//cSize][k%cSize] + offSet k += 1 # Top right k = 0 offSet = cSize**2*2 for i in range(0,cSize): for j in range(size - cSize,size): square[i][j] = Temp[k//cSize][k%cSize] + offSet k += 1 # Bottom Left k = 0 offSet = cSize**2*3 for i in range(size - cSize,size): for j in range(0,cSize): square[i][j] = Temp[k//cSize][k%cSize] + offSet k += 1 # Make some swaps to correct the Magic square dSize = cSize//2 #top half of swaps for i in range(dSize): for j in range(dSize): temp1 = square[i][j] square[i][j] = square[i + cSize][j] square[i + cSize][j] = temp1 #mid swaps i = dSize for j in range(1, dSize+1): temp1 = square[i][j] square[i][j] = square[i + cSize][j] square[i + cSize][j] = temp1 #top half of swaps for i in range(dSize + 1, dSize*2+1): for j in range(dSize): temp1 = square[i][j] square[i][j] = square[i + cSize][j] square[i + cSize][j] = temp1 # If the size > 6 make some more swaps dSize -= 1 for i in range(cSize): for j in range(size - 1,size - dSize - 1, -1): temp1 = square[i][j] square[i][j] = square[i + cSize][j] square[i + cSize][j] = temp1 return square # Return the finished Magic Square
95b53da71bb60b32345dfc290ac8cf3d2f6f3310
RayArthur/PythonLession
/pro0605/py08.py
1,078
3.8125
4
def f1(a, b): return a + b def f3(): print('Python') def f5(a=1, b=2, c=3): return a + b + c def f7(x, y): if x > y: return x else: return y print(f1, type(f1)) print(f1(1, 3)) print('-' * 30) f2 = lambda a, b : a + b #匿名函式 print(f2, type(f2)) print(f2(3, 5)) print(f2(2, 6)) print('-' * 30) f3() f4 = lambda : print('Python...') f4() print('-' * 30) print(f5(1, 3, 5)) f6 = lambda a=1, b=2, c=3 : a + b + c print(f6()) print(f6(3)) print('-' * 30) # x = input('x=') # y = input('y=') x, y = [int(i) for i in input('輸入 x,y = ').split(',')] print(x, type(x)) print(y, type(y)) print(f'{x} 和 {y} 最大值:{f7(x, y)}') #print(f'{x} 和 {y} 最大值:{f7(int(x), int(y))}') print('-' * 30) b = [] a = input('輸入 x,y = ').split(',') for i in a: b.append(int(i)) x, y = b print(x, type(x)) print(y, type(y)) print(f'{x} 和 {y} 最大值:{f7(x, y)}') f8 = lambda x, y : x if x<y else y print(f'{x} 和 {y} 最小值:{f8(x, y)}')
315533accdcaa4bd590de5b0e511287c6482ba21
ghadd/tictacdrop
/ai.py
7,147
4
4
from config import * from random import shuffle from copy import deepcopy def is_column_valid(board, col): return board[0][col] == 0 # check the search range for rows and columns def is_range_valid(row, col): return row in range(ROWS) and col in range(COLS) # return all valid moves (empty columns) from the board def get_valid_moves(board): return [col for col in range(COLS) if is_column_valid(board, col)] def make_move(board, col, player): # deepcopy is used to take a copy of current board and not affecting the original one temp_board = deepcopy(board) for row in reversed(range(ROWS)): if temp_board[row][col] == 0: temp_board[row][col] = player return temp_board, row, col def count_sequence(board, player, length): """ Given the board state , the current player and the length of Sequence you want to count Return the count of Sequences that have the give length """ def vertical_seq(row, col): """Return 1 if it found a vertical sequence with the required length """ count = 0 for row_index in range(row, ROWS): if board[row_index][col] == board[row][col]: count += 1 else: break return int(count >= length) def horizontal_seq(row, col): """Return 1 if it found a horizontal sequence with the required length """ count = 0 for col_index in range(col, COLS): if board[row][col_index] == board[row][col]: count += 1 else: break return int(count >= length) def neg_diagonal_seq(row, col): """Return 1 if it found a negative diagonal sequence with the required length """ count = 0 col_index = col for row_index in reversed(range(row)): if col_index > ROWS: break elif board[row_index][col_index] == board[row][col]: count += 1 else: break col_index += 1 # increment column when row is incremented return int(count >= length) def pos_diagonal_seq(row, col): """Return 1 if it found a positive diagonal sequence with the required length """ count = 0 col_index = col for row_index in range(row, ROWS): if col_index > ROWS: break elif board[row_index][col_index] == board[row][col]: count += 1 else: break col_index += 1 # increment column when row incremented return int(count >= length) total_count = 0 # for each piece in the board... for row in range(ROWS): for col in range(COLS): # ...that is of the player we're looking for... if board[row][col] == player: # check if a vertical streak starts at (row, col) total_count += vertical_seq(row, col) # check if a horizontal four-in-a-row starts at (row, col) total_count += horizontal_seq(row, col) # check if a diagonal (both +ve and -ve slopes) four-in-a-row starts at (row, col) total_count += (pos_diagonal_seq(row, col) + neg_diagonal_seq(row, col)) # return the sum of sequences of length 'length' return total_count def utility_value(board, player): """ A utility function to evaluate the state of the board and report it to the calling function, utility value is defined as the score of the player who calles the function - score of opponent player, The score of any player is the sum of each sequence found for this player scalled by large factor for sequences with higher lengths. """ opponent = AI_PLAYER if player == HUMAN_PLAYER else HUMAN_PLAYER player_score = count_sequence(board, player, 4) * 99999 + \ count_sequence(board, player, 3) * 999 + \ count_sequence(board, player, 2) * 99 opponent_fours = count_sequence(board, opponent, 4) opponent_score = opponent_fours * 99999 + \ count_sequence(board, opponent, 3) * 999 + \ count_sequence(board, opponent, 2) * 99 return float('-inf') if opponent_fours > 0 else player_score - opponent_score def game_is_over(board): """Check if there is a winner in the current state of the board """ return count_sequence(board, HUMAN_PLAYER, 4) >= 1 or count_sequence(board, AI_PLAYER, 4) >= 1 def minimax_alpha_beta(board, depth, player): # get array of possible moves valid_moves = get_valid_moves(board) shuffle(valid_moves) best_move = valid_moves[0] best_score = float("-inf") # initial alpha & beta values for alpha-beta pruning alpha = float("-inf") beta = float("inf") opponent = HUMAN_PLAYER if player == AI_PLAYER else AI_PLAYER # go through all of those boards for move in valid_moves: # create new board from move temp_board = make_move(board, move, player)[0] # call min on that new board board_score = minimize_beta(temp_board, depth - 1, alpha, beta, player, opponent) if board_score > best_score: best_score = board_score best_move = move return best_move def minimize_beta(board, depth, a, b, player, opponent): valid_moves = [] for col in range(7): # if column col is a legal move... if is_column_valid(board, col): # make the move in column col for curr_player temp = make_move(board, col, player)[2] valid_moves.append(temp) # check to see if game over if depth == 0 or len(valid_moves) == 0 or game_is_over(board): return utility_value(board, player) valid_moves = get_valid_moves(board) beta = b # if end of tree evaluate scores for move in valid_moves: board_score = float("inf") # else continue down tree as long as ab conditions met if a < beta: temp_board = make_move(board, move, opponent)[0] board_score = maximize_alpha(temp_board, depth - 1, a, beta, player, opponent) beta = min(beta, board_score) return beta def maximize_alpha(board, depth, a, b, player, opponent): valid_moves = [] for col in range(7): # if column col is a legal move... if is_column_valid(board, col): # make the move in column col for curr_player temp = make_move(board, col, player)[2] valid_moves.append(temp) # check to see if game over if depth == 0 or len(valid_moves) == 0 or game_is_over(board): return utility_value(board, player) alpha = a # if end of tree, evaluate scores for move in valid_moves: board_score = float("-inf") if alpha < b: temp_board = make_move(board, move, player)[0] board_score = minimize_beta(temp_board, depth - 1, alpha, b, player, opponent) alpha = max(alpha, board_score) return alpha
45c66b48391616d3da159e6a1750eb1a871aff37
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/hamming/9210076ca09b4f089924c9b45732cea7.py
203
3.6875
4
def distance(dna1, dna2): longest = None if len(dna1) >= len(dna2): longest = dna1 else: longest = dna2 dist = 0 for i in range(len(longest)): if dna1[i] != dna2[i]: dist += 1 return dist
16c9f40d3688422c4139d53748f653a62cb1f8a3
ashleynkomo/selection
/Revision exercise 3.py
247
4
4
#Ashley Nkomo #30-09-2014 #Selection Revision Exercises 3 number = int(input("Please enter a number: ")) if 21 <= number <=29: print("The number entered is within range") else: print("The number entered is out of range")
f908862645806a014e3e75777b5b03b857d40567
kevingtzz/DistData
/p1/client.py
1,878
3.71875
4
#Client code """ August 1, 2021 Created by: Sebastian Loaiza Correa """ #Import socket library import socket import constants import os #Variables for connection host = constants.SERVER_ADDRESS port = constants.PORT def runClientSocket(): #Create client socket clientSocket = socket.socket() #Connection with server. first parameter = IP address, second parameter = Connection Port clientSocket.connect((host, port)) print("Connected to server") #Maintain connection with the server while True: #Client command command = input("Enter the command you want to send >> ") informationToSend = "" if command == constants.PUT: key = input("Enter the key >> ") value = input("Enter the value >> ") informationToSend = command+","+key+","+value elif command == constants.GET: key = input("Enter the key >> ") informationToSend = command+","+key elif command == constants.UPDATE: key = input("Enter the key >> ") currentValue = input("Enter the current value >> ") newValue = input("Enter the new value >> ") informationToSend = command+","+key+","+currentValue+","+newValue elif(command == constants.DELETE): key = input("Enter the key >> ") informationToSend = command+","+key elif(command == constants.EXIT): break else: print("Non-existent command, try again") continue #Send message clientSocket.send(bytes(informationToSend, constants.ENCODING_FORMAT)) #Server response response = clientSocket.recv(constants.BUFFER_SIZE) print(response.decode()) #Close connection to the server clientSocket.close() print("Connection closed") #Iniatialize client socket runClientSocket()
27c1cabf5662fd4bed2f3d4c400e644cd87ee34d
zombiyamo/nlp100
/1/08.py
473
3.875
4
# -*- coding: utf-8 -*- import sys def cipher(text): rText = '' for letter in text: if 97 <= ord(letter) <= 122: rText += chr(219 - ord(letter)) else: rText += letter return rText # return "".join(chr(219-ord(c)) if c.islower() else c for in text) args = sys.argv text = '' if len(args) >= 2: for i in xrange(len(args)-1): text += args[i+1] + ' ' print cipher(text) print cipher(cipher(text))
f577d321d59b4267ccc87a08bf95f9d678a3cf97
rirwin/sandbox
/scratch/python-dp/longest_common_subsequence.py
355
3.5
4
import numpy def lcs_1(s1,s2): if len(s1) == 0 or len(s2) == 0: return 0 elif s1[0] == s2[0]: return lcs_1(s1[1:], s2[1:]) + 1 else: return max(lcs_1(s1,s2[1:]), lcs_1(s1[1:],s2)) def lcs_2(s1,s2): n = len(s1) m = len(s2) mat = numpy.zeros(n,m) s1 = "theryan" s2 = "aryanirwin" print lcs_1(s1, s2)
328a1870ed5ca480a3123b643812d6f21536924c
PragayanParamitaMohapatra/Basic_python
/DataStructure/convert_integer_to_binary.py
345
4.03125
4
""" use stack data structure to convert the integer values to binary values """ from DataStructure.stack import StackDs def div_by_2(dec_num): s=StackDs() while dec_num>0: rem=dec_num%2 s.push(rem) dec_num=dec_num//2 bin_num="" while not s.is_empty(): bin_num += str(s.pop()) return bin_num
1fa1383f2a5ad583e70a8162001eae75ed5c2e9d
BetterRules/example-rules-as-code
/python/test.py
1,715
4.03125
4
#!/usr/bin/env python import csv from run import Person def make_bool(value): if value == 'Yes': return True if value == 'No': return False return None if __name__ == "__main__": # open up the csv file containing the tests with open('../shared/example_beards.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 passes = 0 failures = 0 # Read each line for row in csv_reader: if line_count > 0: # skip the line with headers test_num = line_count - 1 # call our Rules as Code python bob = Person() bob.facial_hair_length_gt_5 = make_bool(row[0]) bob.facial_hair_on_chin = make_bool(row[1]) bob.facial_hair_uninterupted = make_bool(row[2]) expected = make_bool(row[3]) # value the csv says we should get result = bob.has_a_beard() # the value our code retuns # Check we got the same result as the csv said try: assert result == expected except AssertionError as e: # got a different result, print it print("Test {test_num}. Expected {expected}, got {result}.".format( test_num=test_num, result=result, expected=expected)) failures += 1 else: passes += 1 line_count += 1 # Print a summary print('Run {line_count} tests. {passes} passes. {failures} failures.'.format( line_count=line_count-1, passes=passes, failures=failures))
94a6b47a8468ddc40a758b8c22d0c1894af05fa3
igorfelipes/Estrutura_de_dados_UNIESP
/Exercicios_estrutura_de_dados/exercicioH.py
263
3.9375
4
def main(): ages = [] for i in range(5): ages.append(int(input('Digite o ano de nascimento: '))) ages.sort() print('Crescente: ', ages) ages.sort(reverse=True) print('Decrescente: ', ages) if __name__ == "__main__": main()
9789613a8beff9f27a8429d0a82410de59f78fe7
reiniscirpons/freebandlib
/freebandlib/digraph.py
3,776
4.125
4
"""Graph utility functions.""" from typing import List, Optional DigraphVertex = int DigraphAdjacencyList = List[List[DigraphVertex]] def digraph_reverse(digraph: DigraphAdjacencyList) -> DigraphAdjacencyList: """Create the reverse digraph of the input. Does not modify the input digraph. Parameters ---------- digraph: DigraphAdjacencyList An adjacency list. Returns ------- DigraphAdjacencyList An adjacency list of the reverse digraph. Notes ----- The reverse digraph of a digraph has the same vertices but has each edge is reversed, i.e. the reverse digraph has a directed edge :math:`(u, v)` if and only there is an edge :math:`(v, u)` in the original graph. """ result: DigraphAdjacencyList = [[] for _ in digraph] vertex_u: DigraphVertex vertex_v: DigraphVertex neighbours_u: List[DigraphVertex] for vertex_u, neighbours_u in enumerate(digraph): for vertex_v in neighbours_u: result[vertex_v].append(vertex_u) return result def digraph_is_reachable( digraph: DigraphAdjacencyList, start: List[DigraphVertex] ) -> List[bool]: """For each vertex determine if it can be reached from any start vertex. Parameters ---------- digraph: DigraphAdjacencyList An adjacency list. start: List[DigraphVertex] The list of starting vertices. Returns ------- is_reachable: List[bool] A list such that `is_reachable[v]` is `True` whenever `v` is reachable from some starting vertex and `False` otherwise. Notes ----- A vertex `v` is reachable from a vertex `u` if there is a directed path starting at `u` and ending in `v`. This is calculated by using a breadth first traversal. """ i: int = 0 is_reachable: List[bool] = [False for _ in digraph] vertex_u: DigraphVertex for vertex_u in start: is_reachable[vertex_u] = True vertex_v: DigraphVertex que: List[DigraphVertex] = start[::] while i < len(que): vertex_u = que[i] for vertex_v in digraph[vertex_u]: if not is_reachable[vertex_v]: que.append(vertex_v) is_reachable[vertex_v] = True i += 1 return is_reachable def digraph_topological_order( digraph: DigraphAdjacencyList, ) -> Optional[List[DigraphVertex]]: """Return the digraph vertices in topological order if possible. Returns `None` if the digraph contains a directed cycle. Parameters ---------- digraph: DigraphAdjacencyList An adjacency list. Returns ------- Optional[List[DigraphVertex]] A list of vertices in topological order, if such an order exists, and `None` otherwise. Notes ----- We say that the vertices are in topological order if no child vertex occurs before its parent in the ordering. Such an ordering exists if and only if the digraph contains no ordered cycle. This is calculated using Kahn's algorithm. """ times_seen: List[int] = [0 for _ in digraph] vertex_u: DigraphVertex vertex_v: DigraphVertex neighbours_u: List[DigraphVertex] for vertex_u, neighbours_u in enumerate(digraph): for vertex_v in neighbours_u: times_seen[vertex_v] += 1 topo_order: List[DigraphVertex] = [ u for u, t in enumerate(times_seen) if t == 0 ] i: int = 0 while i < len(topo_order): vertex_u = topo_order[i] for vertex_v in digraph[vertex_u]: times_seen[vertex_v] -= 1 if times_seen[vertex_v] == 0: topo_order.append(vertex_v) i += 1 if len(topo_order) != len(digraph): return None return topo_order
18ffaf2f32689e739646cf04914568cfda69233c
ssrajputtheboss/DSI
/python/item/item.py
953
3.546875
4
from datetime import datetime class item(): def __init__(this ,id : int , name : str , mntime : datetime): this._id = id this._name = name this._mntime = mntime def __repr__(this) -> str: return repr(( this._id , this._name , this._mntime )) def __str__(this) -> str: return f" [ Item(id:{this._id} , name:{this._name} , mndate:{this._mntime}) ];" def __lt__(this,other) -> bool: return this.id < other.id @property def id(this) -> int: return this._id @id.setter def id(this,id:int) -> None: this._id = id @property def name(this) -> str: this._name @name.setter def name(this,name:str) -> None: this.name = name @property def mntime(this) -> datetime: return this._mntime @mntime.setter def mntime(this , mntime:datetime) -> None: this._mntime = mntime if __name__ == '__main__': pass