blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d80609efb93c77a0b9ccdf1f878f9ff14b177ea0
pavelchub1997/Software-implementation-of-work-with-elliptic-curves
/NOD.py
2,737
3.59375
4
import time def input_value(msg): while True: try: val = int(input(msg)) break except ValueError: print('Ошибка. Повторите ввод!') return val def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def extended_gcd(a, b): if b == 0: return a, 1, 0 else: x_2, x_1, y_2, y_1 = 1, 0, 0, 1 while b > 0: q = int(a/b) r = a - q*b x = x_2 - q*x_1 y = y_2 - q*y_1 a, b, x_2, x_1, y_2, y_1 = b, r, x_1, x, y_1, y return a, x_2, y_2 def binary_gcd(a, b): m, n, d = a, b, 1 while not (m == 0 or n == 0): if m%2 == 0 and n%2 == 0: d *= 2 m //= 2 n //= 2 elif m%2 == 0 and n%2 == 1: m //= 2 elif m%2 == 1 and n%2 == 0: n //= 2 elif m%2 == 1 and n%2 == 1 and m>=n: m -= n elif m % 2 == 1 and n % 2 == 1 and m <= n: n -= m if m == 0: return d*n elif n == 0: return d*m if __name__ == '__main__': while True: while True: a = input_value('Введите значение для переменной а: ') b = input_value('Введите значение для переменной b: ') if a < b: print('Ошибка ввода, так как необходимо ввести значение а >= b') else: break t = time.clock() print('Обычный алгоритм Евклида: ', gcd(a, b)) t_1 = time.clock() print('Время выполнения работы обычного алгоритма Евклида', t_1 - t) t = time.clock() d, x, y = extended_gcd(a, b) print('Расширенный алгоритм Евклида (ax + by = d): (', a, '*', x, '+', b, '*', y, '=', d, ')') t_1 = time.clock() print('Время выполнения работы расширенного алгоритма Евклида', t_1 - t) t = time.clock() print('Бинарный алгоритм Евклида: ', binary_gcd(a, b)) t_1 = time.clock() print('Время выполнения работы бинарного алгоритма Евклида', t_1 - t) ans = input('Хотите продолжить работу? (Да или Нет)\n') if ans == 'Да': continue elif ans == 'Нет': print('Работа завершена! Хорошего дня!') break else: print('Ошибка. Аварийное завершение работы.') break
f062ed597a64911eda53043d377c5956c5e832ec
3r10/SimPly
/examples/triangle_i_j.py
130
3.5
4
m = 5 n = 4 # matrix triangle i = 0 while i<m: print(i) j = i while j<n: print(j) j = j+1 i = i+1
936733f7ad3bd505a17c069fbb8c36259a15a450
riyaminiarora/python
/companymanager.py
3,514
4.125
4
from abc import ABC,abstractmethod class Employee(ABC): @abstractmethod def calculatesalary(self): pass class HourlyEmployee(Employee): def __init__(self,name,perhrsalary,totalhours): self.name=name self.perhrsalary=perhrsalary self.totalhours=totalhours def calculatesalary(self): cal=self.perhrsalary*self.totalhours print("total calculated salary of "+self.name+" is "+str(cal)) class SalariedEmployee(Employee): def __init__(self,name,monthly_salary,allowance): self.name=name self.monthly_salary=monthly_salary self.allowance=allowance def calculatesalary(self): cal=self.monthly_salary+self.allowance print("total calculated salary of "+self.name+" is "+str(cal)) class Manager(Employee): def __init__(self,name,base_salary,bonus): self.name=name self.base_salary=base_salary self.bonus=bonus def return_salary(self): return self.base_salary def calculatesalary(self): cal=self.base_salary+2*self.bonus print("total calculated salary of "+self.name+" is "+str(cal)) class Executive(Employee): def __init__(self,name,base_salary,experience): self.name=name self.base_salary=base_salary self.experience=experience def calculatesalary(self): cal=self.base_salary+4*self.experience print("total calculated salary of "+self.name+" is "+str(cal)) class Company(): def __init__(self,base_salary): self.base_salary=base_salary def HireEmp(self): eh_no=input("enter no of employees to be hired:") print("enter details of employee to be hired:") for i in range(int(eh_no)): e_name=input('enter emp name:') e_desig=input("enter emp desig:") fh=open(r"C:\Users\user\Desktop\abc.txt",'a') fh.write(e_name+"\t ") fh.write(e_desig) fh.write("\n") fh.close() print(eh_no+" employee(s) is/are hired") def FireEmp(self): ef_no=int(input('enter no of employees to be fired:')) for i in range(int(ef_no)): ef_name=input('enter name of emp to be fired:') fh=open(r"C:\Users\user\Desktop\abc.txt","r") lines=fh.readlines() fh=open(r"C:\Users\user\Desktop\abc.txt","w") for line in lines: if ef_name not in line: fh.write(line) fh.close() print(str(ef_no)+" employee(s) is/are fired") def raise_emp_sal(self,object1): #object1 here want to take object of manager class salary = object1.return_salary() name=input('enter name of employee whose salary has to be raised:') salary=self.base_salary+0.1*self.base_salary print('salary of employee '+name+' is raised to '+str(salary)) H_E=HourlyEmployee("rahul",25,360) H_E.calculatesalary() S_E=SalariedEmployee("vishal",30000,250) S_E.calculatesalary() man=Manager("abc",40000,500) man.calculatesalary() man.return_salary() ex=Executive("pqr",50000,4) ex.calculatesalary() com= Company(30000) print("enter 1 to hire emp") print("enter 2 to fire emp") print("enter 3 to raise emp salary") while True: choice=int(input("enter your choice:")) if choice==1: com.HireEmp() elif choice==2: com.FireEmp() elif choice==3: com.raise_emp_sal(man) else: break
14e10d396411fe185a1e09469effffe296356f99
suppix/zabbifier-web
/utils.py
727
3.921875
4
def human_readable_date(timedelta): age = "" age_length = 0 if timedelta.years != 0: age += str(timedelta.years) + "y " age_length += 1 if timedelta.months != 0: age += str(timedelta.months) + "m " age_length += 1 if timedelta.days != 0: age += str(timedelta.days) + "d " age_length += 1 if timedelta.hours != 0 and age_length < 3: age += str(timedelta.hours) + "h " age_length += 1 if timedelta.minutes != 0 and age_length < 3: age += str(timedelta.minutes) + "m " age_length += 1 if timedelta.seconds != 0 and age_length < 3: age += str(timedelta.seconds) + "s " age_length += 1 return age
0f6678e949fba358dd10dbfe95bac5d84e049d50
lukbor2/learning
/Python/tutorial_5_1_3.py
277
3.6875
4
def f(x): return x%3 == 0 or x%5 == 0 def cube(x): return x*x*x a = [] for i in filter(f, range(2,25)): a.append(i) print("Result from the filter function", a) a = [] for i in map(cube, range(1,11)): a.append(i) print("Result from the map function", a)
58db07868d189e9da73d06f92aafd8ac9ec31983
Zitelli-Devkek/Drones-con-Python
/Ejercicios practicos Drones/ej-de-codigo-python drones-concatenar.py
376
3.90625
4
nombreAlumno = input ("Ingrese su nombre de pila: ") apellidoAlumno = input ("Ingrese su apellido: ") print("Bienvenido a Aprendé Programando Virtual" + " " + nombreAlumno + " " + apellidoAlumno) edadAlumno = input ("Ingrese su edad expresada en letras: ") print ("Hola, soy" + " " + nombreAlumno + " " + apellidoAlumno + " " "y tengo" " " + edadAlumno + " " + "años")
3481a3ec7f7e62db87b4daaa29348341ddffdc04
jamesdeal89/imageWriter
/imageWriter.py
1,983
4.09375
4
# a class which will generate an image and write that image to a file. import random class CreateImage(): def __init__(self, fileLocation, h=640, w=480): self.fileLoc = fileLocation self.height = h self.width = w def save(self): print("\nImage Save Starting...") # here we will save using a basic image format called 'PPM'. It requires very little data. f = open(self.fileLoc, "w") # for PPM file format the file starts with the magic no. 'P3' to show it's filetype. f.write("P3\n") # width and height is stated next as part of the PPM format. f.write(str(self.width)+ " " + str(self.height) + "\n") # we state the max value of colour on the third line. f.write("255\n") # we start to write the actual image data via a loop to iterate through each RGB value. for row in self.pixels: for collum in row: for colour in collum: # writes the colour to the file and seperates with a space. f.write(str(colour) + " ") print("-", end="") # seperates each set of colours. f.write(" ") # creates a new line for each row of pixel data. f.write("\n") print() def generateRandom(self): print("Image Generation Starting...") # random pixels # grid of pixels self.pixels = [] for y in range(0,self.height): tempList = [] print(".",end='') for x in range(0,self.width): r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) tempList.append([r,g,b]) self.pixels.append(tempList) # save an individual pixel # red, green, blue, alpha values Image1 = CreateImage("testImage1.ppm",360,480) Image1.generateRandom() Image1.save()
b73c505f544a5d3a4ee7eb7adbfd90351a8f37a5
zelzhan/Challenges-and-contests
/LeetCode/sort_characters_by_frequency.py
451
3.765625
4
from heapq import heappop, heappush from collections import Counter class Solution: def frequencySort(self, s: str) -> str: counter = Counter(s) heap = [] for char, freq in counter.items(): heappush(heap, (-freq, char)) res = "" while heap: freq, char = heappop(heap) res += char * (-freq) return res
7ef990e6859448a849bdcfadb67024650f9f6573
MingfeiPan/leetcode
/array/31.py
714
3.5625
4
class Solution: def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ # reverse # nums[i:] = nums[:(i-1):-1] pivot = len(nums) - 2 while pivot >= 0 and nums[pivot+1] <= nums[pivot]: pivot -= 1 print(pivot) if pivot >= 0: flag = len(nums) - 1 while flag >= 0 and nums[flag] <= nums[pivot]: flag -= 1 nums[pivot], nums[flag] = nums[flag], nums[pivot] nums[(pivot+1):] = nums[:pivot:-1] else: nums.reverse()
24dd50854e648212add116f24b45ae4e0d8b2ef2
R110/dquest-datastructures
/traversetrees.py
2,509
3.703125
4
level_order = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] class Node: def __init__(self, value=None): self.value = value self.left = None self.right = None def __repr__(self): return "<Node: {}>".format(self.value) class BaseBinaryTree: def __init__(self, values=None): self.root = None if values: self.insert(values) def insert(self, values, index=0, leftright=''): node = None if index < len(values): node = Node(value=values[index]) # print(leftright, node) if not self.root: self.root = node node.left = self.insert(values, index=index*2+1, leftright='L') node.right = self.insert(values, index=index*2+2, leftright='R') # print("left node of", node, "--", node.left) # print("right node of", node, "--", node.right) return node class BinaryTree(BaseBinaryTree): def preorder_traverse(self, node): if not node: return [] return ( [node.value] + self.preorder_traverse(node.left) + self.preorder_traverse(node.right) ) def inorder_traverse(self, node): if not node: return [] #print(node.value) 2x return ( self.inorder_traverse(node.left) + [node.value] + self.inorder_traverse(node.right) ) def postorder_traverse(self, node): if not node: return [] return ( self.postorder_traverse(node.left) + self.postorder_traverse(node.right) + [node.value] ) # #[1, 2, 4, 8, 9, 5, 10, 3, 6, 7] # Initial(1) preorder -> (2) + 1 + (3) # To dictate --> 4 (node), 8, 9 --> base case returns empty list # 2 -> 2 + (4) + (5) # 4 -> 4 + (8) + (9) # 8 -> 8 + [] + []... # # #[8, 9, 4, 10, 5, 2, 6, 7, 3, 1] # Initial(1) postorder -> (2) + (3) + 1 # ---(Left)-- # 2 -> (4) + (5) + 2 # 4 -> (8) + (9) + 4 # 8 -> [] + [] + 8 # 9 -> [] + [] + 9 # # --> [8,9,4,] # # (2 -> (4) + (5) + 2) execute (5) # 5 -> (10) + [] + 5 # 10 -> [] + [] + 10 # # -->[8,9,4,10,5,] # # --Right--- # 3 -> (6) + (7) + 3 # 6 -> [] + [] + 6 # 7 -> [] + [] + 7 # # -->[8, 9, 4, 10, 5, 2, 6, 7, 3, 1] tree = BinaryTree(level_order) preorder = tree.preorder_traverse(tree.root) inorder = tree.inorder_traverse(tree.root) postorder = tree.postorder_traverse(tree.root) print(preorder,'\n', inorder, '\n', postorder)
fefdb4d3f17dbf27ca0602862a1c926daeee1e03
1914866205/python
/pythontest/day02.py
1,361
4.1875
4
""" 英制单位英寸和公制单位厘米互换 """ value = float(input('请输入长度:')) unit = input('请输入单位:') if unit == 'in' or unit == '英寸': print('%f英寸=%f厘米' % (value, value*2.54)) elif unit == 'cm' or unit == '厘米': print('%f厘米=%f英寸' % (value, value/2.54)) else: print('请输入有效的单位') """ 百分制成绩转换为等级制成绩 要求: 如果输入的成绩在90分以上(90分)输入A; 如果输入的成绩在80-90分以上(不含90分)输入B; 如果输入的成绩在70-80分以上(不含80分)输入C; 如果输入的成绩在60-70分以上(不含70分)输入D; 如果输入的成绩在60分以下,输入E; """ score = float(input('请输入成绩:')) if score >= 90: grade = 'A' elif score >= 80: grade = 'B' elif score >= 70: grade = 'C' elif score >= 60: grade = 'D' else: grade = 'E' print('对应的等级是:', grade) """ 判断输入的边长能否构成三角形,如果能则计算出三角形的周长和面积 """ a = float(input('a=')) b = float(input('b=')) c = float(input('c=')) if a+b > c and a+c > b and b+c > a: print('周长:%f' % (a+b+c)) p = (a+b+c)/2 area = (p*(p-a)*(p-b)*(p-c)**0.5) print('面积:%f' % (area)) else: print('不能构成三角形')
d93da0ddddc75135c8d6305cd13e23c519fa3fdd
SuguruChhaya/python-exercises
/Hackerrank Python/nested lists.py
3,365
4.15625
4
''' # * Approach 1: Don't even use the nested list and use a lot of for loops if __name__ == '__main__': name_list = [] score_list = [] sorted_score_list = [] runner_up_score = 0 dictionary = {} for _ in range(int(input())): name = input() score = float(input()) name_list += [name] score_list += [score] sorted_score_list += [score] # ?Python lists are mutable. That is why score_list and sorted_score_list have the same value # ?I think it is a good idea to make two separate lists in the for loop stage # ?So I don't need to base sorted_score_list off another list sorted_score_list.sort() #!I forgot that it was the second from the bottom we were looking for for item in range(len(sorted_score_list) - 1): if sorted_score_list[item] < sorted_score_list[item + 1]: runner_up_score = sorted_score_list[item + 1] break for make in range(len(name_list)): dictionary[name_list[make]] = score_list[make] #!The sorting is messing the dictionary up final_names = [] for key, value in dictionary.items(): if value == runner_up_score: final_names.append(key) final_names.sort() for item in final_names: print(item) ''' ''' #* Approach 2: Actually use nested lists marksheet = [] scoresheet = [] if __name__ == "__main__": for _ in range(int(input())): name = input() score = float(input()) #!Make sure to put two brackets around #!If I don't the list wouldn't be a nested list and I will have trouble while iterating marksheet += [[name, score]] scoresheet += [score] #!This following line gives the 2nd lowest mark #?Python sets are a different datatype from dictionaries. #?When converted to a set, all duplicates are deleted. #?Sets are immutable and isn't reliable to access through index because it can come out in random order #!But, after we sort the sort the set, we can confidently access it. #!You cannot prepare a set beforehand by assigning a variable to a "{}". This will cause to make a dictionary, not a set. #!The only way to make a set is by set() x = sorted(set(scoresheet))[1] for n, s in sorted(marksheet): if s == x: print(n) ''' #*Approach 3: Similar to appraoch 2 but use dictionaries instead of nested lists mydict = {} score_tracker = [] if __name__ == "__main__": for i in range(int(input())): name = input() score = float(input()) mydict[name] = score score_tracker +=[score] y = sorted(set(score_tracker))[1] #!I can also sort dictionaries, but in a different way #?https://www.geeksforgeeks.org/iterate-over-a-dictionary-in-python/ for i in sorted(mydict): if mydict[i] == y: print(i) #*Reference ''' a = [2,1] b = a.sort() print(b) #!This will not return anything #!The way to use sort() is after a list, and you can't print it. b = sorted(a) print(b) #!But this returns [2,1]. sort() and sorted() do similar things but I have to use it in different ways Additionally, print(sorted(set([2,3,1]))) print({2,3,1}).sort() .sort() is only for lists. but sorted() works for dictionary-like data structures too. thislist = [1,1,2,3] a = {} for b in thislist: a.add(b) print(a) '''
2a2457834bab1bec936359645fd4dde123a0374e
samorajp/reaktorpy
/trener/dzien3/break.py
416
3.59375
4
import random sekret = random.randint(1, 6) proba = 1 while True: wpisana = int(input("Twój strzał: ")) if wpisana == sekret: print("WYGRAŁEŚ W PRÓBIE", proba) break else: print("NIE TRAFIŁEŚ") if wpisana < sekret: print("Za mała!") else: print("Za duża") proba += 1 if proba > 3: break print(sekret)
c65df2de87e164a76b4e1a297516d1dfd20b788e
PeterLD/algorithms
/trees/parse_tree.py
1,824
3.5625
4
from data_structures.linear import Stack from data_structures.trees import BinaryTree import operator def build_parse_tree(expression): expression = expression.split() tree_stack = Stack() parse_tree = BinaryTree('') tree_stack.push(parse_tree) current_tree = parse_tree for token in expression: if token == '(': current_tree.insert_left('') tree_stack.push(current_tree) current_tree = current_tree.get_left_child() elif token not in ['+', '-', '*', '/', ')']: current_tree.set_root_value(int(token)) parent = tree_stack.pop() current_tree = parent elif token in ['+', '-', '*', '/']: current_tree.set_root_value(token) current_tree.insert_right('') tree_stack.push(current_tree) current_tree = current_tree.get_right_child() elif token == ')': current_tree = tree_stack.pop() else: raise ValueError return parse_tree def evaluate_parse_tree(parse_tree): operators = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv } left_child = parse_tree.get_left_child() right_child = parse_tree.get_right_child() if left_child and right_child: function = operators[parse_tree.get_root_value()] return function(evaluate_parse_tree(left_child), evaluate_parse_tree(right_child)) else: return parse_tree.get_root_value() if __name__ == '__main__': expression = "( ( 10 + 5 ) * 3 )" print "Building parse tree for {}".format(expression) tree = build_parse_tree(expression) print "Evaluating parse tree for {}".format(expression) print "Value: {}".format(evaluate_parse_tree(tree))
7d5b3b590f4977a8b3d69e82a39ef24505a79c1c
fyabc/BT4MolGen
/fairseq/tasks/dual_translation.py
2,380
3.640625
4
#! /usr/bin/python # -*- coding: utf-8 -*- from .translation import TranslationTask from . import register_task @register_task('cycle_back_translation') class DualTranslation(TranslationTask): r"""A task for cycle-loop dual translation (back translation). Forward model f: x -> y Backward model g: y -> x Parallel data: (X_p, Y_p) Monolingual data: X_m1, Y_m2 Training process: Translation: Y'_p = f(X_p) (train, grad) Back translation: Y'_m1 = f(X_m1) (gen, no_grad); X''_m1 = g(Y'_m1) = g(f(X_m1)) (forward, grad) X'_m2 = g(Y_m2) (gen, no_grad); Y''_m2 = f(X'_m2) = f(g(Y_m2)) (forward, grad) Loss: 3 components Loss = L(Y_p, Y'_p) + \lambda1 * L(X_m1, X''_m1) + \lambda2 * L(Y_m2, Y''_m2) Training process (2): Translation: Y'_p = f(X_p) (train, grad) Back translation: Y'_m1 = f(X_m1) (gen, no_grad) X'_m2 = g(Y_m2) (gen, no_grad) Loss: 3 components L(Y_p, Y'_p) + TODO References: 1. Dual learning tutorial: https://taoqin.github.io/DualLearning_ACML18.pdf 2. We follow the `bt_step` method of https://github.com/facebookresearch/XLM/blob/master/src/trainer.py#L870 to write our implementation. 3. Another reference: https://github.com/apeterswu/RL4NMT/blob/master/tensor2tensor/utils/model_builder.py#L132 """ @staticmethod def add_args(parser): """Add task-specific arguments to the parser.""" TranslationTask.add_args(parser) # fmt: off parser.add_argument('--mono-src', default=None, metavar='PATH', help='Path to monolingual source data') parser.add_argument('--mono-tgt', default=None, metavar='PATH', help='Path to monolingual target data') # fmt: on def __init__(self, args, src_dict, tgt_dict): super().__init__(args, src_dict, tgt_dict) # Monolingual datasets. self.mono_src_dataset = None self.mono_tgt_dataset = None @classmethod def setup_task(cls, args, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ return super().setup_task(args, **kwargs) def _load_monolingual_dataset(self): # TODO pass
f7c32ab14df3b73cc6ffd8fb01b4f73db85c1ee1
abdullahbilalawan/GAUSS-ELIMINATION-PYTHON-CODE
/gauss elimination.py
2,107
3.984375
4
import numpy import math # defining a matrix #steps of gauss elimination' # 1 make 1st element of row equal to 1 # make elements under it to 0 # make second row pivot be 0 # make zero under it # heading print("============================================GAUSS ELIMINATION FOR 3 VARIABLES ========================================================") print("$$$$$$$$$$$$$$$$$$$$$$$$$$$ ENTER THE ELEMENTS OF THE AUGMENTED MATRIX A VERY CAREFULY $$$$$$$$$$$$$$$$$$$$$$$$$$$") # taking inputs row_1 = [int(input("x1= ")),int(input("y1=")),int(input("z1=")),int(input("b1=")), ] row_2 = [int(input("x2=")),int(input("y2=")),int(input("z2=")),int(input("b2=")), ] row_3 = [int(input("x3=")),int(input("y3=")),int(input("z3=")),int(input("A34=")), ] # creating the matrix A = numpy.array([row_1,row_2,row_3], dtype='f') pivot = 0 #making the first element 1 and 0,s under it if A[0][0] !=1: A[0] = numpy.true_divide(A[0],A[0][0]) for i in range(1,3): if A[:,0][i] != 0 and A[:,0][i]>0: A[i] = A[:,0][i]*A[0] - A[i] else: A[i] = A[:, 0][i] * A[0] + A[i] else: for i in range(1,3): if A[:,0][i] != 0 and A[:,0][i]>0: A[i] = A[:,0][i]*A[0] - A[i] else: A[i] = A[:, 0][i] * A[0] + A[i] # making the pivot in second row and 0,s under it if A[1][1] !=1: A[1] = numpy.true_divide(A[1],A[1][1]) for i in range(2,3): if A[:,1][i] != 0 and A[:,1][i]>0: A[i] = A[:,1][i]*A[1] - A[i] else: A[i] = A[:, 1][i] * A[1] + A[i] # making the last pivot if A[2][2]!=1: A[2] = A[2] / A[2][2] # solving the equations coeffecient_matrix = A[0:3,:3] B_matrix = A[:3,3:4] Answer = numpy.linalg.solve(coeffecient_matrix,B_matrix) print("the answer of three variables are") print("x=",Answer[0],"y=",Answer[1],"z=",Answer[2]) print("if answer is nan , it shows that the linear system has infinite or no solution")
02af31e3d9a1f5c92efca4b9fa9b01f8108ca690
Zhuogang/Python_Computation
/Python_for_NuclearEngineering/ch20.py
10,375
4.1875
4
import numpy as np import matplotlib.pyplot as plt def swap_rows(A, a, b): """Rows two rows in a matrix, switch row a with row b args: A: matrix to perform row swaps on a: row index of matrix b: row index of matrix returns: nothing side effects: changes A to rows a and b swapped """ assert (a>=0) and (b>=0) N = A.shape[0] #number of rows assert (a<N) and (b<N) #less than because 0-based indexing temp = A[a,:].copy() A[a,:] = A[b,:].copy() A[b,:] = temp.copy() def LU_factor(A,LOUD=True): """Factor in place A in L*U=A. The lower triangular parts of A are the L matrix. The L has implied ones on the diagonal. Args: A: N by N array Returns: a vector holding the order of the rows, relative to the original order Side Effects: A is factored in place. """ [Nrow, Ncol] = A.shape assert Nrow == Ncol N = Nrow #create scale factors s = np.zeros(N) count = 0 row_order = np.arange(N) for row in A: s[count] = np.max(np.fabs(row)) count += 1 if LOUD: print("s =",s) if LOUD: print("Original Matrix is\n",A) for column in range(0,N): #swap rows if needed largest_pos = np.argmax(np.fabs(A[column:N,column]/s[column])) + column if (largest_pos != column): if (LOUD): print("Swapping row",column,"with row",largest_pos) print("Pre swap\n",A) swap_rows(A,column,largest_pos) #keep track of changes to RHS tmp = row_order[column] row_order[column] = row_order[largest_pos] row_order[largest_pos] = tmp #re-order s tmp = s[column] s[column] = s[largest_pos] s[largest_pos] = tmp if (LOUD): print("A =\n",A) for row in range(column+1,N): mod_row = A[row] factor = mod_row[column]/A[column,column] mod_row = mod_row - factor*A[column,:] #put the factor in the correct place in the modified row mod_row[column] = factor #only take the part of the modified row we need mod_row = mod_row[column:N] A[row,column:N] = mod_row return row_order def LU_solve(A,b,row_order): """Take a LU factorized matrix and solve it for RHS b Args: A: N by N array that has been LU factored with assumed 1's on the diagonal of the L matrix b: N by 1 array of righthand side row_order: list giving the re-ordered equations from the the LU factorization with pivoting Returns: x: N by 1 array of solutions """ [Nrow, Ncol] = A.shape assert Nrow == Ncol assert b.size == Ncol assert row_order.max() == Ncol-1 N = Nrow #reorder the equations tmp = b.copy() for row in range(N): b[row_order[row]] = tmp[row] x = np.zeros(N) #temporary vector for L^-1 b y = np.zeros(N) #forward solve for row in range(N): RHS = b[row] for column in range(0,row): RHS -= y[column]*A[row,column] y[row] = RHS #back solve for row in range(N-1,-1,-1): RHS = y[row] for column in range(row+1,N): RHS -= x[column]*A[row,column] x[row] = RHS/A[row,row] return x def inversePowerBlock(M11, M21, M22, P11, P12,epsilon=1.0e-6,LOUD=False): """Solve the generalized eigenvalue problem (M11 0 ) (phi_1) = 1/k (P11 P12) using inverse power iteration (M21 M22) (phi_2) (0 0 ) Inputs Mij: An LHS matrix (must be invertible) P1j: A fission matrix epsilon: tolerance on eigenvalue Outputs: l: the smallest eigenvalue of the problem x1: the associated eigenvector for the first block x2: the associated eigenvector for the second block """ N,M = M11.shape assert(N==M) #generate initial guess x1 = np.random.random((N)) x2 = np.random.random((N)) l_old = np.linalg.norm(np.concatenate((x1,x2))) x1 = x1/l_old x2 = x2/l_old converged = 0 #compute LU factorization of M11 row_order11 = LU_factor(M11,LOUD=False) #compute LU factorization of M22 row_order22 = LU_factor(M22,LOUD=False) iteration = 1; while not(converged): #solve for b1 b1 = LU_solve(M11,np.dot(P11,x1) + np.dot(P12,x2),row_order11) #solve for b2 b2 = LU_solve(M22,np.dot(-M21,b1),row_order22) #eigenvalue estimate is norm of combined vectors l = np.linalg.norm(np.concatenate((b1,b2))) x1 = b1/l x2 = b2/l converged = (np.fabs(l-l_old) < epsilon) l_old = l if (LOUD): print("Iteration:",iteration,"\tMagnitude of l =",1.0/l) iteration += 1 return 1.0/l, x1, x2 def create_grid(R,I): """Create the cell edges and centers for a domain of size R and I cells Args: R: size of domain I: number of cells Returns: Delta_r: the width of each cell edges: the cell edges of the grid centers: the cell centers of the grid """ Delta_r = float(R)/I centers = np.arange(I)*Delta_r + 0.5*Delta_r edges = np.arange(I+1)*Delta_r return Delta_r, centers, edges def TwoGroupDiffusionEigenvalue(R,I,D1,D2,Sig_r1,Sig_r2, nu_Sigf1, nu_Sigf2,Sig_s12, geometry,epsilon = 1.0e-8): """Solve a neutron diffusion eigenvalue problem in a 1-D geometry using cell-averaged unknowns Args: R: size of domain I: number of cells Dg: name of function that returns diffusion coefficient for a given r Sig_rg: name of function that returns Sigma_rg for a given r nuSig_fg: name of function that returns nu Sigma_fg for a given r Sig_s12: name of function that returns Sigma_s12 for a given r geometry: shape of problem 0 for slab 1 for cylindrical 2 for spherical Returns: k: the multiplication factor of the system phi_fast: the fast flux fundamental mode with norm 1 phi_thermal: the thermal flux fundamental mode with norm 1 centers: position at cell centers """ #create the grid Delta_r, centers, edges = create_grid(R,I) M11 = np.zeros((I+1,I+1)) M21 = np.zeros((I+1,I+1)) M22 = np.zeros((I+1,I+1)) P11 = np.zeros((I+1,I+1)) P12 = np.zeros((I+1,I+1)) #define surface areas and volumes assert( (geometry==0) or (geometry == 1) or (geometry == 2)) if (geometry == 0): #in slab it's 1 everywhere except at the left edge S = 0.0*edges+1 S[0] = 0.0 #to enforce Refl BC #in slab its dr V = 0.0*centers + Delta_r elif (geometry == 1): #in cylinder it is 2 pi r S = 2.0*np.pi*edges #in cylinder its pi (r^2 - r^2) V = np.pi*( edges[1:(I+1)]**2 - edges[0:I]**2 ) elif (geometry == 2): #in sphere it is 4 pi r^2 S = 4.0*np.pi*edges**2 #in sphere its 4/3 pi (r^3 - r^3) V = 4.0/3.0*np.pi*( edges[1:(I+1)]**3 - edges[0:I]**3 ) #Set up BC at R M11[I,I] = 1.0 M11[I,I-1] = 1.0 M22[I,I] = 1.0 M22[I,I-1] = 1.0 #fill in rest of matrix for i in range(I): r = centers[i] M11[i,i] = (0.5/(Delta_r * V[i])*((D1(r)+D1(r+Delta_r))*S[i+1]) + Sig_r1(r)) M22[i,i] = (0.5/(Delta_r * V[i])*((D2(r)+D2(r+Delta_r))*S[i+1]) + Sig_r2(r)) M21[i,i] = -Sig_s12(r) P11[i,i] = nu_Sigf1(r) P12[i,i] = nu_Sigf2(r) if (i>0): M11[i,i-1] = -0.5*(D1(r)+D1(r-Delta_r))/(Delta_r * V[i])*S[i] M11[i,i] += 0.5/(Delta_r * V[i])*((D1(r)+D1(r-Delta_r))*S[i]) M22[i,i-1] = -0.5*(D2(r)+D2(r-Delta_r))/(Delta_r * V[i])*S[i] M22[i,i] += 0.5/(Delta_r * V[i])*((D2(r)+D2(r-Delta_r))*S[i]) M11[i,i+1] = -0.5*(D1(r)+D1(r+Delta_r))/(Delta_r * V[i])*S[i+1] M22[i,i+1] = -0.5*(D2(r)+D2(r+Delta_r))/(Delta_r * V[i])*S[i+1] #find eigenvalue l,phi1,phi2 = inversePowerBlock(M11,M21,M22,P11,P12,epsilon) k = 1.0/l #remove last element of phi because it is outside the domain phi1 = phi1[0:I] phi2 = phi2[0:I] return k, phi1, phi2, centers def hide_spines(intx=False,inty=False): """Hides the top and rightmost axis spines from view for all active figures and their respective axes.""" # Retrieve a list of all current figures. figures = [x for x in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()] if (plt.gca().get_legend()): plt.setp(plt.gca().get_legend().get_texts(), fontproperties=font) for figure in figures: # Get all Axis instances related to the figure. for ax in figure.canvas.figure.get_axes(): # Disable spines. ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') # Disable ticks. ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # ax.xaxis.set_major_formatter(mtick.FuncFormatter(lambda v,_: ("10$^{%d}$" % math.log(v,10)) )) for label in ax.get_xticklabels() : label.set_fontproperties(font) for label in ax.get_yticklabels() : label.set_fontproperties(font) #ax.set_xticklabels(ax.get_xticks(), fontproperties = font) ax.set_xlabel(ax.get_xlabel(), fontproperties = font) ax.set_ylabel(ax.get_ylabel(), fontproperties = font) ax.set_title(ax.get_title(), fontproperties = font) if (inty): ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%d')) if (intx): ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%d')) def show(nm,a=0,b=0): hide_spines(a,b) #ax.xaxis.set_major_formatter(mtick.FuncFormatter(lambda v,_: ("10$^{%d}$" % math.log(v,10)) )) #plt.yticks([1,1e-2,1e-4,1e-6,1e-8,1e-10,1e-12], labels) #ax.yaxis.set_major_formatter(mtick.FuncFormatter(lambda v,_: ("10$^{%d}$" % math.log(v,10)) )) plt.savefig(nm); plt.show()
164103ed6953c6845460c00331bf2d4ead7dd9d9
8jdetz8/ATBSwPython
/Filling in the Gaps
687
3.625
4
#! python3 #fillingInTheGaps.py-Searches a folder to find files with a given prefix #(spam1.txt, spam2.txt...) finds any gaps (spam3.txt, spam5.txt) and renames #later files to close gaps. import os, shutil, re #TODO open capitals folder folder = os.listdir('C:\\Users\hairy\AppData\Local\Programs\Python\Python37-32\ATBS Projects') folder.sort #TODO create regex to search for prefix capsAnswRegex = re.compile(r'capitalquiz_answers\d+') matches = list(filter(capsAnswRegex.match, folder)) i = 0 for file in matches: i += 1 os.rename(os.path.join('C:\\Users\hairy\AppData\Local\Programs\Python\Python37-32\ATBS Projects', file), 'capitalquiz_answers_' + str(i)) print('done')
e5117eda82ee4e5169fc7d57ae740bf013785f7d
meet1993shah/Python_practice
/powerseries.py
250
3.640625
4
import math x = float(raw_input("Enter the value of x: ")) n = term = num = 1 sum = 1.0 while n <= 100: term *= x / n sum += term n += 1 if term < 0.0001: break print "No of times = %d and Sum = %f" % (n, sum) print math.e ** x
1201ad19d5d3455dfebacdd79bd3eab807ad2759
RutyRibeiro/CursoEmVideo-Python
/Exercícios/Desafio_34.py
251
3.84375
4
# Calcula aumento de salario de acordo com a faixa de valores sal = float(input('Digite o salário:')) if sal > 1250.00: print('Novo salário: {}'.format(sal + (10 / 100) * sal)) else: print('Novo salário: {}'.format(sal + (15 / 100) * sal))
4b3f3032529adf5e177ea40dc8d0a76bb7823e0f
tfio17/Python_Basics
/Quiz_One.py
190
3.9375
4
# # #Tom Fiorelli # #Quiz 1 Exercise # # # num = int(input("Input a number: ")) if num > 10 and num < 100: print("This number is in range.") else: print("Out of range.")
a11728c812e443513ed0b8e747865ce26fe0b635
eechoo/Algorithms
/LeetCode/ValidNumber.py
2,371
4.21875
4
#!/usr/bin/python ''' Validate if a given string is numeric. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. ''' class Solution: # @param s, a string # @return a boolean def isNumber(self,s): i=0 havepoint=False havenum=False while(i<len(s) and s[i]==' '): i+=1 if(i<len(s) and (s[i]=='+' or s[i]=='-' )): i+=1 while(i<len(s) and (s[i].isdigit() or s[i]=='.' )): if(s[i]=='.'): if(havepoint == False): havepoint=True else: return False else: havenum=True i+=1 if(i<len(s) and s[i].upper()=='E' and havenum==True): i+=1 havepoint=False havenum=False if(i<len(s) and (s[i] == '+' or s[i]=='-')): i+=1 while(i<len(s) and s[i].isdigit() ): havenum=True i+=1 while(i<len(s) and s[i]==' '): i+=1 if(i < len(s) or havenum==False): return False else: return True def isNumber1(self, s): haveNum=False result=True havedot=False haveE=False havespace=False haveFlag=False for i in range(len(s)): if(s[i].isdigit()): haveNum=True if(havespace==True): result=False break elif(s[i].isalpha()): if(s[i].upper()=='E' and haveNum ): haveE=True else: result=False break elif(s[i]==' '): if(haveNum): havespace=True elif(s[i]=='.'): if(havedot==True): result=False break havedot=True elif(s[i]=='+' or s[i]=='-'): if(haveFlag==True and haveE=='False'): result=False break haveFlag=True if(haveNum==False): return False else: return result def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) def main(): ins=Solution() test(ins.isNumber("6e6.5"),False) test(ins.isNumber("e9"),False) test(ins.isNumber("5e"),False) test(ins.isNumber("1."),True) test(ins.isNumber("0e"),False) test(ins.isNumber(".1"),True) test(ins.isNumber(" "),False) test(ins.isNumber("."),False) test(ins.isNumber("0"),True) test(ins.isNumber(" 0.1 "),True) test(ins.isNumber("abc"),False) test(ins.isNumber("1 a"),False) test(ins.isNumber("2e10"),True) if __name__ == '__main__': main()
c2727d27c0810536ffca742259caf17a444651c4
GinnyGaga/PY-3
/ex20-2.py
723
3.859375
4
from sys import argv #导入脚本需要用的功能模块 script,f=argv #定义参数变量的参数名 def print_a_line(count_line,f):#定义函数名和函数参数 print (count_line,f.readline()) #f.readline()从文件中读取一 行;如果f.readline()返回一个空 字符串,则文件的结尾已经到达 #def rewind(f): # f.seek(0)##读取定义好的文件的初始位置 current_file=open(f) current_line=0 while current_line <= 2: current_line+=1 print_a_line(current_line,current_file) #current_line=1 #print_a_line(current_line,current_file) #current_line=current_line+1 #print_a_line(current_line,current_file) #current_line=current_line+1 #print_a_line(current_line,current_file)
05a308adbb6660ce6a5e0693dd1c2e2850f427cd
Divine11/InterviewBit
/Hashing/Longest_Substring_without_repeat.py
932
4.0625
4
# Given a string, # find the length of the longest substring without repeating characters. # Example: # The longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. # For "bbbbb" the longest substring is "b", with the length of 1. def lengthOfLongestSubstring(self, A): n = len(A) if n==0: return 0 if n==1: return 1 start = 0 end = 0 cur_len = 0 max_len = 0 current = 0 dic = {} while current <n: print("At starting",dic,current,start,cur_len) if A[current] not in dic: dic[A[current]] = 1 cur_len+=1 current+=1 else: del dic[A[start]] start+=1 cur_len-=1 if cur_len>max_len: max_len = cur_len print("At End",dic,current,start,cur_len) return max_len print(lengthOfLongestSubstring("","the pot is full"))
78b63d34e867db24879649bc6766e570ed6f096b
sheddy20/My-python-projects
/method.py
116
3.953125
4
# Casting In Python num1 = '45' num2 = '34' num1 = int(num1) num2 = int(num2) result = num1 * num2 print(result)
f61a9162bc6d16a35acaa2e175e8ea3097f2100d
hasanozdem1r/Find_Shortest_Distance_from_MKAD
/dir_api/yandex_api.py
4,355
3.90625
4
from dir_api.__init__ import * class YandexGeolocationApi: def __init__(self, geolocator_api_key:str="") -> None: """ __init__ is a constructor is a special member function of a class that is executed whenever we create new objects of that class :param geolocator_api_key: <str>Yandex.Maps API Geocoder API key used for HTTP request """ self._geolocator_api_key = geolocator_api_key def search_by_address(self,address:str) -> str: """ This method via Yandex Geolocation API get the information of given address in JSON format :param address: <str> address entered by user :return: request_result <str> :information for given address """ # HTTP error handling [200, 400, 403, 500, 503] First 3 items as informed in official document can be raised by API # but also 500 and 503 is common mistakes by user internet connection and server status therefore I have added. try: # Preparing HTTP request string by API_KEY and given address request_str: str="https://geocode-maps.yandex.ru/1.x/?apikey=%s&geocode=%s&format=json" %(self._geolocator_api_key,address) #temporary variable # HTTP GET request for given address request_response:models.Response=get(request_str) # The request has succeeded. if (request_response.status_code==200): # HTTP 200 --> SUCCESSFUL request_result:str=request_response.text # return format json structure : str return request_result # The server could not understand the request due to invalid syntax. The client SHOULD NOT repeat the request without modifications. except BadRequest as error: # HTTP 400 --> Bad Request error_msg: str = "Error: {}".format(error) abort(400) # The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. # Unlike 401, the client's identity is known to the server. except Forbidden as error: # HTTP 403 --> Forbidden (wrong API Key) error_msg: str = "Error: {}".format(error) abort(403) # The server has encountered a situation it doesn't know how to handle. except exceptions.ConnectionError as error: # Internal Server Error 500 error_msg:str="Error: {}".format(error) abort(500) # Any other error which is not so common except exceptions.RequestException as error: error_msg:str="Error: {}".format(error) abort(406) def get_geolocation(self,address:str) -> tuple: """ This method return geolocation from given JSON file about given address (latitude,longitude) :param address: <str> Given address information in JSON data structure :return: <tuple> address_geolocation is a latitude and longitude information of address """ # loads function used to parse a valid JSON string and convert it into python dictionary address_dict:dict=loads(address) # filter result (dict type) to receive geolocation information address_dict=address_dict["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["Point"]["pos"] # convert result to tuple address_geolocation:tuple=tuple(address_dict.split(" ")) # result in opposite order <longitude, latitude) therefore we convert this to correct order <latitude, longitude> # also api return keep information as string therefore we return it to float type --> (float(latitude), float(langitude)) address_geolocation=(float(address_geolocation[1]),float(address_geolocation[0])) # we received for given address geolocation from http_response and return # return format (latitude:float,longitude:float) : tuple return address_geolocation # here can be used while you test your code. # if you call this class from another file this part will not be executed if (__name__=="__main__"): yandex_obj : YandexGeolocationApi = YandexGeolocationApi(yandex_api_key) result_str : str = yandex_obj.search_by_address("Moscow") yandex_obj.get_geolocation(result_str) print(yandex_obj.get_geolocation(result_str))
4e04feea765f873d7d7b3194338d1dd5ef69ec07
pennli/Apache-Spark-2-for-Beginners
/Code_Chapter 7 spark machine learning/Code/Python/PythonSparkMachineLearning.py
9,037
3.65625
4
# coding: utf-8 # In[32]: print("==============Regression Use case==============") # In[33]: from pyspark.ml.linalg import Vectors from pyspark.ml.regression import LinearRegression from pyspark.ml.param import Param, Params from pyspark.sql import Row # In[34]: # TODO - Change this directory to the right location where the data is stored dataDir = "/Users/RajT/Downloads/wine-quality/" # In[35]: # Create the the RDD by reading the wine data from the disk lines = sc.textFile(dataDir + "winequality-red.csv") splitLines = lines.map(lambda l: l.split(";")) # Vector is a data type with 0 based indices and double-typed values. In that there are two types namely dense and sparse. # A dense vector is backed by a double array representing its entry values, # A sparse vector is backed by two parallel arrays: indices and values wineDataRDD = splitLines.map(lambda p: (float(p[11]), Vectors.dense([float(p[0]), float(p[1]), float(p[2]), float(p[3]), float(p[4]), float(p[5]), float(p[6]), float(p[7]), float(p[8]), float(p[9]), float(p[10])]))) # In[36]: # Create the data frame containing the training data having two columns. 1) The actula output or label of the data 2) The vector containing the features trainingDF = spark.createDataFrame(wineDataRDD, ['label', 'features']) trainingDF.show() # Create the object of the algorithm which is the Linear Regression with the parameters # Linear regression parameter to make lr.fit() use at most 10 iterations lr = LinearRegression(maxIter=10) # Create a trained model by fitting the parameters using the training data model = lr.fit(trainingDF) # In[37]: # Once the model is prepared, to test the model, prepare the test data containing the labels and feature vectors testDF = spark.createDataFrame([ (5.0, Vectors.dense([7.4, 0.7, 0.0, 1.9, 0.076, 25.0, 67.0, 0.9968, 3.2, 0.68,9.8])), (5.0, Vectors.dense([7.8, 0.88, 0.0, 2.6, 0.098, 11.0, 34.0, 0.9978, 3.51, 0.56, 9.4])), (7.0, Vectors.dense([7.3, 0.65, 0.0, 1.2, 0.065, 15.0, 18.0, 0.9968, 3.36, 0.57, 9.5]))], ["label", "features"]) testDF.createOrReplaceTempView("test") testDF.show() # In[38]: # Do the transformation of the test data using the model and predict the output values or lables. This is to compare the predicted value and the actual label value testTransform = model.transform(testDF) tested = testTransform.select("features", "label", "prediction") tested.show() # In[39]: # Prepare a data set without the output/lables to predict the output using the trained model predictDF = spark.sql("SELECT features FROM test") predictDF.show() # In[40]: # Do the transformation with the predict data set and display the predictions predictTransform = model.transform(predictDF) predicted = predictTransform.select("features", "prediction") predicted.show() # In[41]: print("==============Classification Use case==============") # In[42]: from pyspark.ml.linalg import Vectors from pyspark.ml.classification import LogisticRegression from pyspark.ml.param import Param, Params from pyspark.sql import Row # In[43]: # TODO - Change this directory to the right location where the data is stored dataDir = "/Users/RajT/Downloads/wine-quality/" # In[44]: # Create the the RDD by reading the wine data from the disk lines = sc.textFile(dataDir + "winequality-white.csv") splitLines = lines.map(lambda l: l.split(";")) wineDataRDD = splitLines.map(lambda p: (float(0) if (float(p[11]) < 7) else float(1), Vectors.dense([float(p[0]), float(p[1]), float(p[2]), float(p[3]), float(p[4]), float(p[5]), float(p[6]), float(p[7]), float(p[8]), float(p[9]), float(p[10])]))) # In[45]: # Create the data frame containing the training data having two columns. 1) The actula output or label of the data 2) The vector containing the features trainingDF = spark.createDataFrame(wineDataRDD, ['label', 'features']) # Create the object of the algorithm which is the Logistic Regression with the parameters # LogisticRegression parameter to make lr.fit() use at most 10 iterations and the regularization parameter. # When a higher degree polynomial used by the algorithm to fit a set of points in a linear regression model, to prevent overfitting, regularization is used and this parameter is just for that lr = LogisticRegression(maxIter=10, regParam=0.01) # Create a trained model by fitting the parameters using the training data model = lr.fit(trainingDF) trainingDF.show() # In[46]: # Once the model is prepared, to test the model, prepare the test data containing the labels and feature vectors testDF = spark.createDataFrame([ (1.0, Vectors.dense([6.1,0.32,0.24,1.5,0.036,43,140,0.9894,3.36,0.64,10.7])), (0.0, Vectors.dense([5.2,0.44,0.04,1.4,0.036,38,124,0.9898,3.29,0.42,12.4])), (0.0, Vectors.dense([7.2,0.32,0.47,5.1,0.044,19,65,0.9951,3.38,0.36,9])), (0.0, Vectors.dense([6.4,0.595,0.14,5.2,0.058,15,97,0.991,3.03,0.41,12.6]))], ["label", "features"]) testDF.createOrReplaceTempView("test") testDF.show() # In[47]: # Do the transformation of the test data using the model and predict the output values or lables. This is to compare the predicted value and the actual label value testTransform = model.transform(testDF) tested = testTransform.select("features", "label", "prediction") tested.show() # In[48]: # Prepare a data set without the output/lables to predict the output using the trained model predictDF = spark.sql("SELECT features FROM test") # Do the transformation with the predict data set and display the predictions predictTransform = model.transform(predictDF) predicted = testTransform.select("features", "prediction") predicted.show() # In[49]: print("==============Spam Filtering Use case==============") # In[50]: from pyspark.ml import Pipeline from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import HashingTF, Tokenizer from pyspark.sql import Row # In[51]: # Prepare training documents from a list of messages from emails used to filter them as spam or not spam # If the original message is a spam then the label is 1 and if the message is genuine then the label is 0 LabeledDocument = Row("email", "message", "label") training = spark.createDataFrame([ ("you@example.com", "hope you are well", 0.0), ("raj@example.com", "nice to hear from you", 0.0), ("thomas@example.com", "happy holidays", 0.0), ("mark@example.com", "see you tomorrow", 0.0), ("xyz@example.com", "save money", 1.0), ("top10@example.com", "low interest rate", 1.0), ("marketing@example.com", "cheap loan", 1.0)], ["email", "message", "label"]) # In[52]: training.show() # In[53]: # Configure an Spark machin learning pipeline, consisting of three stages: tokenizer, hashingTF, and lr. tokenizer = Tokenizer(inputCol="message", outputCol="words") hashingTF = HashingTF(inputCol="words", outputCol="features") # LogisticRegression parameter to make lr.fit() use at most 10 iterations and the regularization parameter. # When a higher degree polynomial used by the algorithm to fit a set of points in a linear regression model, to prevent overfitting, regularization is used and this parameter is just for that lr = LogisticRegression(maxIter=10, regParam=0.01) pipeline = Pipeline(stages=[tokenizer, hashingTF, lr]) # Fit the pipeline to train the model to study the messages model = pipeline.fit(training) # In[54]: # Prepare messages for prediction, which are not categorized and leaving upto the algorithm to predict test = spark.createDataFrame([ ("you@example.com", "how are you"), ("jain@example.com", "hope doing well"), ("caren@example.com", "want some money"), ("zhou@example.com", "secure loan"), ("ted@example.com","need loan")], ["email", "message"]) test.show() # In[55]: # Make predictions on the new messages prediction = model.transform(test).select("email", "message", "prediction") prediction.show() # In[56]: print("==============Finding Synonyms==============") # In[57]: from pyspark.ml.feature import Word2Vec from pyspark.ml.feature import RegexTokenizer from pyspark.sql import Row # In[58]: # TODO - Change this directory to the right location where the data is stored dataDir = "/Users/RajT/Downloads/20_newsgroups/*" # Read the entire text into a DataFrame textRDD = sc.wholeTextFiles(dataDir).map(lambda recs: Row(sentence=recs[1])) textDF = spark.createDataFrame(textRDD) # In[59]: # Tokenize the sentences to words regexTokenizer = RegexTokenizer(inputCol="sentence", outputCol="words", gaps=False, pattern="\\w+") tokenizedDF = regexTokenizer.transform(textDF) # In[60]: # Prepare the Estimator # It sets the vector size, and the parameter minCount sets the minimum number of times a token must appear to be included in the word2vec model's vocabulary. word2Vec = Word2Vec(vectorSize=3, minCount=0, inputCol="words", outputCol="result") # Train the model model = word2Vec.fit(tokenizedDF) # In[61]: # Find 10 synonyms of a given word synonyms1 = model.findSynonyms("gun", 10) synonyms1.show() # In[62]: # Find 10 synonyms of a different word synonyms2 = model.findSynonyms("crime", 10) synonyms2.show() # In[ ]:
c89f69423cda1bb0901ed4ba74a17fecf78515fe
andrewDeacy/CSVtoJavascriptArray
/main.py
1,352
3.5625
4
__author__ = 'Andrew' #quick tool to create a functional javascript array from a raw csv file format import csv import sys isValid = 0 columns = [] while isValid < 1: try: number = input('Enter the amount of columns in the array: ') if int(number) > 0: for num in range(0,int(number)): name = input('Enter the name for each column: ') columns.append(name) isValid = 2 else: isValid = 0 except: print ('Error enter a valid number please...') isValid = 0 length = int(len(columns)) while isValid < 1: csvfile = open('data.csv', 'rt') reader = csv.reader(csvfile) for row in reader: print('{', end="") #need to find out if row is a int or string to determine if i need quotes for num in range(0, length): if isinstance(row[num], float): if (num) == (length -1): print (columns[num] + ": " + row[num], end="") else: print (columns[num] + ": " + row[num], end="") else: if (num) == (length -1): print (columns[num] + ": " "'" + row[num] + "'", end="") else: print (columns[num] + ": " "'" + row[num] + "',", end="") print('}')
ea23e6cf67beafdc74f170326f49b52d4eabc2eb
E-voldykov/Python_Base
/Lesson2/base_les2_4.py
721
3.671875
4
""" Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. """ print("-" * 70) input_list = input(f'Введите строку из нескольких значений, разделив их пробелом!\n').split() print("-" * 70) count = 0 for i in input_list: count += 1 if len(i) > 10: print(f'{count}. - {i[:11]}') else: print(f'{count}. - {i}') print("-" * 70)
6a91f6d98d25223eb7f76ccb3053f33048e504be
DPGoertzen/PythonExercises
/FunctionPractice.py
3,074
4.28125
4
#Practicing functions in Python # Write your square_root function here: def square_root(num): return num**.5 # Uncomment these function calls to test your square_root function: #print(square_root(16)) # should print 4 #print(square_root(100)) # should print 10 # Write your introduction function here: def introduction(first_name, last_name): intro_string = last_name + ", " + first_name + " " + last_name return intro_string # Uncomment these function calls to test your introduction function: #print(introduction("James", "Bond")) # should print Bond, James Bond #print(introduction("Maya", "Angelou")) # should print Angelou, Maya Angelou # Write your tip function here (essentially how much should you tip given a # total and percentage to tip) def tip(total, percentage): return (total * (1 + percentage*.01)) - total # Uncomment these function calls to test your tip function: #print(tip(10, 25)) # should print 2.5 #print(tip(0, 100)) # should print 0.0 # Write your win_percentage function here: def win_percentage(wins, losses): total_games = wins + losses return (wins / total_games) * 100 # Uncomment these function calls to test your win_percentage function: #print(win_percentage(5, 5)) # should print 50 #print(win_percentage(10, 0)) # should print 100 # Write your first_three_multiples function here (it should print 3 lines, and return the 3rd multiple: def first_three_multiples(num): print(num) print(num * 2) print(num * 3) return num * 3 # Uncomment these function calls to test your first_three_multiples function: #first_three_multiples(10) # should print 10, 20, 30, and return 30 #first_three_multiples(0) # should print 0, 0, 0, and return 0 # Write your dog_years function here: def dog_years(name, age): dog_age = age * 7 return name + ", you are " + str(dog_age) + " years old in dog years" # Uncomment these function calls to test your dog_years function: #print(dog_years("Lola", 16)) # should print "Lola, you are 112 years old in dog years" #print(dog_years("Baby", 0)) # should print "Baby, you are 0 years old in dog years" # Write your remainder function #(The function should return the remainder of twice num1 divided by half of num2.) here: def remainder(num1, num2): return (2 * num1) % (.5 * num2) # Uncomment these function calls to test your remainder function: #print(remainder(15, 14)) # should print 2 #print(remainder(9, 6)) # should print 0 # Write your lots_of_math function here: # The function should print 4 lines. # First, the sum of a and b. # Second, d subtracted from c. # Third, the first number printed, multiplied by the second number printed. # Finally, it should return the third number printed mod a. def lots_of_math(a,b,c,d): nl = "\n" first = a + b second = c - d third = first * second print(str(first) + nl + str(second) + nl + str(third)) return third % a # Uncomment these function calls to test your lots_of_math function: #print(lots_of_math(1, 2, 3, 4)) # should print 3, -1, -3, 0 #print(lots_of_math(1, 1, 1, 1)) # should print 2, 0, 0, 0
d7a2d07902abc4d3fb0cfcf52c6e258f86c05d4e
pedroceciliocn/programa-o-1
/monitoria/prova 1/q_1_2020_1_soma_n_termos.py
1,134
3.90625
4
""" Questão 1 - 2020.1 - Faça um programa Python para calcular a soma dos N primeiros termos da série abaixo, onde o valor de N deve ser informado pelo usuário no início. O seu programa deve imprimir o resultado (com 4 casas decimais) da seguinte forma: “O valor da série com ... termos é ...”. S = 19 / 1 – 70 / 5 + 25 / 2 – 85 / 12 + 31 / 4 – 100 / 19 + 37 / 8 ... """ N = int(input("Dê o número N de termos: ")) while N <= 0: N = int(input("Dê o número N de termos (maior que 0): ")) numerador_par = 19 numerador_impar = 70 denominador_par = 1 denominador_impar = 5 S = 0 print("S = ", end = "") for i in range(N): if i % 2 == 0: S += numerador_par/denominador_par print(f"+{numerador_par}/{denominador_par} ", end = "") # para meios de checagem numerador_par += 6 denominador_par *= 2 else: S -= numerador_impar/denominador_impar print(f"-{numerador_impar}/{denominador_impar} ", end = "") # para meios de checagem numerador_impar += 15 denominador_impar += 7 print(f"\nO valor da sére com {N} termos é: S = {S:.4f}")
6880e6c83281d9f527674779ac4abe170e86a6fd
gunzigun/Python-Introductory-100
/28.py
682
3.734375
4
# -*- coding: UTF-8 -*- """ 题目:有5个人坐在一起, 问第五个人多少岁?他说比第4个人大2岁。 问第4个人岁数,他说比第3个人大2岁。 问第三个人,又说比第2人大两岁。 问第2个人,说比第一个人大两岁。 最后问第一个人,他说是10岁。请问第五个人多大? 程序分析:利用递归的方法,递归分为回推和递推两个阶段。要想知道第五个人岁数,需知道第四人的岁数,依次类推, 推到第一人(10岁),再往回推。 """ nNeed = 1 def Age(n): if n == 1: return 10 return 2+Age(n-1) print "the %dth people's age: %d" % (nNeed,Age(nNeed))
baff4bea368f0f0dddbb2cf157cf9dd27ccad88d
raianmol172/data_structure_using_python
/create_stack_using_singly_linkedlist.py
1,655
4.09375
4
class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def isempty(self): if self.head is None: return True else: return False def push(self, data): if self.head is None: self.head = Node(data) else: new_node = Node(data) new_node.next = self.head self.head = new_node def pop(self): if self.isempty(): return None else: popped_node = self.head self.head = self.head.next popped_node.next = None return popped_node.data def peek(self): if self.isempty(): return None else: return self.head.data def display(self): temp = self.head if self.isempty(): return None else: while temp is not None: print(temp.data, "->", end=" ") temp = temp.next print("\n") return if __name__ == '__main__': mystack = Stack() mystack.push(10) mystack.push(20) mystack.push(30) mystack.push(40) mystack.display() print("Top element is: ", mystack.peek()) print("Removed element is ", mystack.pop()) print("Removed element is ", mystack.pop()) print("Top element is: ", mystack.peek()) mystack.display() print(mystack.isempty()) print("Removed element is ", mystack.pop()) print("Removed element is ", mystack.pop()) mystack.display() print(mystack.isempty())
d95ebab51c0a39bc91fe9e361868ca237093dc2a
shalom-pwc/challenges
/Pytho Challenges/08.Is-the-Word-Singular-or-Plural.py
238
4.09375
4
# Is-the-Word-Singular-or-Plural # ----------------------------------------------- def is_singular(text): char = text[-1] if(char == "s") : return "Plular" else: return "Singular" print(is_singular("changes")) # Plular
a445180dc494eecc44273854c43dd05a91612ef6
seeprybyrun/project_euler
/problem0044.py
1,707
3.8125
4
# Pentagonal numbers are generated by the formula, P_n=n(3n−1)/2. The first # ten pentagonal numbers are: # # 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... # # It can be seen that P_4 + P_7 = 22 + 70 = 92 = P_8. However, their # difference, 70 − 22 = 48, is not pentagonal. # # Find the pair of pentagonal numbers, P_j and P_k, for which their sum and # difference are pentagonal and D = |P_k − P_j| is minimised; what is the # value of D? import time import math def isPerfectSquare(x): sr = int(math.sqrt(x)) return x == sr**2 ##print isPerfectSquare(0) ##print isPerfectSquare(0.5) ##print isPerfectSquare(1) ##print isPerfectSquare(2) ##print isPerfectSquare(25) ##print isPerfectSquare(25.0) ##print isPerfectSquare(24.99999999) # m(3m−1) + n(3n−1) == j(3j-1) # m(3m-1) - n(3n-1) == k(3k-1) # 3m^2 - m + 3n^2 - n == 3j^2 - j # 3m^2 - m - 3n^2 + n == 3k^2 - k # y(3y-1)/2 == x # 3y^2 - y == 2x # 3y^2 - y - 2x == 0 # y == (1 \pm \sqrt{1+24x})/6 # if (1 + math.sqrt(1+24*x))/6 is integral, then x is pentagonal # equivalently, isPerfectSquare(1+24*x) and int(math.sqrt(1+24*x)) % 6 == 5 def isPentagonal(x): return isPerfectSquare(1+24*x) and int(math.sqrt(1+24*x)) % 6 == 5 ##print isPentagonal(1) ##print isPentagonal(4) ##print isPentagonal(5) ##print isPentagonal(35) ##print isPentagonal(69) ##print isPentagonal(70) t0 = time.clock() D = float('inf') for i in range(1,2200): for j in range(1,2200): x = i*(3*i-1)/2 y = j*(3*j-1)/2 if isPentagonal(x+y) and isPentagonal(abs(x-y)): print i,j,abs(x-y) D = min(D,abs(x-y)) print 'D = {0}'.format(D) print 'milliseconds elapsed: {0}'.format(1000*(time.clock()-t0))
a0c74be232bee775a9c3d27631f538299204feb7
bielabades/Bootcamp-dados-Itau
/Listas/Tuplas e Dicionarios/13.py
1,770
4.28125
4
# Faça um programa que fique pedindo uma resposta do usuário, entre 1, 2 e 3. # Se o usuário digitar 1, o programa deve cadastrar um novo usuário nos moldes # do exercício 10 e guardar esse cadastro num dicionário cuja chave será o CPF da pessoa. # Quando o usuário digitar 2, o programa deve imprimir os usuários cadastrados; e se o # usuário digitar 3, o programa deve fechar. # Exemplo do dicionário: # ‘987.654.321-00’: {‘nome’: Maria, ‘idade’: 20, ‘email’ : maria@mail.com} nome = str('') cad = {} def cadastrar(nome=''): # Variáveis choice = str(".") cabecalho = str("Cadastro de Usuarios") cabecalho2 = str("por Gabriel Abades") # Página Inicial print(10 * "=-") print(f"{cabecalho:^20}") print(f"{cabecalho2:^20}") print(10 * "=-") # Escolhas while choice not in 'ABC' or choice == "ABC": print(''' (A) NOVO CADASTRO (B) CADASTRADOS (C) FECHAR ''') choice = str(input("")).upper().strip() # Escolhas caso resposta errada if choice not in ("ABC") or choice == "ABC": print("Desculpe, não entendi...") # Cadastramento if choice == "A": inserir() cadastrar() elif choice == "B": exibir() cadastrar() def exibir(): for nome in cadastros.keys(): print("CPF: ", nome, " - Outros dados: ", cadastros[nome]) def inserir(): nome = input('Qual seu nome?') idade = input('Qual a sua idade?') email = input('Digite seu e-mail:') cpf = input('Digite seu cpf:') if cadastros.get(nome): print("Ja existe cadastrado ",nome) else: cadastros[cpf] = nome, idade, email, cpf cadastros = {} cadastrar() # if(__name__ == '__main__'): # cadastrar()
453b2442d8aa5836e7ab2650ad043b5f700b23fa
durhambn/CSCI_220_Computer_Programming
/HW 5 weightedAverage.py
1,348
3.984375
4
##Name: Brandi Durham ##weightedAverage.py ## ##problem: Calculates a persons avarage and the class average ##from a set of grades from a file ## ##Certification of Authenticity: ## I certify that this lab is entirely my own work. def weightedAverage(): #ask user for name of file of grades fileName = input("Enter name of file: ") infile = open(fileName, "r") #compute each students average and print totalAvg = 0 numOfPpl = 0 for line in infile: parts = line.split() name = parts[:2] firstLast = " ".join(name) gradeAndAvg = parts[2:] #multiply weight and grade and add each together and / by 100 weight = gradeAndAvg[::2] grades = gradeAndAvg[1::2] total = 0 totalGrades = 0 for i in range(len(weight)): #weight times average wXa = eval(weight[total]) * eval(grades[total]) total += 1 totalGrades += wXa average = totalGrades / 100 print(firstLast +"'s average: " + str(average)) totalAvg += average numOfPpl += 1 #track num of people print() #class average = total of all grades / num of people classAvg = totalAvg / numOfPpl print("Class average: ", round(classAvg,1)) #rounds the class average to one decimal place
f6235871117bb6e8e7b8ada3df87f0f24348eae2
Athulya-Unnikrishnan/DjangoProjectBasics
/LaanguageFundamentals/python_collections/set_prgms/removing_du[licates.py
272
3.703125
4
lst=[1,2,3,4,5] num=int(input("Enter a number")) st=set(lst) out=set()#to remove duplicates for s in st: op=num-s if op in lst: if(s>op): out.add((op,s)) elif(s==op): pass else: out.add((s,op)) print(out)
0229d1107dda665ddc09d4314c6b0591736a3928
bsakari/Python-Projects
/User_Defined_Functions/UserInput.py
375
3.921875
4
print("Enter Student One Name") stdt1 = str(input()) print("Enter Student Two Name") stdt2 = str(input()) print("Enter Student Three Name") stdt3 = str(input()) print("Enter Student Four Name") stdt4 = str(input()) print("Enter Student Five Name") stdt5 = str(input()) print("The Names of the Students are \n") print(stdt1+"\n"+stdt2+"\n"+stdt3+"\n"+ stdt4+"\n"+stdt5)
f5c31cee765a77815e7c861fb98f6b85952a0da9
sonyabrazell/worksheets
/shopping_cart_lab/shopping_cart.py
626
3.546875
4
class ShoppingCart: def __init__(self, products_in_cart, product, product_price): self.products_in_cart = products_in_cart self.product = product self.product_price = product_price self.products_in_cart = [] self.product = '' self.product_price = '' def add_product(self): self.products_in_cart.append print(self.products_in_cart) def cart_total(self): self.total_price = self.product * self.product_price print(self.total_price) def empty_cart(self): self.products_in_cart.remove print(self.products_in_cart)
0796014291e89a4ba311ba1831f1c8e7d1172aaa
requestriya/Python_Basics
/basic56.py
248
4.03125
4
# wap to perform an action if a condition is true # Given a variable name, if the value is 1, display the string "First day of month!" # and do nothing if the value is not equal var = 2 if var == 1: print("First day of month!") else: pass
03d4ecce4f03f8d1d607642825eaf76f33964522
ashwingarad/Core-Python
/function/Recursive.py
145
3.875
4
def fact (n): if n == 0: f = 1 else: f = n * fact(n - 1) return f print('Factorial is ', fact(5))
17bc6183f0e31592ec0b132e76d57bcb5ee7ff37
Asumji/Turn-based-game-thing
/index.py
1,473
3.640625
4
import os import random import time enemy = { "name": "Enemy", "health": 100 } player = { "health": 100, } enemyActions = ["Attack", "Heal", "Heal", "Attack", "Attack", "Attack"] playerActions = ["Attack", "Heal"] clear = lambda: os.system('cls') clear() print(enemy["name"] + " Health: " + str(enemy["health"]) + "\nYour Health: " + str(player["health"])) def playerAction(): action = input("1: " + playerActions[0] + " 2: " + playerActions[1] + "\n") if (action == "1"): enemy["health"] -= 10 elif (action == "2"): player["health"] += 15 else: print("You did not enter 1 or 2!") clear() print(enemy["name"] + " Health: " + str(enemy["health"]) + "\nYour Health: " + str(player["health"])) def enemyAction(): action = enemyActions[random.randrange(0, len(enemyActions))] clear() print(enemy["name"] + " uses " + action) time.sleep(1.5) if (action == enemyActions[0]): player["health"] -= 10 elif (action == enemyActions[1]): enemy["health"] += 15 print(enemy["name"] + " Health: " + str(enemy["health"]) + "\nYour Health: " + str(player["health"])) while enemy["health"] > 0 and player["health"] > 0: playerAction() enemyAction() else: if (enemy["health"] <= 0): clear() print("You win!") else: clear() print("You have been defeated!")
7fd6103933af7a2802e219fa3cfd05a865b67548
Oriolowo-Mustapha/Assignment
/Q7.py
131
4.09375
4
integer1 = int(input("Enter first integer: ")) integer2 = int(input("Enter second integer: ")) add = integer1 + integer2 print(add)
771e8b3ed9e7bcb33ed74279446e79c60d984802
cainingning/leetcode
/array_119.py
541
3.515625
4
class Solution: def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ pre_list = [1] if rowIndex < 0 or rowIndex > 33: return [] for i in range(1, rowIndex + 1): now_list = [1] * (i + 1) for j in range(1, len(now_list) -1): now_list[j] = pre_list[j - 1] + pre_list[j] pre_list = now_list return pre_list if __name__ == '__main__': solution = Solution() print(solution.getRow(3))
8739eed36afa03ede22057d8650f14223baa5979
YellowSpoonGang/WeeklyCode
/9-6-20/Kyles.py
881
3.96875
4
# 1.1 def unique(string): sorted(string) for i in range (len(string) - 1): if string[i] == string[i + 1]: return False return True if __name__ == "__main__": string = "abcd" if(unique(string)): print("Yes") else: print("No") #1.2 def perm(string, string2): a = sorted(string) string = "".join(a) b = sorted(string2) string2 = "".join(b) for i in range (0, len((string))): if string[i] != string2[i]: return False return True if __name__ == "__main__": string = "Yellow" string2 = "Spoon" if (perm(string, string2)): print("Yes") else: print("No") #1.3 sep_string = "%20" string = "Mr John Smith " a_string = string.split() print(sep_string.join(a_string))
4e6fd96d678dcbbc22d21963875d35cb94e615fd
DrewRitos/projects
/AssignXIV("Number_Analyzer").py
2,606
4.125
4
#_continue is the variable that determines if any while function continues or not _continue = "yes" #default is the callname I put in to any function that requires a parameter for what it will respond with if the #user inputs something that gets caught by exception handling #get and getint are input functions that do exception handling default = "I'm sorry, I didn't get that. Please try again." def getint(x,u="I'm sorry, I didn't get that. Please try again.",y="",z=""): while True: try: b = int(input(x)) except: print("I'm sorry, I didn't get that. Please try again.") else: if y != "k": if y <= b <= z: return b else: print(u) else: return b def get(x,u="I'm sorry, I didn't get that. Please try again.",y=0,z=0,c=0): while True: try: b = input(x) except: print("I'm sorry, I didn't get that. Please try again.") else: if y != 0: if b == y or z or c: return b else: print(u) else: return b #is_even returns true if x is even and false if it isn't def is_even(x): return bool(x % 2 == 0) #is_square returns true if x is a perfect square and false if it isn't def is_square(x): return bool(x**(1/2) == int(x**(1/2))) #is_prime returns true if x is a prime number and false if it isn't def is_prime(x): for p in range(2,x): if x%p == 0: return False return True #Runs number analyzer menu code print("Welcome to the Number Analyzer Code!\nYou can choose to:\n(1) analyze a single integer\n(2) examine a range of numbers\n(3) exit the program") q1 = getint("Which would you like to choose?",default,1,3) if q1 == 1: print("\nOkay, let's analyze a number.") while _continue == "yes": num = getint("\nEnter a number (1 - 100,000):",default,1,100000) if is_even(num): print(num,"is an even number.") else: print(num,"is an odd number.") if is_square(num): print(num,"is a perfect square.") else: print(num,"is not a perfect square.") if is_prime(num): print(num,"is a prime number.") else: print(num,"is not a prime number.") _continue = get("\nWould you like to analyze another number?",default,"yes","no") if q1 == 2: print("\nOkay, great! Let's take a look at a range of range of numbers.") while _continue == "yes": lo = getint("\nEnter the lower number:",default,1,100000) hi = getint("Enter the higher number:",default,lo,100000) for t in range(lo,hi+1): if is_prime(t): print(t,"is a prime number.") else: pass _continue = get("\nWould you like to analyze another number?",default,"yes","no") if q1 == 3: print("\nOkay, goodbye.")
05b78bbeadaebb0ce2a2a7ed4c7e315813ec2831
timsergor/StillPython
/301.py
1,117
3.84375
4
# 162. Find Peak Element. Medium. 42%. # A peak element is an element that is greater than its neighbors. # Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. # The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. # You may imagine that nums[-1] = nums[n] = -∞. class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ def solution(nums): print(nums) if len(nums) == 1: return 0 if len(nums) == 2: if nums[0] > nums[1]: return 0 else: return 1 if nums[len(nums) // 2] < nums[len(nums) // 2 - 1]: return solution(nums[:len(nums) // 2]) elif nums[len(nums) // 2] < nums[len(nums) // 2 + 1]: return len(nums) // 2 + 1 + solution(nums[len(nums) // 2 + 1:]) else: return len(nums) // 2 return solution(nums) # 11min.
06e09975edfc24249bbb11386c0808b3ebfb65dd
HurricaneInteractive/Python-Journey
/basics/calculator.py
1,390
4.21875
4
# imports the regular expression library import re # prints out a welcome message print("Our Magical Calculator") print("Type 'quit' to exit\n") # global functions previous = 0 run = True # Defines the main program function def perform_math(): # get the global functions, they won't be available due to function scope global run global previous equation = "" # if there hasn't been a previous equation if previous == 0: # ask the user for a input equation = input("Enter equation:") else: # otherwise, start with the previous value equation = input(str(previous)) # if the person enters 'quit' if equation == 'quit': # set run to False which will close the program print("Goodbye, human") run = False # otherwise calculate math else: # uses regular expression to get rid of dangerous charaters in user input equation = re.sub('[a-zA-z,.:()" "]', '', equation) # if there hasn't been a previous equation if previous == 0: # evaluate the result previous = eval(equation) # Otherwise else: # evaluate result of the previous result and new equation previous = eval(str(previous) + equation) # While the application is running, call the perform_math function while run: perform_math()
aada36b3769ce9e60b7f9d52ca00ff9d6c00e095
bhatiamanav/TensorFlowBasics
/graphs_tf.py
893
3.9375
4
#Graphs are created on System backend when a Tensorflow process is done. #They consist of nodes containing values and operations & edges containing results leading out of opeartion nodes #Tensorflow is primarily used for Computation graphs import tensorflow as tf var1 = tf.constant(10) var2 = tf.constant(20) var3 = var1+var2 with tf.Session() as sess: result = sess.run(var3) print(result) print(var3) print(tf.get_default_graph())#Prints the address location of the default graph created on backend for all the whole tensorflow operation done in this branch #Creates a new graph and we can print its location g = tf.Graph() #print(g) with g.as_default():#Sets the graph that we created as default graph print(g is tf.get_default_graph()) #g1=tf.get_default_graph()#Changes g1's address to that of default graph i.e overwrites g1's address at place of default graph #print(g1)
ca1374426040c822c7a70b39ea2d90e8c97a3f0e
danieltibaquira/Analisis_Numerico
/Talleres/Taller 1/Punto3.1.1.py
879
4.03125
4
#Taller 1 Punto 3.1.1 Convergencia metodos iterativos #Stiven Gonzalez Olaya #John Jairo Gonzalez Martinez #Karen Sofia Coral Godoy #Daniel Esteban Tibaquira Galindo import math import numpy from matplotlib import pyplot def res311(f,a,b,N,E): if f(a)*f(b) >= 0: print("Secant method fails.") return None a_n = a b_n = b for n in range(1,N+1): m_n = a_n - f(a_n)*(b_n - a_n)/(f(b_n) - f(a_n)) f_m_n = f(m_n) if(abs(m_n - a) < E): break if f(a_n)*f_m_n < 0: a_n = a_n b_n = m_n elif f(b_n)*f_m_n < 0: a_n = m_n b_n = b_n elif f_m_n == 0: print("Found exact solution.") return m_n, n else: print("Secant method fails.") return None return a_n - f(a_n)*(b_n - a_n)/(f(b_n) - f(a_n)) f = lambda x: math.log( x + 2 ) - math.sin( x ) res311(f, 0, -1.7, 20,1e-16)
ab07218ef7d71aff98a06a2f74c1ddf8db2c5f09
Max143/Python_programs
/List directiry.py
215
3.875
4
# list all files in a directory in python from os import listdir from os.path import isfile, join file_list = [f or f in listdir('/home/students') if isfile(join('/home/students', f))] print(files_list)
258bb59dc75e9f4208595f8437a76960efb934aa
yang529593122/python_study
/study_05/array/一位数组的动态和.py
413
3.609375
4
# 不改变原数据 def oneArr(nums): out = [] temp = 0 for i in range(len(nums)): out.append(temp + nums[i]) temp += nums[i] return out # 改变数据 def yesChange(nums): for i in range(len(nums)): if i == 0: nums[i] = nums[i] else: nums[i] += nums[i - 1] return nums print(oneArr([1, 2, 3, 4])) print(yesChange([1, 2, 3, 4]))
dd040346d45e8ac9509ea64909c7b12f96a611b4
stephen-allison/word-chains
/team_2/wordchainsdijkstra.py
3,270
3.765625
4
import sys import string import heapq # had some time to kill on a flight so thought i would see if i could # get the dojo word-chain program running using dijkstra's algorithm. # this should give the shortest chain between two given words, at the # expense of running time. # it seems quite robust - it does the seven->eight chain faster # than the original version from the dojo. # could probably be improved further by adding A* type heuristic def make_graph(n): with open('/usr/share/dict/words') as f: words = set(word.lower() for word in f.read().splitlines() if len(word) == n) print 'there are '+str(len(words))+' words of this length' graph = {} for word in words: graph[word] = Node(word,similar_words(word, words)) return graph def similar_words(word, words): sim_words = set() for i in range(len(word)): for c in string.ascii_lowercase: new_word = word[:i]+c+word[i+1:] if new_word in words and new_word != word: sim_words.add(new_word) return sim_words def walk(graph, start, end): heap = [] start_node = graph[start] if not start_node: print 'no path from '+start return [] end_node = graph[end] if not end_node: print 'no path to '+end return [] start_node.dist = 0 for n in graph.values(): heapq.heappush(heap,n) unvisited = set(graph.values()) while len(unvisited) > 0: node = heapq.heappop(heap) for n in node.neighbours: neighbour = graph[n] new_dist = 1 + node.dist if new_dist < neighbour.dist: neighbour.dist = new_dist neighbour.previous = node if n == end: break unvisited.remove(node) heap.sort() #expensive! path = [] node = graph[end] if node.dist == float('inf'): print 'no links to '+end return [] while node: path.append(node.word) print node if node.word == start: break node = node.previous path.reverse() return path class Node: def __init__(self,word,neighbours): self.word = word self.neighbours = neighbours self.dist = float('inf') self.previous = None def __lt__(self,other): return self.dist < other.dist def __le__(self,other): return self.dist <= other.dist def __eq__(self,other): return self.dist == other.dist def __ne__(self,other): return self.dist != other.dist def __ge__(self,other): return self.dist >= other.dist def __gt__(self,other): return self.dist > other.dist def __str__(self): return self.word+" ("+str(self.dist)+")" def __repr__(self): return str(self) def __hash__(self): return self.word.__hash__() def solve(start_word, end_word): assert len(start_word) == len(end_word) graph = make_graph(len(start_word)) return walk(graph, start_word, end_word) def find(start, finish): print " -> ".join(solve(start,finish)) if __name__ == "__main__": start_word, end_word = sys.argv[1:] find(start_word, end_word)
46dc6bb09e05d62ef041804d75c3c4d2b557ee59
asharkova/python_practice
/UdacityAlgorithms/lessons1-3/quickSort.py
417
4.09375
4
"""Implement quick sort in Python. Input a list. Output a sorted list.""" import random def quicksort(array): # Randomly select pivot random_element_index = random.randint(0, len(array)) pivot = array[random_element_index] # Move pivot to the end array[random_element_index] = array[-1] array[-1] = pivot return array test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14] print(quicksort(test))
c7994668fa8e1f34af08e16b0e4ee398d838d150
reyotak/Introducao-Python
/parouimpar.py
142
3.859375
4
#Par ou Impar N = int(input("Digite um numero inteiro ")) n = N / 2 if (n == int(n)): print("par") else: print("ímpar")
af15229dc6885106b5c0d6f49f557c157add5c6e
hanrick2000/LaoJi
/Leetcode/0076.todo.py
1,352
3.65625
4
76. Minimum Window Substring Basic idea: use two pointers and Counter to count all the element inside the window, use another variable to keep track how many char completed Time O(n) class Solution: """ @param source : A string @param target: A string @return: A string denote the minimum window, return "" if there is no such a string """ def minWindow(self, source , target): # write your code here target_count = collections.Counter(target) curr_count = collections.Counter() res = '' j = 0 numComp = 0 min_len = len(source) + 1 for i in range(len(source)): while j < len(source) and numComp < len(target_count): if source[j] in target_count: curr_count[source[j]] += 1 if curr_count[source[j]] == target_count[source[j]]: numComp += 1 j += 1 if numComp==len(target_count) and j - i < min_len: min_len = j - i res = source[i:j] if source[i] in target_count: curr_count[source[i]] -= 1 if curr_count[source[i]] < target_count[source[i]]: numComp -= 1 return res
b1d6d9756ee3836b775cc7921325444d9a73a521
lncyby/Di-Yi-Ci
/课件/课堂笔记/myfile/function/test6.py
441
3.546875
4
#!/usr/bin/python #coding=utf-8 #输入日期,确定是当年的多少天。 a=raw_input("Please input your date>",) #input date l=a.split('-') #把字符串形式的年月日按-分割并放在列表里。 y=int(l[0]) m=int(l[1]) d=int(l[2]) sum=0 dcount=[31,28,31,30,31,30,31,31,30,31,30,31] if (y%4==0 and y%100 !=0) or y%400==0 : dcount[1]+=1 for i in range(0,m-1): sum+=dcount[i] print "This date is the %d day!"%(sum+d)
66e05430cfd749e7e430021a114a57435c898f8d
qmnguyenw/python_py4e
/geeksforgeeks/algorithm/hard_algo/2_4.py
7,225
3.578125
4
Sum of all divisors from 1 to N | Set 2 Given a positive integer **N** , the task is to find the sum of divisors of first **N** natural numbers. **Examples:** > **Input:** N = 4 > **Output:** 15 > **Explanation:** > Sum of divisors of 1 = (1) > Sum of divisors of 2 = (1+2) > Sum of divisors of 3 = (1+3) > Sum of divisors of 4 = (1+2+4) > Hence, total sum = 1 + (1+2) + (1+3) + (1+2+4) = 15 > > **Input:** N = 5 > **Output:** 21 > **Explanation:** > Sum of divisors of 1 = (1) > Sum of divisors of 2 = (1+2) > Sum of divisors of 3 = (1+3) > Sum of divisors of 4 = (1+2+4) > Sum of divisors of 5 = (1+5) > Hence, total sum = (1) + (1+2) + (1+3) + (1+2+4) + (1+5) = 21 Recommended: Please try your approach on _**_{IDE}_**_ first, before moving on to the solution. For linear time approach, refer to Sum of all divisors from 1 to N **Approach:** To optimize the approach in the post mentioned above, we need to look for a solution with logarithmic complexity. A number **D** is added multiple times in the final answer. Let us try to observe a pattern of repetitive addition. Considering **N** = **12** :D| Number of times added| 1| 12| 2| 6| 3| 4| 5, 6| 2| 7, 8, 9, 10, 11, 12| 1 ---|--- From the above pattern, observe that every number **D** is added ( **N** / **D** ) times. Also, there are multiple D that have same (N / D). Hence, we can conclude that for a given **N** , and a particular **i** , numbers from ( **N** / ( **i** \+ **1** )) + **1** to ( **N** / **i** ) will be added **i** times. > **Illustration:** > > > 1. N = 12, i = 1 > (N/(i+1))+1 = 6+1 = 7 and (N/i) = 12 > All numbers will be 7, 8, 9, 10, 11, 12 and will be added 1 time only. > 2. N = 12, i = 2 > (N/(i+1))+1 = 4+1 = 5 and (N/i) = 6 > All numbers will be 5, 6 and will be added 2 times. > Now, assume **A** = (N / (i + 1)), **B** = (N / i) Sum of numbers from A + 1 to B = Sum of numbers from 1 to B – Sum of numbers from 1 to A Also, instead of just incrementing i each time by 1, find next i like this, i = N/(N/(i+1)) Below is the implementation of the above approach: ## C++ __ __ __ __ __ __ __ // C++ program for // the above approach #include<bits/stdc++.h> using namespace std; int mod = 1000000007; // Functions returns sum // of numbers from 1 to n int linearSum(int n) { return (n * (n + 1) / 2) % mod; } // Functions returns sum // of numbers from a+1 to b int rangeSum(int b, int a) { return (linearSum(b) - linearSum(a)) % mod; } // Function returns total // sum of divisors int totalSum(int n) { // Stores total sum int result = 0; int i = 1; // Finding numbers and //its occurence while(true) { // Sum of product of each // number and its occurence result += rangeSum(n / i, n / (i + 1)) * (i % mod) % mod; result %= mod; if (i == n) break; i = n / (n / (i + 1)); } return result; } // Driver code int main() { int N = 4; cout << totalSum(N) << endl; N = 12; cout << totalSum(N) << endl; return 0; } // This code is contributed by rutvik_56 --- __ __ ## Java __ __ __ __ __ __ __ // Java program for // the above approach class GFG{ static final int mod = 1000000007; // Functions returns sum // of numbers from 1 to n public static int linearSum(int n) { return (n * (n + 1) / 2) % mod; } // Functions returns sum // of numbers from a+1 to b public static int rangeSum(int b, int a) { return (linearSum(b) - linearSum(a)) % mod; } // Function returns total // sum of divisors public static int totalSum(int n) { // Stores total sum int result = 0; int i = 1; // Finding numbers and //its occurence while(true) { // Sum of product of each // number and its occurence result += rangeSum(n / i, n / (i + 1)) * (i % mod) % mod; result %= mod; if (i == n) break; i = n / (n / (i + 1)); } return result; } // Driver code public static void main(String[] args) { int N = 4; System.out.println(totalSum(N)); N = 12; System.out.println(totalSum(N)); } } // This code is contributed by divyeshrabadiya07 --- __ __ ## Python3 __ __ __ __ __ __ __ # Python3 program for # the above approach mod = 1000000007 # Functions returns sum # of numbers from 1 to n def linearSum(n): return n*(n + 1)//2 % mod # Functions returns sum # of numbers from a+1 to b def rangeSum(b, a): return (linearSum(b) - ( linearSum(a))) % mod # Function returns total # sum of divisors def totalSum(n): # Stores total sum result = 0 i = 1 # Finding numbers and # its occurence while True: # Sum of product of each # number and its occurence result += rangeSum( n//i, n//(i + 1)) * ( i % mod) % mod; result %= mod; if i == n: break i = n//(n//(i + 1)) return result # Driver code N= 4 print(totalSum(N)) N= 12 print(totalSum(N)) --- __ __ ## C# __ __ __ __ __ __ __ // C# program for // the above approach using System; class GFG{ static readonly int mod = 1000000007; // Functions returns sum // of numbers from 1 to n public static int linearSum(int n) { return (n * (n + 1) / 2) % mod; } // Functions returns sum // of numbers from a+1 to b public static int rangeSum(int b, int a) { return (linearSum(b) - linearSum(a)) % mod; } // Function returns total // sum of divisors public static int totalSum(int n) { // Stores total sum int result = 0; int i = 1; // Finding numbers and //its occurence while(true) { // Sum of product of each // number and its occurence result += rangeSum(n / i, n / (i + 1)) * (i % mod) % mod; result %= mod; if (i == n) break; i = n / (n / (i + 1)); } return result; } // Driver code public static void Main(String[] args) { int N = 4; Console.WriteLine(totalSum(N)); N = 12; Console.WriteLine(totalSum(N)); } } // This code is contributed by Amit Katiyar --- __ __ **Output:** 15 127 _**Time complexity:** O(log N)_ Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course** **.** My Personal Notes _arrow_drop_up_ Save
54371c4bd5de7d3ee85af78ff718eea18352f77f
wakasa-seesaa/Pyformath
/1/2.py
276
3.96875
4
#!/usr/bin/python # -*- coding: utf-8 -*- def multi_table(a,b): for i in range(1, int(b+1)): print('{0} x {1} = {2}'.format(a,i,a*i)) if __name__ == '__main__': a = input('Enter a number:') b = input('Enter a number:') multi_table(float(a), float(b))
d9f177bf406178833e1e374b3abe366cd9619fa1
NARUTOyxj/python
/pythonBase/use_property.py
735
3.578125
4
class Screen(object): """docstring for Screen""" @property def width(self): return self._width @width.setter def width(self, value): if value <= 0: raise ValueError('请输入大于0的数') #'ValueError'首字母要大写,否则出错 else: self._width = value @property def height(self): return self._height @height.setter def height(self, value): if value <= 0: raise ValueError('请输入大于0的数') else: self._height = value @property def resolution(self): return self._width * self._height screen = Screen() screen.width = 30 screen.height = 40 print('resolution =',screen.resolution) if screen.resolution == 1200: print('测试通过!') else: print('测试失败!')
844d8899b300a5bf8d7eaeffb9e3071668f49186
ArhamChouradiya/Python-Course
/27class_05.py
428
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 4 13:22:58 2019 @author: arham """ class objectcounter: num = 0 def __init__(self): objectcounter.num+=1 @staticmethod #I don't know why it is used def display(): print(objectcounter.num) a=objectcounter() q=objectcounter() s=objectcounter() d=objectcounter() objectcounter.display()
648f26f5f73a03f5ee4b2e09ce8d03d1a8654ab1
sivatoms/Python_DataStructures
/Heap_Min.py
2,991
4.03125
4
class Heap_Min: def __init__(self, items = []): self.list = [] for i in items: self.push(i) # push an item into the list def push(self, item): if self.list == [] : self.list.append(item) elif self.size(self.list) == 1: if self.list[0] > item: self.list.append(item) self.list[0], self.list[1] = self.list[1], self.list[0] else: self.list.append(item) self.build_min_heap(self.list) # Returns Min heap peek item of the tree def peek(self): if self.list == []: return return self.list[0] # remove min heap item of the tree def pop(self): # swap the peek item with the last item of the list self.list[0], self.list[self.size(self.list)] = self.list[self.size(self.list)], self.list[0] poped = self.list.pop() #print('After pop ',self.list) self.build_min_heap(self.list) return poped # building min heap tree def build_min_heap(self, arr): n = self.size(arr) for i in range(n//2, -1, -1): self.min_heapify(arr, i, n) # generate min heapify tree def min_heapify(self,arr, i, n): left = 2 * i + 1 right = 2 * i + 2 smallest = i if left <= n and arr[left] < arr[i]: smallest = left if right <= n and arr[right] < arr[smallest]: smallest = right if smallest != i: arr[i] , arr[smallest] = arr[smallest], arr[i] self.min_heapify(arr, smallest, n) # returns the tree list def print_tree(self): return self.list # heap sort method ascending order def heapsort(self): self.build_min_heap(self.list) n = self.size(self.list) arr = self.list b = [] HeapSize = self.size(arr) for i in range(n, -1, -1): arr[i], arr[0] = arr[0], arr[i] b.append(arr[i]) arr = arr[:-1] HeapSize = HeapSize - 1 self.min_heapify(arr, 0, i-1) return b # hepa sort method descending oreder def heapsort2(self): self.build_min_heap(self.list) n = self.size(self.list) arr = self.list for i in range(n, -1, -1): arr[i], arr[0] = arr[0], arr[i] self.min_heapify(arr, 0, i-1) return arr # returns the size of the list def size(self,arr): return len(arr) - 1 if __name__ == '__main__': lst = [35, 33, 42, 10, 14, 19, 27, 44, 26, 31] H = Heap_Min(lst) #for i in lst: # H.push(i) print('Min Heap tree is : ', H.print_tree()) H.push(5) print('Min Heap tree is : ', H.print_tree()) print('Peek item : ',H.peek()) print('Poped item : ', H.pop()) print('Heap sort desc : ', H.heapsort2())
dc68b01cdbe546052934170c7f224b0ee4065720
stasDomb/PythonHomeworkDombrovskyi
/Lesson6FilesDecorators/FilesTask1.py
1,624
3.75
4
# Задача-1 # Из текстового файла удалить все слова, содержащие от трех до пяти символов, # но при этом из каждой строки должно быть удалено только четное количество таких слов. with open("./file.txt") as f_in: array_of_file = [row.strip() for row in f_in] result_in_file = [] for words in array_of_file: counter_hits = 0 every_line = words.split(' ') # для каждой строки находим слова, которые нас интересуют excluded_words = list(filter(lambda x: 2 < len(x) < 6, every_line)) # узнаем сколько таких слов counter_hits = len(excluded_words) # если таких слов нечетное количество, то уменьшаем счетчик, чтобы удалить на 1 слово меньше if counter_hits % 2 != 0: counter_hits -= 1 # приступаем к удалению for word in every_line: if word in excluded_words and counter_hits > 0: every_line.remove(word) counter_hits -= 1 # добавляем к результирующему списку очередную подернизированную строку result_in_file.append(every_line) # записываем в файл with open('./file.txt', 'w') as f_out: for line in result_in_file: f_out.write(" ".join(line) + "\n")
ca208bc236899bd18acd0b6d1fe26666704ed026
tyagivipul629/python1
/iterable.py
112
3.609375
4
def iter1(obj): return iter(obj) #def next1(): #return __next__() ab=iter1([1,2,3,4,5]) for i in ab: print(i)
a6145763fd8045dff1c646182df3e007be12f751
ysoftman/test_code
/python/string_replace.py
148
4.0625
4
str1="lemon apple orange" str2 = str1.replace("apple", "---") print(str1) print(str2) print(str1.replace("zzz", "---")) # 못찾으면 변화없음
9d17df5229f8db5a2fb6148f5622995e1a2666e0
sergelemon/python_training
/task4_1.py
681
3.90625
4
'''4. В первый день спортсмен пробежал `x` километров, а затем он каждый день увеличивал пробег на 10% от предыдущего значения. По данному числу `y` определите номер дня, на который пробег спортсмена составит не менее `y` километров. Программа получает на вход числа `x` и `y` и должна вывести одно число - номер дня.''' x = int(input('x:')) y = int(input('y:')) n, s, v = 0, 0, x while s < y: n += 1 s = s + v v *= 1.1 print(n)
5f6d76714acc96bea13de17b898630687e02a275
is42-2019/-1-
/Задачи по программированию 1 семестр/№35.py
890
4.125
4
#Задача №35 из раздела Циклические алгоритмы. Обработка последовательностей и одномерных массивов #Условие:Дан одномерный массив числовых значений, насчитывающий N элементов. Поменять местами группу из M элементов, начинающихся с позиции K с группой из M элементов, начинающихся с позиции P. import random M = random.randint(1,5) K = random.randint(1,5) P = random.randint(5,10) N = random.randint(1,15) arr = [random.randint(1,100) for i in range(N)] print("N= " + str(N)) print("K= " + str(K)) print("P= " + str(P)) print("M= " + str(M)) print(arr) arr[K : M + K + 1] , arr[P : M+P+1] = arr[P : M+P+1] , arr[K : M+K+1] print(arr)
d0799f182dbb7882a4c3edea246cc86f80f4b1a5
Joe2357/Baekjoon
/Python/Code/2700/2751 - 수 정렬하기 2.py
462
3.578125
4
import sys n = int(input()) arr_1 = [] arr_2 = [] for i in range(n): temp = int(sys.stdin.readline()) if i % 2: arr_1.append(temp) else: arr_2.append(temp) arr_1.sort(reverse = True) arr_2.sort(reverse = True) try: for i in range(n): if arr_1[-1] < arr_2[-1]: print(arr_1.pop()) else: print(arr_2.pop()) except: if len(arr_1) == 0: for i in range(len(arr_2)): print(arr_2.pop()) else: for i in range(len(arr_1)): print(arr_1.pop())
3510136e936785c86cb7f843a266bc1447d73e8a
havsor/middagsplanlegger
/middagsplanlegger.py
2,238
3.65625
4
# -*- coding: utf-8 -*- """ Ukeplanlegger for middagsmat """ import random kjøttretter = open("kjøttretter.txt", encoding="utf-8") kjøtt = kjøttretter.read().splitlines() vegetarretter = open("vegetarretter.txt", encoding="utf-8") vegetar = vegetarretter.read().splitlines() fiskeretter = open("fiskeretter.txt", encoding="utf-8") fisk = fiskeretter.read().splitlines() ant_vegetar = int(input("Hvor mange vegetarmiddager ønsker du?")) ant_fisk = int(input("Hvor mange fiskemiddager ønsker du?")) def vegpop(): return vegetar.pop(random.randint(0, len(vegetar)-1)) def fipop(): return fisk.pop(random.randint(0, len(fisk)-1)) def kjøpop(): return kjøtt.pop(random.randint(0, len(kjøtt)-1)) def nytt_forslag(): ny = input("Vil du ha forslag til kjøtt, vegetar eller fisk?") gyldige_svar = ["kjøtt", "fisk", "vegetar"] if ny in gyldige_svar: if ny == "kjøtt": print(kjøpop()) elif ny == "fisk": print(fipop()) elif ny == "vegetar": print(vegpop()) while ant_vegetar + ant_fisk > 7: print() print("Oisann, dette ble vel litt for mange middager? Prøv igjen du. ") print() ant_vegetar = int(input("Hvor mange vegetarmiddager ønsker du?")) ant_fisk = int(input("Hvor mange fiskemiddager ønsker du?")) veg = [] for i in range(ant_vegetar): veg.append(vegpop()) fi = [] for i in range(ant_fisk): fi.append(fipop()) if len(veg+fi) < 7: kjø = [] for i in range(7-ant_vegetar-ant_fisk): kjø.append(kjøpop()) middager = veg + fi + kjø random.shuffle(middager) dager = ["Mandag ", "Tirsdag", "Onsdag ", "Torsdag", "Fredag ", "Lørdag ", "Søndag "] print() print("Dine middager denne uken: ") print("--------------------------") for i in range(7): print(dager[i], ": ", middager[i]) fler = "j" while fler == "j": print() fler = input("Trenger du nye forslag? (j/n) ") if fler == "j": nytt_forslag() elif fler == "n": print() input("Så bra! Da er ukens middager klare. Trykk en tast for å avslutte.")
383857bb1b8acab94cc93dd0ca664a4df5d9bae4
xyzhangaa/ltsolution
/SpiralMatrix.py
1,118
4.15625
4
###Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. ###For example, ###Given the following matrix: ###[ ### [ 1, 2, 3 ], ### [ 4, 5, 6 ], ### [ 7, 8, 9 ] ###] ###You should return [1,2,3,6,9,8,7,4,5]. #time O(m*n) #space O(1) def SpiralMatrix(matrix): if matrix == []: return [] up = 0 left = 0 right = len(matrix)-1 down = len(matrix[0])-1 direc = 0 result = [] while True: if direc == 0: for i in range(left,right+1): result.append(matrix[up][i]) up += 1 if direc == 1: for i in range(up,down+1): result.append(matrix[i][right]) right -= 1 if direc == 2: for i in range(right,left-1,-1): result.append(matrix[down][i]) down -= 1 if direc == 3: for i in range(down,up-1,-1): result.append(matrix[i][left]) left += 1 if up > down or left > right: return result direc = (direc+1)%4 if __name__ == "__main__": print Solution().spiralOrder([[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]) print Solution().spiralOrder([[2,3]])
b165e89551f6b7c7d3f4e47d0306c65060226418
Nurse-Mimi/from-cel
/2020-10-08/expressions3.py
200
3.796875
4
import re def match_num(string): text = re.compile(r"^5") if text.match(string): return True else: return False print(match_num('5-2345861')) print(match_num('6-2345861'))
d313583272aacf5f9e5337ad2bab98b7ea3bb65b
jcohen66/python-sorting
/matrix/matrix_mult_list_comprehension.py
610
3.6875
4
# x = [[12, 7,3], # [4, 5, 6], # [7, 8, 9]] # y = [[5, 8 ,1, 2], # [6, 7, 3, 0], # [4, 5, 9, 1]] x = [[0,3,5], [5,5,2]] y = [[3,4], [3,-2], [4,-2]] def dot_product(x, y): sum = 0 for i in x: for j in y: sum += i * j return sum # E x D # E cols must equal D rows if len(x[0]) != len(y): print('In an ExD matrix mult, E cols must equal D rows') exit(-1) result = [[sum(a*b for a,b in zip(x_row, y_col)) for y_col in zip(*y)] for x_row in x] for r in result: print(r) yi = y[:] xi = x[0] # print(dot_product(xi, yi)) print(yi)
82f2c18dbab3dd0bd82e206e1559d121736a75c2
ryanchang1005/ALG
/string/LeetCode 14 Longest Common Prefix.py
896
4.09375
4
""" 找出最長的前綴 Input: ['flower','flow','flight'] Output: 'fl' Input: ['dog','racecar','car'] Output: '' 思路 A=Input 先找出長度最小字串, shortest_str 回圈shortest_str: 回圈A: 如A[i]==shortest_str[i]下一圈(不寫) A[i]!=shortest_str[i]回傳shortest_str[0:i](不含i) """ def solve(A): if len(A) == 0: return '' # 先找出最短的字串 shortest_str = A[0] for it in A: if len(it) < len(shortest_str): shortest_str = it for i in range(len(shortest_str)): ch = shortest_str[i] for other in A: if other[i] != ch: return shortest_str[0:i] return '' if __name__ == '__main__': print(solve(['flower', 'flow', 'flight'])) # 'fl' print(solve(['dog', 'racecar', 'car'])) # '' print(solve(['abcd', 'abc123', 'ab987654321'])) # 'ab'
7b6b38bfb96e6375d78a71a6014f758c58517a03
perrymant/CodeWarsKataStuff
/CodeWarsKataStuff/Postfix eval.py
612
3.671875
4
def eval_postfix(text): s = list() plus = None for symbol in text: if symbol in "0123456789": s.append(int(symbol)) elif not s: if symbol == "+": plus = s.pop() + s.pop() elif symbol == "-": plus = s.pop() - s.pop() elif symbol == "*": plus = s.pop() * s.pop() elif symbol == "/": plus = s.pop() / s.pop() if plus is not None: s.append(plus) else: raise Exception("unknown value %s"%symbol) return s.pop()
7bf0e80b53cc0af7cdcbe40237ac4d9fd1647aba
rayfengleixing/learnPy
/Basic/CaiNum.py
293
3.890625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- import random s = random.randint(0,101) while True: n = int(input("Input a number between 0~100>> ")) if n > s: print("bigger") elif n < s: print("smaller") else: print("Yes it's %s"%s) break
b5eeb96eea44331f08867a296e57f66d2a8e82fd
Sunqk5665/Python_projects
/Python课余练习/lect02.汇率兑换/currency_converter_v5.0.py
1,373
3.65625
4
""" 作者:Sunqk 功能:汇率兑换 版本:2.0 日期:2019/7/30 2.0 新增功能:根据输入判断是人民币还是美元,进行相应的转换计算 3.0 新增功能:程序可以一直运行,直到用户选择退出 4.0 新增功能:将汇率兑换功能封装到函数中 5.0 新增功能: (1)使程序结构化(2)简单函数的定义 Lambda """ # def convert_currency(im,er): # """ # 汇率兑换函数 # """ # out = im * er # return out def main(): """ 主函数 """ # 汇率 USD_VS_RMB = 6.77 # 带单位的货币输入 currency_str_value = input('请输入带单位的货币金额:') unit = currency_str_value[-3:] if unit == 'CNY': exchange_rate = 1 / USD_VS_RMB elif unit == 'USD': exchange_rate = USD_VS_RMB else: exchange_rate = -1 if exchange_rate != -1: in_money = eval(currency_str_value[:-3]) # 使用lambda定义函数 convert_currency2 = lambda x: x * exchange_rate # # 调用函数 # out_money = convert_currency(in_money,exchange_rate) # 调用lambda函数 out_money = convert_currency2(in_money) print('转化后的金额;', out_money) else: print('不支持该种货币:') if __name__ == '__main__': main()
443fa5e0b58e4cb4e94fd894b2e0a0394d5485b7
greenfox-velox/attilakrupl
/break/Python CW practice/IntToEnglish.py
2,357
3.734375
4
ones = {"1":"one", "2":"two", "3":"three", "4":"four", "5":"five", "6":"six", "7":"seven", "8":"eight", "9":"nine", "0":"zero"} tenToTwenty = {"0":"ten", "1":"eleven", "2":"twelve", "3":"thirteen", "4":"fourteen", "5":"fifteen", "6":"sixteen", "7":"seventeen", "8":"eighteen", "9":"nineteen"} tens = {"2":"twenty", "3":"thirty", "4":"forty", "5":"fifty", "6":"sixty", "7":"seventy", "8":"eighty", "9":"ninety", "0":""} powers = {"3":"thousand", "6":"million", "9":"billion", "12":"trillion", "15":"quadrillion", "18":"quintillion", "21":"sextillion", "24":"septillion"} def splitEveryThird(lst): newLst = [] for i in range(int(len(lst)/3)): newLst.append(lst[i*3:i*3+3]) return newLst def numberToListOfStrings(n): lst = [] n = str(n) length = len(n) if length % 3 == 1: lst.append(n[0]) n = n[1:length] for element in splitEveryThird(n): lst.append(element) elif length % 3 == 2: lst.append(n[0:2]) n = n[2:length] for element in splitEveryThird(n): lst.append(element) else: for element in splitEveryThird(n): lst.append(element) return lst def int_to_english(n): lst = numberToListOfStrings(n) english = [] for i in range(len(lst)): if int(lst[i]) >= 100: english.append(ones[lst[i][0]]) english.append("hundred") if int(lst[i][1]) >= 2: english.append(tens[lst[i][1]]) elif int(lst[i][1]) == 1: english.append(tenToTwenty[lst[i][2]]) if int(lst[i][1]) >= 2 or int(lst[i][1]) < 1: if int(lst[i][2]) > 0: english.append(ones[lst[i][2]]) elif int(lst[i]) >= 20: english.append(tens[str(int(lst[i]))[0]]) if int(str(int(lst[i]))[1]) > 0: english.append(ones[str(int(lst[i]))[1]]) elif int(lst[i]) < 20 and int(lst[i]) >= 10: english.append(tenToTwenty[str(int(lst[i]))[1]]) elif int(lst[i]) < 10: if int(str(int(lst[i]))[0]) > 0: english.append(ones[str(int(lst[i]))[0]]) if i < len(lst)-1: english.append(powers[str((len(lst)-1-i)*3)]) english = ' '.join(english) return (english) print (int_to_english(6009042968033))
ad2f57884492307777b2f179cf35ccda0132970c
gustavogneto/app-comerciais-kivy
/funcaovariadica.py
421
3.640625
4
# exemplo de funcões variadicas def valores(*arqs): print(arqs) def listadeargumentroassociativos(**kwarqs): print(kwarqs) def argumentos(*args, **kwargs): print(args, kwargs) valores(1,2,3,4,5,6) valores("um", "dois", "tres", "quatro") listadeargumentroassociativos(a=1,b=2,c=3,d=4,e=5,f=6) listadeargumentroassociativos(um=1,dois=2,tres=3,quatro=4) argumentos(1,2,3,4,5,6,um=1,dois=2,tres=3,quatro=4)
d49d881952994de6f1e4d2d35c5dc718eb1577be
prestwich/bitcoind_mock
/bitcoind_mock/utils.py
530
3.59375
4
import random from hashlib import sha256 from binascii import unhexlify, hexlify def get_random_value_hex(nbytes): """ Returns a pseduorandom hex value of a fixed length :param nbytes: Integer number of random hex-encoded bytes to return :type nbytes: int :return: A pseduorandom hex string representing `nbytes` bytes :rtype: hex str """ pseudo_random_value = random.getrandbits(8 * nbytes) # left 0-pad, to 2*nbytes characters, lower-case hex return f"{pseudo_random_value:0{2*nbytes}x}"
67e247c190d218fbb83eee4e025219cfa5f68ace
ckdrjs96/algorithm
/programmers/level3/정수 삼각형.py
382
3.5
4
def solution(triangle): n=len(triangle) add=triangle[n-1] for row in range(n-2,-1,-1): new=[] for col in range(row+1): #현재값과 자식노드 왼쪽 오른쪽의 최댓값을 저장 new.append(triangle[row][col]+max(add[col],add[col+1])) # 하위문제를 모두 풀어 add에 저장 add=new return add[0]
836beb4ba7d7f37a8b2c1e20c9dcb33d258eb342
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3994/codes/1791_3140.py
164
3.78125
4
from numpy import* v=array(eval(input("Digite os numeros: "))) i=0 M=0 while(i<size(v)): M=(v[i])**5 M=M+ () i=i+1 M =(M/size(v))**1/5 print(round(M,2))
fbbdd32d0497eb42211024de77d9def98d5976ba
Abhinav-Kamatamu/Linux
/Python_Code/print[s] a[s]dimond.py
314
3.875
4
# -*- coding: utf-8 -*- """ Created on Sun May 27 12:35:17 2018 @author: abhinav """ numberOfLines =int(input('enter the number of lines:')) for i in range(1,numberOfLines+1): print((numberOfLines-i)*" "+(2*i-1)*"*") for j in range(1,numberOfLines): print((j)*' '+(2*(numberOfLines-j)-1)*"*") 1
64de19894bc10c102381c47aa2ae14bf601f7874
yourshadypast/FaceRecon
/face_recon.py
1,599
4
4
import face_recognition from tkinter.filedialog import askopenfilename # Load the known images image_of_person_1 = face_recognition.load_image_file(askopenfilename()) image_of_person_2 = face_recognition.load_image_file(askopenfilename()) image_of_person_3 = face_recognition.load_image_file(askopenfilename()) # Get the face encoding of each person. This can fail if no one is found in the photo. person_1_face_encoding = face_recognition.face_encodings(image_of_person_1)[0] person_2_face_encoding = face_recognition.face_encodings(image_of_person_2)[0] person_3_face_encoding = face_recognition.face_encodings(image_of_person_3)[0] # Create a list of all known face encodings known_face_encodings = [ person_1_face_encoding, person_2_face_encoding, person_3_face_encoding ] # Load the image we want to check unknown_image = face_recognition.load_image_file(askopenfilename()) # Get face encodings for any people in the picture unknown_face_encodings = face_recognition.face_encodings(unknown_image) # There might be more than one person in the photo, so we need to loop over each face we found for unknown_face_encoding in unknown_face_encodings: # Test if this unknown face encoding matches any of the three people we know results = face_recognition.compare_faces(known_face_encodings, unknown_face_encoding, tolerance=0.6) name = "Unknown" if results[0]: name = "Person 1" elif results[1]: name = "Person 2" elif results[2]: name = "Person 3" print(f"Found {name} in the photo!")
379d91797e1ce3e91782458372d34ae34ea98e91
ornichola/learning-new
/pythontutor-ru/09_2d_arrays/05_secondary_diagonal.py
1,260
3.796875
4
""" http://pythontutor.ru/lessons/2d_arrays/problems/secondary_diagonal/ Дано число n. Создайте массив размером n×n и заполните его по следующему правилу: Числа на диагонали, идущей из правого верхнего в левый нижний угол равны 1. Числа, стоящие выше этой диагонали, равны 0. Числа, стоящие ниже этой диагонали, равны 2. Полученный массив выведите на экран. Числа в строке разделяйте одним пробелом. """ n = int(input()) lst = [[0] * n for i in range(n)] _i = 0 _j = n - 1 for i in range(n): for j in range(n): if j < _j: lst[i][j] = 0 elif i == _i and j == _j: lst[i][j] = 1 _i = _i + 1 _j = _j - 1 else: lst[i][j] = 2 for line in lst: print(' '.join([str(i) for i in line])) """ a = [[0] * n for i in range(n)] for i in range(n): a[i][n - i - 1] = 1 for i in range(n): for j in range(n - i, n): a[i][j] = 2 for row in a: for elem in row: print(elem, end=' ') print() """
651993421642a921012640f31911fb7f44292aa1
matthijskrul/ThinkPython
/src/Eighteenth Chapter/Exercise4.py
638
3.890625
4
# Write a function count that returns the number of occurrences of target in a nested list: from unit_tester import test def count(target, data): tally = 0 for e in data: if e == target: tally += 1 elif type(e) == list: tally += count(target, e) return tally test(count(2, []) == 0) test(count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]) == 4) test(count(7, [[9, [7, 1, 13, 2], 8], [7, 6]]) == 2) test(count(15, [[9, [7, 1, 13, 2], 8], [2, 6]]) == 0) test(count(5, [[5, [5, [1, 5], 5], 5], [5, 6]]) == 6) test(count("a", [["this",["a",["thing","a"],"a"],"is"], ["a","easy"]]) == 4)
e447f6b38c0d004b18f70214fd3b70c268a2fa7d
manbalboy/python-another-level
/python-basic-syntax/Chapter08/03.상속.py
609
3.796875
4
# 생성자 # : 인스턴스를 만들 때 호출되는 메서드 class Monster: def __init__(self, health, attack, speed): self.health = health self.attack = attack self.speed = speed def move(self): print("이동하기") class Wolf(Monster): pass class Shark(Monster): def move(self): print("헤엄치기") class Dragon(Monster): def move(self): print("날기") wolf = Wolf(100, 20, 20) print(wolf) shark = Shark(200, 300, 440) print(shark) dragon = Dragon(20049, 299, 200) print(dragon) wolf.move() shark.move() dragon.move()
1df1bf758500f1beeb8f5f0de69e9a25e1a1265d
dbanerjee/ctci-5th-ed
/chp01_arrays_and_strings/1_3.py
689
3.84375
4
# Solution to Exercise 1.3 from Cracking the Coding Interview, 5th Edition # Nitin Punjabi # nptoronto@yahoo.com # https://github.com/nitinpunjabi # # Assumptions: # - whitespace is significant # - case-sensitive def is_permutation_sort(s1, s2): if len(s1) != len(s2): return False return sorted(s1) == sorted(s2) def is_permutation_char_freq(s1, s2): if len(s1) != len(s2): return False char_freq = {} for c in s1: if c in char_freq: char_freq[c] += 1 else: char_freq[c] = 1 for c in s2: if c in char_freq: char_freq[c] -= 1 if char_freq[c] < 0: return False else: return False return True
92d80868d8b1c1c3cb8ea48397b6103fe6801a81
redashu/shubhredhat
/file_operations.py
1,308
3.859375
4
#!/usr/bin/python2 import time # creating an empty file # file name , file mode ==(r,w,a) f=open('/tmp/myfile1.txt','w') print "file is created.." f.close() # create file and write some data f=open('/tmp/shubhdha.txt','w') #print "file is created..." #print "writing some random data .." time.sleep(2) f.write("hey guys") f.close() # writing another data ''' remember write mode always override previous data in write mode you can not read the file content ''' f=open('/tmp/shubhdha.txt','w') f.write("hello world this is me ") f.write("\n") f.write("adding more data") f.close() # now opening a file for read only f=open('/etc/hosts','r') data=f.read() print data f.close() # now read and write both in a new file f=open('/tmp/shubhdha1.txt','w+') f.write("wrrrisdfldsf") f.write('\n') # to change cursor position f.seek(0) x=f.read() print x f.close() # there is another mode called r+ --- same as w+ # r+ can not create a new file --file must be present already # w+ always create a new file first then do the rest # now time for append mode f=open('/tmp/shubhdha1.txt','a') f.write("\n") f.write("hii heros") f.seek(0) f.write("appending again ") f.close() # there is no read operation possible in a mode # use a+ to append and read both
2ea650efc17f31b2eb72c7c9b0749611525d4092
tliu57/Leetcode
/Easy/HappyNumber/test.py
379
3.609375
4
from sets import Set from math import pow class Solution(object): def isHappy(self, n): used_digit = Set([]) used_digit.add(n) while n!= 1: result = 0 while n != 0: result += int(pow(n%10, 2)) n /= 10 if result in used_digit: return False else: used_digit.add(result) n = result return True sol = Solution() n = 19 print sol.isHappy(n)
52acd89ed6598ba501d5fe3701d7860c86f18f26
stephen1776/Python-for-Biologists
/03 - Working With Files/P4B0302_writingFASTAfile.py
1,028
3.890625
4
''' Writing a FASTA file Write a program that will create a FASTA file for the following three sequences – make sure that all sequences are in uppercase and only contain the bases A, T, G and C. Sequence header DNA sequence ABC123 ATCGTACGATCGATCGATCGCTAGACGTATCG DEF456 actgatcgacgatcgatcgatcacgact HIJ789 ACTGAC-ACTGT--ACTGTA----CATGTG ''' def writeFASTA(): seq_header1 = "ABC123" seq_header2 = "DEF456" seq_header3 = "HIJ789" seq1 = "ATCGTACGATCGATCGATCGCTAGACGTATCG" seq2 = "actgatcgacgatcgatcgatcacgact" seq3 = "ACTGAC-ACTGT--ACTGTA----CATGTG" return [seq_header1, seq_header2, seq_header3, seq1, seq2.upper(), seq3.replace('-', '')] if __name__ == '__main__': with open('dna_sequences.fasta', 'w') as dsf: dsf.write('>' + writeFASTA()[0] + '\n') dsf.write(writeFASTA()[3] + '\n') dsf.write('>' + writeFASTA()[1] + '\n') dsf.write(writeFASTA()[4] + '\n') dsf.write('>' + writeFASTA()[2] + '\n') dsf.write(writeFASTA()[5] + '\n')
d91dae77fbc7e6e7700f75159b96e9dd42daa2dc
chapmanbe/BMI_6018_Final_Project
/caloriedb.py
784
4.34375
4
"""import sqlite3 to use with the sqlite database""" import sqlite3 class Database: """database object that stores the user's balance for the date""" def __init__(self): self.connection = sqlite3.connect("calorie.db") self.cursor = self.connection.cursor() def updatedb(self, bal): """insetrs data into the table""" self.cursor.execute("INSERT INTO calorie (balance) VALUES (?)", (bal,)) self.connection.commit() return def get_info(self): """gets the information from the database""" self.cursor.execute("SELECT * FROM calorie;") return self.cursor.fetchall() def close_db(self): """closes the database""" self.connection.close() return
b58ffcc6e946be821ceb77d53b7d9989335c5e6a
Yuxuan-Chan/algorithm-and-data-structure
/python/Leetcode/Leetcode_292_Nim_Game.py
651
3.828125
4
#! python3 # -*- coding: utf-8 -*- class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ return n % 4 != 0 """ 这题概述的其实有点问题, If there are 8 stones, I can pick 3 Opponent can pick 3 I can pick 2 stones . I win. So how is this solution valid. In this question, both of you and your friend are very clever and have optimal strategies for the game. So if you pick 3, the opponent will pick 2 then you will lose. 这里其实别人解释了游戏双方每次都会选择最优解,所以并不会出现上面说的你的对手故意让你赢的情况 """
5de4005b58d525f6ea6afa852134eb64582e3e36
WYWAshley/Python-100-Days
/Day080910.py
8,354
4.21875
4
# coding=utf-8 # import time # # class clock(object): # def __init__(self, hour=0, minute=0, second=0): # self._hour = hour # self._minute = minute # self._second = second # # def show(self): # print("%02d:%02d:%02d" % (self._hour, self._minute, self._second)) # # def run(self): # self._second += 1 # if self._second == 60: # self._second = 0 # self._minute += 1 # if self._minute == 60: # self._minute = 0 # self._hour += 1 # if self._hour == 24: # self._hour = 0 # # __str__方法和__init__方法类似,都是一些特殊方法,所以前后都有双下划线,它用来返回对象的字符串表达式 # 如果要把一个类的实例变成 str,就需要实现特殊方法__str__() 而不使用__str__()方法 # def __str__(self): # return '(%d:%d:%d)' % (str(self._hour), str(self._minute), str(self._second)) # c = clock(23, 59, 50) # while True: # c.show() # c.run() # time.sleep(1) # class stu(object): # @property # def birth(self): # return self._birth # @birth.setter # def birth(self, value): # self._birth = value # @property # def age(self): # return 2019-self._birth # # s = stu() # s.birth = 1996 # print(s.birth) # print(s.age) # s.birth = 1995 # print(s.age) # print(s.birth) # 在python中,它是使用字典来保存一个对象的实例属性的。这非常有用,因为它允许我们我们在运行时去设置任意的新属性。 # 但是,这对某型已知属性的类来说,它可能是一个瓶颈。因为这个字典浪费了很多内存。 # python不能在对象创建的时候直接分配一个固定量的内存来保存所有属性,因此如果你有成千上万的属性的时候,它就会消耗很多内存。 # 有一个办法可以规避这个问题,就是使用__slots__来告诉python不要使用字典,而是只给一个固定集合的属性分配空间。 # 下面是个例子感受一下:https://www.jianshu.com/p/c0e5f7addb54 # Python 3.4.3 (default, Jun 6 2015, 13:32:34) # Type "copyright", "credits" or "license" for more information. # # IPython 4.0.0 -- An enhanced Interactive Python. # ? -> Introduction and overview of IPython's features. # %quickref -> Quick reference. # help -> Python's own help system. # object? -> Details about 'object', use 'object??' for extra details. # # In [1]: import ipython_memory_usage.ipython_memory_usage as imu # # In [2]: imu.start_watching_memory() # In [2] used 0.0000 MiB RAM in 5.31s, peaked 0.00 MiB above current, total RAM usage 15.57 MiB # # In [3]: %cat slots.py # class MyClass(object): # __slots__ = ['name', 'identifier'] # def __init__(self, name, identifier): # self.name = name # self.identifier = identifier # # num = 1024*256 # x = [MyClass(1,1) for i in range(num)] # In [3] used 0.2305 MiB RAM in 0.12s, peaked 0.00 MiB above current, total RAM usage 15.80 MiB # # In [4]: from slots import * # In [4] used 9.3008 MiB RAM in 0.72s, peaked 0.00 MiB above current, total RAM usage 25.10 MiB # # In [5]: %cat noslots.py # class MyClass(object): # def __init__(self, name, identifier): # self.name = name # self.identifier = identifier # # num = 1024*256 # x = [MyClass(1,1) for i in range(num)] # In [5] used 0.1758 MiB RAM in 0.12s, peaked 0.00 MiB above current, total RAM usage 25.28 MiB # # In [6]: from noslots import * # In [6] used 22.6680 MiB RAM in 0.80s, peaked 0.00 MiB above current, total RAM usage 47.95 MiB # class Person(object): # # # 限定Person对象只能绑定_name, _age和_gender属性 # __slots__ = ('_name', '_age', '_gender') # # def __init__(self, name, age): # self._name = name # self._age = age # # @property # def name(self): # return self._name # # @property # def age(self): # return self._age # # @age.setter # def age(self, age): # self._age = age # # def play(self): # if self._age <= 16: # print('%s正在玩飞行棋.' % self._name) # else: # print('%s正在玩斗地主.' % self._name) # # # def main(): # person = Person('王大锤', 22) # person.play() # person._gender = '男' # # AttributeError: 'Person' object has no attribute '_is_gay' # person._is_gay = True # coding=gbk # import random # # # class Card(object): # """一张牌""" # # def __init__(self, suite, face): # self._suite = suite # self._face = face # # @property # def face(self): # return self._face # # @property # def suite(self): # return self._suite # # def __str__(self): # if self._face == 1: # face_str = 'A' # elif self._face == 11: # face_str = 'J' # elif self._face == 12: # face_str = 'Q' # elif self._face == 13: # face_str = 'K' # else: # face_str = str(self._face) # return '%s%s' % (self._suite, face_str) # # def __repr__(self): # return self.__str__() # # # class Poker(object): # """一副牌""" # # def __init__(self): # self._cards = [Card(suite, face) # for suite in '♠♥♣♦' # for face in range(1, 14)] # self._current = 0 # # @property # def cards(self): # return self._cards # # def shuffle(self): # """洗牌(随机乱序)""" # self._current = 0 # random.shuffle(self._cards) # # @property # def next(self): # """发牌""" # card = self._cards[self._current] # self._current += 1 # return card # # @property # def has_next(self): # """还有没有牌""" # return self._current < len(self._cards) # # # class Player(object): # """玩家""" # # def __init__(self, name): # self._name = name # self._cards_on_hand = [] # # @property # def name(self): # return self._name # # @property # def cards_on_hand(self): # return self._cards_on_hand # # def get(self, card): # """摸牌""" # self._cards_on_hand.append(card) # # def arrange(self, card_key): # """玩家整理手上的牌""" # self._cards_on_hand.sort(key=card_key) # # # # 排序规则-先根据花色再根据点数排序 # def get_key(card): # return (card.suite, card.face) # # # def main(): # p = Poker() # p.shuffle() # players = [Player('东邪'), Player('西毒'), Player('南帝'), Player('北丐')] # for _ in range(13): # for player in players: # player.get(p.next) # for player in players: # print(player.name + ':', end=' ') # player.arrange(get_key) # print(player.cards_on_hand) # # # if __name__ == '__main__': # main() import tkinter import tkinter.messagebox def main(): flag = True # 修改标签上的文字 def change_label_text(): nonlocal flag flag = not flag color, msg = ('red', 'Hello, world!')\ if flag else ('blue', 'Goodbye, world!') label.config(text=msg, fg=color) # 确认退出 def confirm_to_quit(): if tkinter.messagebox.askokcancel('温馨提示', '确定要退出吗?'): top.quit() # 创建顶层窗口 top = tkinter.Tk() # 设置窗口大小 top.geometry('240x160') # 设置窗口标题 top.title('小游戏') # 创建标签对象并添加到顶层窗口 label = tkinter.Label(top, text='Hello, world!', font='Arial -32', fg='red') label.pack(expand=1) # 创建一个装按钮的容器 panel = tkinter.Frame(top) # 创建按钮对象 指定添加到哪个容器中 通过command参数绑定事件回调函数 button1 = tkinter.Button(panel, text='修改', command=change_label_text) button1.pack(side='left') button2 = tkinter.Button(panel, text='退出', command=confirm_to_quit) button2.pack(side='right') panel.pack(side='bottom') # 开启主事件循环 tkinter.mainloop() if __name__ == '__main__': main()
d18d10a6fe1ce761b70b798e27754f497579011f
kengo-0805/pythonPractice
/day3.py
520
3.953125
4
''' # 問題3-1 x = input("1つ目の数字:") y = input("2つ目の数字:") s1 = float(x) s2 = float(y) if s2 == 0: print("0での割り算はできません") else: print("足し算:{} 引き算:{} 掛け算:{} 割り算:{}".format(s1+s2,s1-s2,s1*s2,s1/s2)) ''' # 問題3-2 text = input("文字を入力してください:") count = len(text) if count < 5: print("短い文章") elif 5 < count < 20: print("中くらいの文章") elif count < 20: print("長い文章") print(count)
6bde94d9bec059befa3ecd59964d526f9a00f7ab
suman0204/p2_201611119
/w5Main8.py
342
4.21875
4
height=input ("input user height (m) : ") weight=input ("input user weight (kg): ") print "%s" %height, "%s" %weight BMI=weight/(height*height) print "%s" %BMI if BMI<18.5: print 'Low weight' elif 18.5<= BMI <23: print 'normal weight' elif 23<= BMI <25: print 'over weight' else: print 'very over weight'
b12094f251f8e2830fe46cc7fb4c220599c17aa1
aschey/cs260
/makeintegers.py
701
4.03125
4
import sys import random if len(sys.argv) == 1: print("usage: python3 makeintegers.py count start step swaps") exit() def main(): #gets the command-line arguments count = int(sys.argv[1]) start = int(sys.argv[2]) step = int(sys.argv[3]) swaps = int(sys.argv[4]) ints = [] #generates the numbers for i in range(count): ints.append(start + i*step) #randomly swaps for i in range(0, swaps, 1): a = random.randint(0, len(ints) - 1) b = random.randint(0, len(ints) - 1) temp = ints[a] ints[a] = ints[b] ints[b] = temp #prints the newly swapped array for i in ints: print(i, end=" ") main()
353ef118306930c4d49970bc6c03b2e6369bc83f
prabhurd/DataScientistPython
/4LetterCombination.pyi
152
3.640625
4
import itertools d ={'2':['a','b','c'], '3':['d','e','f']} for combo in itertools.product(*[d[k] for k in sorted(d.keys())]): print(''.join(combo))
5dbd255635a948cdf7be350f58361066acdb7a54
av9ash/DSwithPython
/mQueue.py
715
3.765625
4
class mQueue(object): def __init__(self): self.queue = [] def enqueue(self,data): self.queue.append(data) def dequeue(self): x = self.queue[0] del self.queue[0] return x def isEmpty(self): return self.queue ==[] def peek(self): if not self.isEmpty(): return self.queue[0] def length(self): return len(self.queue) def printQ(self): print(list(self.queue)) def main(): q = mQueue() for i in range(0, 10): q.enqueue(i) q.printQ() print(q.isEmpty()) print(q.length()) print(q.peek()) print(q.dequeue()) print(q.peek()) if __name__=='__main__': main()
f4a2a3802f785b235c8b473633e7e068b840edbb
denkovarik/Machine-Learning-Library
/linearRegressionDemo.py
4,053
4.0625
4
# File: linearRegressinDemo.py # Author: Dennis Kovarik # Purpose: Run the Linear Regression model on examples # Usage: python3 linearRegressinDemo.py from ML import LinearRegression import numpy as np from sklearn.datasets import make_regression from utils import * import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d import pandas as pd # Linear Regression example with randomly generated data print("Running Linear Regression Demo") print("\tLinear Regression Example on Randomly Generated Data") X, Y = genPointsFittedToLine(np.array([-2]), 10) plotTitle = "Linear Regression Demo:\n" plotTitle += "Data Visualization for Randomly Generated Data Fitted to a Line" plotRegression(X, Y, title=plotTitle) # Create the Model model = LinearRegression() # Fit the model model.fit(X, Y) print("\t\tSquared Error: ", end="") print(model.squaredError(X,Y)) # Display regression plane plotTitle = "Regression Line Determined by Linear Regression Model for the\n" plotTitle += "Randomly Generated Data" plotRegression(X, Y, w=model.getWeights(), title=plotTitle) # Linear Regression example with the Iris Plants Databse print("\tLinear Regression Example on the Iris Plants Database") # Download and read the data df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None) # Extract the first 2 features (sepal length and pedal length) X = df.iloc[0:50, [0]].values Y = df.iloc[0:50, [1]].values plotTitle = "Linear Regression Demo:\n" plotTitle += "Data Visualization for the Septal Width and Septal Length of Iris Setosa" # Visualize the data plotRegression(X, Y, title=plotTitle, xLabel="Sepal Length", yLabel="Sepal Width") # Create the Model model = LinearRegression() # Fit the model model.fit(X, Y) print("\t\tSquared Error: ", end="") print(model.squaredError(X,Y)) # Display regression line plotTitle = "Regression Line Determined by Linear Regression Model for the\n" plotTitle += "Septal Width and Septal Length of Iris Setosa" plotRegression(X, Y, w=model.getWeights(), title=plotTitle, \ xLabel="Sepal Length", yLabel="Sepal Width") # Multiple Regression example with Randomly Generated Data print("\tMultiple Regression Example on Randomly Generated Data") # Multiple Regression example X, Y =make_regression(n_samples=200, n_features=2, n_targets=1, random_state=47) # Randomly display regression data Y = randomizeData(Y, 0.25) plotTitle = "Multiple Regression Demo:\n" plotTitle += "Data Visualization for Randomly Generated Data Fitted to a Plane" plotRegression(X, Y, title=plotTitle, xLabel="x", yLabel="y", zLabel="z") # Create the Model model = LinearRegression() # Fit the model model.fit(X, Y) print("\t\tSquared Error: ", end="") print(model.squaredError(X,Y)) # Display regression plane plotTitle = "Regression Plane Determined by Multiple Regression Model for\n" plotTitle += "Randomly Generated Data" plotRegression(X[:,:], Y, model.getWeights(), title=plotTitle, xLabel="x", \ yLabel="y", zLabel="z") # Multiple Regression example with the Iris Plants Databse print("\tMultiple Regression Example on the Iris Plants Database") # Extract the first 2 features (sepal length and pedal length) X = df.iloc[0:50, [0,2]].values Y = df.iloc[0:50, [1]].values plotTitle = "Multiple Regression Demo:\n" plotTitle += "Data Visualization for the Septal Width, Septal Length, and\n" plotTitle += "Petal Length of Iris Setosa" # Visualize the data plotRegression(X, Y, title=plotTitle, xLabel="Sepal Length", \ yLabel="Petal Length", zLabel="Sepal Width") # Create the Model model = LinearRegression() # Fit the model model.fit(X, Y) print("\t\tSquared Error: ", end="") print(model.squaredError(X,Y)) # Display regression plane plotTitle = "Regression Plane Determined by Multiple Regression Model for the\n" plotTitle += "Septal Width, Septal Length, and\n" plotTitle += "Petal Length of Iris Setosa" plotRegression(X, Y, w=model.getWeights(), title=plotTitle, \ xLabel="Sepal Length", yLabel="Petal Length", zLabel="Sepal Width")