blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
c831efd2c779d46b9959e5cc317f2a46cbfd7766
Jeremy277/exercise
/pytnon-month01/month01-class notes/day11-fb/demo03.py
843
3.875
4
''' 封装 ''' class Wife: def __init__(self, name=None, age=None): self.name = name #私有成员:以双下划线开头 # self.__age = age # self.set_age(age) self.age = age @property #拦截读取 age = property(get_age, None) def age(self): return self.__age #设置写入方法age.setter(写入方法) @age.setter#拦截写入 def age(self, value): if 20 <= value <= 25: self.__age = value else: #抛出异常 # raise ValueError('超过范围') print('超范围') #拦截对age的读写操作 # age = property(get_age, set_age) w01 = Wife('李知恩',25) #不能访问私有变量 # print(w01.name,w01.__age) # w01.set_age(25) # print(w01.get_age()) # w01.age = 25 print(w01.age) print(w01)
286d3019f532899549c55b15e4b0561e41e30ef9
grieff/dice-rolling
/dice-roll.py
1,108
4.53125
5
# Dice Rolling Simulation # Python 3.0 # Rolls a number of dice, with x sides, depending on the user input import random # ROLL FUNCTION def roll(die, sides): r = 0 # While loop based on number of dice selected while r < die: # Store the random roll to variable rolls rolls = random.randint(1, sides) # Increase r by 1 each loop r += 1 # Prints out the rolls for each die selected print("Rolled a ", rolls) # MAIN FUNCTION def main(): rolling = True # start loop while rolling: # Receive an anser to begin the program answer = input("Ready to roll? Y or N:") # If user says yes, run the program if answer.lower() == "y" # Variable for amount of die die = eval(input("Please enter the amount of dice you wish to roll")) # Variable for amount of sides sides = eval(input("Please enter the number of sides on your dice:")) else: print("Thank you for playing") # End while loop break # Call main function main()
a65720775df47fc20c736b5218a8ef5f0a9573df
tyut-zhuran/python_learn
/基础/多线程同步.py
703
4.0625
4
#同步是指定执行的顺序 import threading import time def test1(): if lock1.acquire(): print("------test1-------") time.sleep(0.5) lock2.release() def test2(): if lock2.acquire(): print("-------test2------") time.sleep(0.5) lock3.release() def test3(): if lock3.acquire(): print("--------test3--------") time.sleep(0.5) lock1.release() if __name__ == "__main__": lock1 = threading.Lock() lock2 = threading.Lock() lock2.acquire() lock3 = threading.Lock() lock3.acquire() for i in range(5): t1 = threading.Thread(target = test1) t2 = threading.Thread(target = test2) t3 = threading.Thread(target = test3) t1.start() t2.start() t3.start()
7ae5b57385892b4c6b5f525a161ec569ac1fb947
Ahmad-Hassan-03kml/Python-Practice-codes-Begginers-to-Pro
/function_referrence.py
236
3.609375
4
def func( pr1 ): print("list before eddit {}" .format(pr1)) # 20 pr1 = [1,2,3,4,5 ,6,7,7] print("list after eddit {}" .format(pr1)) # 20 #end of func pr1 = 20 func(pr1) print(pr1)# 20
efbd9906eb13bdcae7c44ce32352d8fdabd7d499
astraldawn/misc_code
/interview/worked_solutions/python_notes.py
5,080
4.0625
4
# Functionality in external library # 2D array declaration - using numpy # Code? # xrange vs range # xrange: generator like object # range: list # ( ) generator, [ ] list comprehension # The difference between == and is # ==: if the objects referred by the variables are equal # is: variables point to the same object # Shallow vs. deep copying # Shallow copy: the top layer of the object # Deep copy: the entire object # For primitives: shallow copy is equivalent to deep copy # e.g. result = [[0] * col] * row # [0] * col works fine because it is constructing shallow copies # * row does not as what it does is it creates 3 references to the same object # Binary search # The proper way # Bisect function (show them this first) # DP: memorise coin change / knapsack # Other python stuff # os.walk # hashlib (md5) # Dictionary keys and values (how the default iteration looks like) # 2D array import numpy as np row = 5 col = 5 dv = 0 a = np.empty((row, col)) a.fill(dv) b = [[dv] * col for j in xrange(row)] # xrange vs. range # always use xrange, range generates the list full list a = xrange(5) b = range(5) # Generator vs. list comprehension # Generator just comes up with a convenient object that can be iterated def first_n(n): num = 1 while num <= n: yield num num += 1 a = sum(first_n(100)) b = sum(xrange(1, 101)) c = sum([x for x in range(1, 101)]) # The difference between == and is # ==: if the objects referred by the variables are equal # is: variables point to the same object # # Immutable types: int float long complex str / bytes tuple / frozen set # Mutable types: byte array / list / set / dict # Binary search # The proper way # Bisect function (show them this first) # The proper way def binary_search_find(A, value): low = 0 high = len(A) - 1 while low <= high: mid = low + (high - low) / 2 if A[mid] == value: return mid elif A[mid] >= value: high = mid - 1 else: low = mid + 1 return -1 def binary_search_left(A, value): low = 0 high = len(A) - 1 while low <= high: mid = low + (high - low) / 2 if A[mid] >= value: # Leftmost insertion point (rightmost is >) high = mid - 1 else: low = mid + 1 return low import bisect def binary_search_find_python(A, value): high = len(A) - 1 pos = bisect.bisect_left(A, value) if pos <= high: return pos return -1 A = range(5) B = [binary_search_find(A, x) for x in range(6)] B1 = [binary_search_find_python(A, x) for x in range(6)] C = [binary_search_left(A, x) for x in range(6)] D = [bisect.bisect_left(A, x) for x in range(6)] E = [bisect.bisect_right(A, x) for x in range(6)] print A, B, B1, C, D, E # Coin change DP # 9.8 # Making change # Minimum number of coins needed def make_change1(amount, denom): min_coins = np.zeros(amount + 1) coin_used = np.zeros(amount + 1) for i in xrange(amount + 1): coin_count = i new_coin = 1 for j in [k for k in denom if k <= i]: if min_coins[i - j] + 1 < i: coin_count = min_coins[i - j] + 1 new_coin = j min_coins[i] = coin_count coin_used[i] = new_coin return min_coins[amount] # Number of ways to make change def make_change(amount, denom, index, c_map): if c_map[amount][index] > 0: return c_map[amount][index] if index >= len(denom) - 1: return 1 denom_amount = denom[index] ways = 0 # Make a smaller amount without the current coin for i in xrange(0, amount + 1, denom_amount): ways += make_change(amount - i, denom, index + 1, c_map) c_map[amount][index] = ways return ways def make_change_better(n, denom, ways): for coin in denom: for i in xrange(coin, n + 1): ways[i] += ways[i - coin] return ways[n] def make_change_test(): denom = [25, 10, 5, 1] n = 25 c_map = np.zeros((n + 1, len(denom))) # result = make_change(n, denom, 0, c_map) ways = [1] + [0] * n result = make_change_better(n, denom, ways) print result # Knapsack # os.walk # Hashing import hashlib # Using a block is important when dealing with files that may be very large BLOCKSIZE = 65536 hasher = hashlib.md5() with open('anotherfile.txt', 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) print(hasher.hexdigest()) # Dictionary keys and values A = {'a': 1, 'b': 2, 'c': 3} print A.keys() print A.values() print [x for x in A] # Default iterator through dictionary is keys print [x for x in A.iteritems()] # Iterates through the entire dictionary # Collections from collections import defaultdict A = defaultdict(list) # int can be used also A['a'].append('x') A['a'].append('5') print A # Random number generator from random import randint print randint(0, 63) # Returns random integer N such that 0 <= N <= 63
f65823f74d5d9cd00c7206198c6d7495663bbe5b
MatthewRatajczyk/Simple-Work-Automation
/AutomateMonthlyReports/Source Code/AutomateReports.py
1,995
3.53125
4
from tkinter import filedialog from tkinter import * import tkinter.simpledialog import pandas root = Tk() # initialdir is where we wrtie the file to csv_file = filedialog.askopenfilename(initialdir = "",title = "Select Disk Utilization.CSV",filetypes=[("CSV Files",".csv")]) inputData = pandas.read_csv(csv_file, skiprows=2) excel_file = filedialog.askopenfilename(initialdir = "",title = "Select The Report.XML") writeToFile = filedialog.askopenfilename(initialdir = "",title = "Where will the finsihed data be written to?") date = tkinter.simpledialog.askstring("Report Month","Type in the month that this report is for ") date = date.title() root.destroy() outputData = pandas.read_excel(excel_file, skiprows=49, skipcols=1) outputData = outputData.drop(columns=['Unnamed: 0']) outputData = outputData[:-67] outputData.columns = ['a', 'b','January','February','March','April','May','June','July','August','September','October','November','December','o'] outputDataIndex = outputData.drop(columns=[ 'b','January','February','March','April','May','June','July','August','September','October','November','December','o']) inputDataIndex = inputData.drop(columns=[ 'Disk','Size','% Used', 'Avg','Last Poll' ]) Total = 0 for Value in range(len(outputData.index)): serverValue = 0 x = (str(outputData.iloc[Value]['a'])) for index, row in inputData.iterrows(): y = row['Device'] if x.lower() == y.lower(): serverValue = serverValue + int(row[('Max')])/1000000000 print("Final value for " + str(x) + ' Max Size ' + str(serverValue)) outputData.set_value(Value, date, serverValue) #http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html writer = pandas.ExcelWriter(writeToFile, engine='xlsxwriter') outputData.to_excel(writer, sheet_name='Sheet1', header=False, index=False) writer.save() print("Where good")
67ad21b39e5518f55ea69cf85609d39b837d0c8b
johnkle/FunProgramming
/Leetcode/数组字符串/1470重新排列数组.py
457
3.59375
4
class Solution(object): def shuffle(self, nums, n): res = [0]*2*n for i in range(n): res[i*2] = nums[i] res[i*2+1] = nums[n+i] return res class Solution(object): def shuffle(self, nums, n): res = [] left = 0 right = n while left < n: res.append(nums[left]) res.append(nums[right]) left += 1 right += 1 return res
1de6112fe1b81ff461474cd5dcc513cf6d773b3f
ramdharam/python_progs
/fibonocci.py
188
4.125
4
def fibonocci(num): if num==1: return 1 elif num==0: return 0 else: return ( fibonocci(num-1) + fibonocci(num-2) ) if __name__ == "__main__": print(fibonocci(6)) #1 1 2 3 5 8
a05a301cfe2cc7e32f08ea28f326c160e06f9533
z0x010/medusa
/medusacode/python_process_demo/process_02_process.py
1,382
3.515625
4
#!/usr/bin/env python # coding:utf-8 """ In multiprocessing, processes are spawned by creating a Process object and then calling its start() method. (Process follows the API of threading.Thread) """ from multiprocessing import Process from multiprocessing import Queue, Pipe from multiprocessing import Lock, RLock, Event, Semaphore, Condition from multiprocessing import Value, Array, Manager, Pool import os import time import datetime class MyProcess(Process): def __init__(self): Process.__init__(self) def run(self): print '..........(worker start)' for n in range(5): print '[worker](pid:%s ppid:%s)' % (os.getpid(), os.getppid()), '%s' % datetime.datetime.now() time.sleep(0.5) print '..........(worker stop)' print '..........(main start)' process = MyProcess() print '[main](pid:%s ppid:%s)' % (os.getpid(), os.getppid()) process.start() process.join() print '..........(main stop)' # ..........(main start) # [main](pid:6490 ppid:536) # ..........(worker start) # [worker](pid:6491 ppid:6490) 2016-03-29 20:18:32.468724 # [worker](pid:6491 ppid:6490) 2016-03-29 20:18:32.969163 # [worker](pid:6491 ppid:6490) 2016-03-29 20:18:33.470393 # [worker](pid:6491 ppid:6490) 2016-03-29 20:18:33.970710 # [worker](pid:6491 ppid:6490) 2016-03-29 20:18:34.471355 # ..........(worker stop) # ..........(main stop)
48fa2b4c18571b78c299137416b1889b56f72f6d
iacopoff/nsgaii
/vic/plot_sa.py
7,938
3.53125
4
import networkx as nx import numpy as np import itertools import matplotlib.pyplot as plt # Load Sensitivity Analysis results as dictionary SAresults = np.load('SAresults_test.npy').item() # Get list of parameters parameters = list(SAresults['S1'].keys()) # Set min index value, for the effects to be considered significant index_significance_value = 0.01 ''' Define some general layout settings. ''' node_size_min = 15 # Max and min node size node_size_max = 30 border_size_min = 1 # Max and min node border thickness border_size_max = 8 edge_width_min = 1 # Max and min edge thickness edge_width_max = 10 edge_distance_min = 0.1 # Max and min distance of the edge from the center of the circle edge_distance_max = 0.6 # Only applicable to the curved edges ''' Set up some variables and functions that will facilitate drawing circles and moving items around. ''' # Define circle center and radius center = [0.0, 0.0] radius = 1.0 # Create an array with all angles in a circle (i.e. from 0 to 2pi) step = 0.001 radi = np.arange(0, 2 * np.pi, step) # Function to get distance between two points def distance(p1, p2): return np.sqrt(((p1 - p2) ** 2).sum()) # Function to get middle point between two points def middle(p1, p2): return (p1 + p2) / 2 # Function to get the vertex of a curve between two points def vertex(p1, p2, c): m = middle(p1, p2) curve_direction = c - m return m + curve_direction * (edge_distance_min + edge_distance_max * (1 - distance(m, c) / distance(c, p1))) # Function to get the angle of the node from the center of the circle def angle(p, c): # Get x and y distance of point from center [dx, dy] = p - c if dx == 0: # If point on vertical axis (same x as center) if dy > 0: # If point is on positive vertical axis return np.pi / 2. else: # If point is on negative vertical axis return np.pi * 3. / 2. elif dx > 0: # If point in the right quadrants if dy >= 0: # If point in the top right quadrant return np.arctan(dy / dx) else: # If point in the bottom right quadrant return 2 * np.pi + np.arctan(dy / dx) elif dx < 0: # If point in the left quadrants return np.pi + np.arctan(dy / dx) ''' First, set up graph with all parameters as nodes and draw all second order (S2) indices as edges in the network. For every S2 index, we need a Source parameter, a Target parameter, and the Weight of the line, given by the S2 index itself. ''' combs = [list(c) for c in list(itertools.combinations(parameters, 2))] Sources = list(list(zip(*combs))[0]) Targets = list(list(zip(*combs))[1]) # Sometimes computing errors produce negative Sobol indices. The following reads # in all the indices and also ensures they are between 0 and 1. Weights = [max(min(x, 1), 0) for x in [SAresults['S2'][Sources[i]][Targets[i]] for i in range(len(Sources))]] Weights = [0 if x<index_significance_value else x for x in Weights] # Set up graph G = nx.Graph() # Draw edges with appropriate weight for s, t, weight in zip(Sources, Targets, Weights): G.add_edges_from([(s, t)], w=weight) # Generate dictionary of node postions in a circular layout Pos = nx.circular_layout(G) ''' Normalize node size according to first order (S1) index. First, read in S1 indices, ensure they're between 0 and 1 and normalize them within the max and min range of node sizes. Then, normalize edge thickness according to S2. ''' # Node size first_order = [max(min(x, 1), 0) for x in [SAresults['S1'][key] for key in SAresults['S1']]] first_order = [0 if x < index_significance_value else x for x in first_order] node_size = [node_size_min * (1 + (node_size_max - node_size_min) * k / max(first_order)) for k in first_order] # Node border thickness total_order = [max(min(x, 1), 0) for x in [SAresults['ST'][key] for key in SAresults['ST']]] total_order = [0 if x < index_significance_value else x for x in total_order] border_size = [border_size_min * (1 + (border_size_max - border_size_min) * k / max(total_order)) for k in total_order] # Edge thickness edge_width = [edge_width_min * ((edge_width_max - edge_width_min) * k / max(Weights)) for k in Weights] ''' Draw network. This will draw the graph with straight lines along the edges and across the circle. ''' nx.draw_networkx_nodes(G, Pos, node_size=node_size, node_color='#98B5E2', edgecolors='#1A3F7A', linewidths=border_size) nx.draw_networkx_edges(G, Pos, width=edge_width, edge_color='#2E5591', alpha=0.7) names = nx.draw_networkx_labels(G, Pos, font_size=12, font_color='#0B2D61', font_family='sans-serif') for node, text in names.items(): position = (radius * 1.1 * np.cos(angle(Pos[node], center)), radius * 1.1 * np.sin(angle(Pos[node], center))) text.set_position(position) text.set_clip_on(False) plt.gcf().set_size_inches(9, 9) # Make figure a square plt.axis('off') ''' We can now draw the network with curved lines along the edges and across the circle. Calculate all distances between 1 node and all the others (all distances are the same since they're in a circle). We'll need this to identify the curves we'll be drawing along the perimeter (i.e. those that are next to each other). ''' min_distance = round(min([distance(Pos[list(G.nodes())[0]], Pos[n]) for n in list(G.nodes())[1:]]), 1) # Figure to generate the curved edges between two points def xy_edge(p1, p2): # Point 1, Point 2 m = middle(p1, p2) # Get middle point between the two nodes # If the middle of the two points falls very close to the center, then the # line between the two points is simply straight if distance(m, center) < 1e-6: xpr = np.linspace(p1[0], p2[0], 10) ypr = np.linspace(p1[1], p2[1], 10) # If the distance between the two points is the minimum (i.e. they are next # to each other), draw the edge along the perimeter elif distance(p1, p2) <= min_distance: # Get angles of two points p1_angle = angle(p1, center) p2_angle = angle(p2, center) # Check if the points are more than a hemisphere apart if max(p1_angle, p2_angle) - min(p1_angle, p2_angle) > np.pi: radi = np.linspace(max(p1_angle, p2_angle) - 2 * np.pi, min(p1_angle, p2_angle)) else: radi = np.linspace(min(p1_angle, p2_angle), max(p1_angle, p2_angle)) xpr = radius * np.cos(radi) + center[0] ypr = radius * np.sin(radi) + center[1] # Otherwise, draw curve (parabola) else: edge_vertex = vertex(p1, p2, center) a = distance(edge_vertex, m) / ((distance(p1, p2) / 2) ** 2) yp = np.linspace(-distance(p1, p2) / 2, distance(p1, p2) / 2, 100) xp = a * (yp ** 2) xp += distance(center, edge_vertex) theta_m = angle(middle(p1, p2), center) xpr = np.cos(theta_m) * xp - np.sin(theta_m) * yp ypr = np.sin(theta_m) * xp + np.cos(theta_m) * yp xpr += center[0] ypr += center[1] return xpr, ypr ''' Draw network. This will draw the graph with curved lines along the edges and across the circle. ''' plt.figure(figsize=(9, 9)) for i, e in enumerate(G.edges()): x, y = xy_edge(Pos[e[0]], Pos[e[1]]) plt.plot(x, y, '-', c='#2E5591', lw=edge_width[i], alpha=0.7) for i, n in enumerate(G.nodes()): plt.plot(Pos[n][0], Pos[n][1], 'o', c='#98B5E2', markersize=node_size[i] / 5, markeredgecolor='#1A3F7A', markeredgewidth=border_size[i] * 1.15) for i, text in enumerate(G.nodes()): if node_size[i] < 100: position = (radius * 1.05 * np.cos(angle(Pos[text], center)), radius * 1.05 * np.sin(angle(Pos[text], center))) else: position = (radius * 1.01 * np.cos(angle(Pos[text], center)), radius * 1.01 * np.sin(angle(Pos[text], center))) plt.annotate(text, position, fontsize=12, color='#0B2D61', family='sans-serif') plt.axis('off') plt.tight_layout() plt.show()
36ec91dc30d62a56f3d3be5cf51a4155a0324148
FUNsys/sirabasu_scraping
/course.py
3,069
3.5
4
#!/usr/bin/env python # coding: UTF-8 class Course(object): def __init__(self): self._name = '' self._thema = '' self._lecture_content = '' self._schedule = '' self._grade = '' self._textbook = '' self._note = '' self._remark = '' self._target = '' self._annual = '' self._semesta = '' self._unitnum = '' self._teachers = '' self._extra = [] @property def name(self): return self._name @name.setter def name(self, name): self._name += name @property def thema(self): return self._thema @thema.setter def thema(self, value): self._thema += value @property def lecture_content(self): return self._lecture_content @thema.setter def lecture_content(self, value): self._lecture_content += value @property def schedule(self): return self._schedule @schedule.setter def schedule(self, value): self._schedule += value @property def grade(self): return self._grade @grade.setter def grade(self, value): self._grade += value @property def textbook(self): return self._textbook @textbook.setter def textbook(self, value): self._textbook += value @property def note(self): return self._note @note.setter def note(self, value): self._note += value @property def target(self): return self._note @target.setter def target(self, value): self._note += value @property def remark(self): return self._remark @remark.setter def remark(self, value): self._remark += value @property def target(self): return self._target @target.setter def target(self, value): self._target += value @property def extra(self): return self._extra @extra.setter def extra(self, value): self._extra.append(value) @property def annual(self): return self._annual @annual.setter def annual(self, value): self._annual.append(value) @property def semesta(self): return self._semesta @semesta.setter def semesta(self, value): self._semesta.append(value) @property def unitnum(self): return self._semesta @unitnum.setter def unitnum(self, value): self._unitnum.append(value) @property def teachers(self): return self._teachers @teachers.setter def teachers(self, value): self._teachers.append(value) def parse_extra(self): for i in range(len(self._extra)): if i == 4: self._annual = self._extra[i] elif i== 5: self._semesta = self._extra[i] elif i == 6: self._unitnum = self._extra[i] elif i > 6 and self._extra[i].find('1.講義内容と目的') == -1: self._teachers += self._extra[i] def print_all(self): self.parse_extra() print 'name: ' + self._name print 'thema: ' + self._thema print '_lecture_content: '+ self._lecture_content print 'scgedule: '+ self._schedule print 'grade: '+ self._grade print 'textbook: '+ self._textbook print 'note: '+ self._note print 'remark: '+ self.remark print 'target: '+ self._target print 'thema: ' + self._thema print 'annual: '+ self._annual print 'semesta: '+ self._semesta print 'unitnum: '+ self._unitnum print 'teacher: '+ self._teachers
a4ce45add728ebcab7d09b6c85fc63c020e05f08
24apanda/python_useful
/function.py
384
3.84375
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 15 21:48:45 2016 @author: apanda88 """ ###########prime Number########## max = 10 count=0 for i in range(2,max+1): for j in range(2,i+1): if (i%j==0 and i !=j): count=1 break if(count==1): print( i,"Opposite mane paduni") else: print(i,"prime") count=0
5a1f9e48b15a36fabbea639408fd42a7a96f0bad
dusty-phillips/pyjaco
/tests/strings/zipstring.py
132
3.96875
4
s1 = "hello" s2 = "world" s3 = "abcd" s4 = zip(s1,s2,s3) for item in s4: print "----" for val in item: print val
e0a47fb4329f890a9f05f8461d49fbc828e14dee
zakir360hossain/MyProgramming
/Languages/Python/Learning/regular expression/regex1.py
572
4.46875
4
import re def main(): # 'match' matches the entire string. 'search' look for specific words or character in the string line = "I think I know it" matchResult = re.match('think ', line, re.M | re.I) if matchResult: print("Match found" + matchResult.group()) else: print("No match was found") # => output because the entire string is not just 'think' search_result = re.search('think', line, re.M | re.I) if search_result: print("Match found " + search_result.group()) else: print("Nothing found") main()
8fc6d2a8049230432ea9ddf5f7187c07d8127961
maalik-mcburrows/Week-1-Exercises
/DC Week 1/ex_8_tip_calc.py
838
4.15625
4
bill_amount = float(input("Total bill amount? ")) service_lvl = input("Level of service? Good/Bad/Fair? ").lower() # set .lower because this will return the users answer in all lower case which is essential for the code to be able to read the if statements if service_lvl == "good": tip_amount = bill_amount * 0.2 elif service_lvl == "fair": tip_amount = bill_amount * 0.15 print(tip_amount) elif service_lvl == "bad": tip_amount = bill_amount * 0.1 else: print("Indicate whether service is Good,Bad, or Fair.") check_split = float(input("Split how many ways? ")) result = bill_amount + tip_amount print("Tip amount: ${:,.2f}".format + (tip_amount)) print("Total amount: ${:,.2f}".format , (result)) amount_per_person = result / check_split print("Amount per person: ${:,.2f}".format + str(amount_per_person))
1c645965634fe542f2e047be4c8de81658d1c4ed
donRumata03/Experiments
/AstronomyProject/measurements.py
2,766
3.625
4
import json import math import numpy as np from typing import * from datetime import date, timedelta n_days = 48 initial_date = date(2020, 9, 24) """ Day index starts from zero for the first measurement day and is [0, n_days) In GoogleDocs(https://docs.google.com/spreadsheets/d/1F_DoQ4brBQePHNCiOVG615uoBIPiO2jDlzrxd8Wwrc4/): date index is `row_number - 2` """ def day_index_to_date(day_index: int): assert day_index < n_days return initial_date + timedelta(days=int(day_index)) def date_to_day_index(this_date: date): return (this_date - initial_date).days all_measured_day_indices = list(range(n_days)) all_measured_dates = [day_index_to_date(i) for i in all_measured_day_indices] ######## def process_measurement_data(data: List[Tuple[int, float]]): return [(day_index_to_date(measurement[0]), math.atan(measurement[1])) for measurement in data] def convert_data_to_day_indexes(data): return [ (date_to_day_index(i[0]), i[1]) for i in data ] def convert_data_to_dates(data): return [ (day_index_to_date(i[0]), i[1]) for i in data ] def convert_radians_to_degrees(data): return [ (i[0], math.degrees(i[1])) for i in data ] def convert_degrees_to_radians(data): return [ (i[0], math.radians(i[1])) for i in data ] # Data: ( Day index | measured tangent ) --> converted to ( Date | degree ) vova_house_h = 28.5 real_data_by_vova = process_measurement_data([ (1, vova_house_h / 75), (2, vova_house_h / 70) ]) andrew_house_height = 14. andrew_stick_height = 1.205 _raw_real_data_by_andrew = [ # Nothing for day 0 (1, andrew_house_height / (45 + 0.0)), (2, andrew_house_height / (45 + 2.3)), (6, andrew_house_height / (45 + 9.2)), (7, andrew_house_height / (45 + (8.7 * 2 + 10.4 * 1) / (2 + 1))), (8, andrew_house_height / (45 + 10.2)), # HALYAVA (20, andrew_house_height / (45 + 31.)), # BIG HALYAVA (38, andrew_stick_height / 8.65), # Little HALYAVA (47, andrew_stick_height / 17.5) ] real_data_by_andrew = process_measurement_data(_raw_real_data_by_andrew) real_data_by_sergey = process_measurement_data([ (3, math.tan(math.radians(17))), (46, math.tan(math.radians(3.4))), ]) real_data_by_nikita = process_measurement_data([ (47, math.tan(math.radians(5))), ]) all_real_data = sorted( real_data_by_vova[:] + real_data_by_andrew[:] + real_data_by_sergey[:] + real_data_by_nikita[:] ) good_real_data = sorted( real_data_by_andrew[:] + real_data_by_sergey[:] + real_data_by_nikita[:] ) def print_measurement_data(data): print( json.dumps( [(i[0].__str__(), i[1]) for i in data], indent=1 ) ) if __name__ == '__main__': print_measurement_data(all_real_data) print(_raw_real_data_by_andrew) print(day_index_to_date(0)) # real_measurement_data = [ # # ]
bace6854513e0a07c65432d186c5e8ceabb7ba85
linch433/diffi_helman
/main.py
971
3.953125
4
import random import math def is_prime(a): if a == 2: return True elif (a < 2) or ((a % 2) == 0): return False elif a > 2: for i in range(2, a): if not (a % i): return False return True def CheckIfProbablyPrime(x): return pow(2, x - 1, x) == 1 a = int(input("Write A: ")) p = int(input("Write P: ")) check_a = is_prime(a) check_p = is_prime(p) while (check_a == False) or (check_p == False): a = int(input("Enter a prime number for A: ")) p = int(input("Enter a prime number for P: ")) check_p = is_prime(a) check_q = is_prime(p) Xa = int(input("Secret number Xa: ")) Xb = int(input("Secret number Xb: ")) if 1 <= Xa <= p - 1 and 1 <= Xb <= p - 1: Ya = pow(a, Xa, p) print("Ya: ", Ya) Yb = pow(a, Xb, p) print("Yb: ", Yb) kA = pow(Yb, Xa, p) print("kA: ", kA) kB = pow(Ya, Xb, p) print("kB: ", kB) else: print("(Xa or Xb) <1 or >p-1")
5c5361fbe1ea81d405a3c2d5c61ea88ba3111e21
nikhil-shukla/GitDemo
/pythonProject/oopDemo/InheritanceDemo1.py
294
3.640625
4
#SingleLevel Heritance class Base: name="nikhil" def baseMethod(self): print("I'm in base class") class Child(Base): company="nik" def childMethod(self): print("I'm in child class") c= Child() c.childMethod() #b= Base() c.baseMethod() print(c.name,c.company)
1f48171c91e2ecf8c05cd1da446db601a87b8cb4
crato-thaissa/crato-thaissa.github.io
/python/inicio.py
2,956
4.09375
4
a = 1 + 2 print(a) # Tipos básicos a = 1 # inteiros b = 1.2 # ponto flutuante c = "c" # string d = 'Hello mundo' # string e = d[3] # "caractere" print(a,b,c,d,e) # Operadores Aritméticos: + - + / // & ** # a <op>= b ======= a = a <op> b x = 1 + 2 # soma y = 4 - 3 # subtração z = 5/2 # divisão ponto flutuante w = 5//2 # divisão inteira u = 5%2 # módulo (resto da divisão) v = 5**2 # potência (elevado a) t = 25**(1/2) # raiz (elevado a 0.5) == 25**0.5 print(x, y, z, w, u, v) # Conversão entre tipos r = int (5.0) s = float(5) f = str(r) g = float('23.9') + 2 print (r,s,f,g) # Strings msg = 'The quick brown fox jumps over the lazy dog' print(msg[0], len(msg)) s0 = msg[4:9] print ('0:', s0) s1 = msg[40:] print ('1:', s1) s2 = msg[:3] print ('2:', s2) s3 = msg[-8:] print ('3:', s3) s4 = msg[-8:-4] print ('4:', s4) s5 = msg[-1] print ('5:', s5) s6 = msg.upper() print ('6:', s6) s7 = msg.lower() print ('7:', s7) s8 = 'hello mundo'.upper() print ('8:', s8) s9 = 'hello mundo'[6:-4] print ('9:', s9) msga = "\n meu texto \t\t" print (msga.strip()) msgb = '\t\t 3;4.5;6;-7.6;cardio;XX\n'.strip() print (msgb.split(';')) print(s8 + ' ' + msga.strip()) # operador + concatena strings # Caracteres de escape: \?, onde ? é um 'comando' # \n : nova linha # \t : tab (identação) # \\ : \ # \' : ' # \" : " caracteres = '\n\t\'\\\"' print(caracteres) # Lógica Booleana q0 = False q1 = True q2 = q0 and q1 q3 = q0 or q1 q4 = not q3 # Decisão if q4 and not q3: a += 4 print ('Olá') elif not (q1 or q2): print('Eitcha') else: print ('Tchau') # Comparações print(3 > 4) print(3 >= 4) print(3 < 4) print(3 <= 4) print(3 == 4) print(3 != 4, not(3 == 4)) # Arrays / Listas li = [1,2,3,4] print (li) li = [1,'2',3.5,"jimmy".upper] print (li) # referencia na lista igual a da sting print (li[:3]) # método append insere elementos na lista li.append('novo elemento') print (li) # operador + concatena listas print (list(range(1,4)) + ['***'] + [5,6,7]) # Laço print ('Laço:') stri = '' for i in range (5): stri += str(i) + ' ' print (stri) stri = '' for i in range (6,11): stri += str(i) + ' ' print (stri) stri = '' for i in range (10, 101, 5): stri += str(i) + ' ' print (stri) li = [1,2,3,4,5,6,7,8] stri = ' ' for el in li: stri += str(el) + " " print (stri) # for (i =0; i < li.lenght; i++) { # console .log(i); } for xoxoxoxoxo in li: print (xoxoxoxoxo) for xoxoxoxoxo in range(len(li)): print (li[xoxoxoxoxo]) li = [1,2,3,4,5,6,7,8] for i, el in enumerate(li): print (i, ":", el) # Coisas chiques li0 = list (range(1,100,2)) print (li0) li1 = list (i**2 for i in li0) print (li1) li2 = list (e for e in li0 if e%3 == 0) print (li2) Matriz = list(list((i,j) for j in range(4)) for i in range(4)) for linha in Matriz: print (linha)
80e75012aa401ac7c5d504b1efefcafeefc744c5
zhuolikevin/Algorithm-Practices-Python
/Google/numberOfIsland.py
875
3.515625
4
class Solution: def numberOfIsland(self, matrix): if not matrix or not matrix[0]: return 0 count = 0 m = len(matrix) n = len(matrix[0]) for i in range(m): for j in range(n): if matrix[i][j] == 1: count += 1 stack = [(i, j)] while stack: x, y = stack.pop() if x < 0 or x >= m or y < 0 or y >= n or matrix[x][y] != 1: continue matrix[x][y] = 'x' stack.append((x-1, y)) stack.append((x+1, y)) stack.append((x, y-1)) stack.append((x, y+1)) return count solu = Solution() matrix = [[1,1,0,0,1], [1,0,0,1,1]] print solu.numberOfIsland(matrix)
298fab86703c4ade18560ef901cb048f33bde0c7
yllausac/programmers
/연습장.py
65
3.578125
4
array = ['a', 'b', 'c', 'd', 'e'] print(array[::-1]) ##내일
162fffb5977c1aab6768de347f43f8251ef9bd1e
vwinkler/LDE-Solver
/tests/TrivialEquationTests.py
684
3.5
4
import unittest from LinearDiophanticEquation import LinearDiophanticEquation from DiophanticSum import DiophanticSum class TrivialEquationTests(unittest.TestCase): def setUp(self): self.equation = LinearDiophanticEquation() self.equation.addVariable("x1", 1) self.equation.addVariable("x2", -6) self.equation.setConstant(7) def test_solveForVariableWithCoefficientOne(self): actual = self.equation.solveForVariableWithCoefficientOne("x1") expectedCoefficients = {"x2": 6} expectedConstant = 7 expected = DiophanticSum(expectedCoefficients, expectedConstant) self.assertEqual(actual, expected)
f1246ca7561ec4fb8ff2f9a05c786208ecda6c9c
Yensj/learn_python
/age.py
555
4.0625
4
#... user_age = float(input("Укажите ваш возраст: ")) if user_age < 7: print('Скорее всего вы посещаете детский сад') elif 7 <= user_age < 18: print('Скорее всего вы ходите в школу') elif 18 <= user_age < 23: print('Скорее всего вы учитесь в институте') else: print('Скорее всего вы работаете') #n_check = float.is_integer(user_age) #if n_check = 'True': # print('correct') # else: # print('wrong')
469e0f7baf4be6dcd467e3110ac922b3ca7ad5bc
da1907/AlgorithmWithPython
/withPython/Programmers/week02/올바른괄호.py
321
3.578125
4
def solution(s): for i in s: if i == '(': stack.append(i) else: if len(stack): stack.pop() else: return False if not len(stack): return True else: return False stack = [] s = list(input()) print(solution(s))
f247d4432a3d7764f3213621c3106964044713b2
fatecspmanha182/IAL-002-algoritmos_e_logica_de_programacao
/Resolução-Exercícios-Parte1/ALP_Lista1-07 (sem lista).py
476
4
4
""" Dada uma lista de números reais terminada pelo número 99.99, imprima cada número lido. No final, imprima a média aritmética de todos os números da lista (É claro que o nº 99.99 não faz parte da média). """ lista = n = cont = 0 while n != 99.99: n = float(input("Digite um elemento para lista (caso queira parar, digite \ 99.99): ")) if n != 99.99: print(n) lista += n cont += 1 print("A média aritmética é:", lista/cont,".")
49a7634a42dd5818ef238f5a76c9ac0cbdeb558d
sanvedj/MayuriC2WT
/Daily Flash/week 4/day 1/18-DailyFlash_Solutions/3_Feb_Solutions_One/Python/program5.py
214
3.859375
4
def powerOf10(under,upper): while upper!=0: under = 10*under upper = upper - 1 return under num = input("Enter the number : ") ans = (powerOf10(10,num)-(9*num)-10)/9 print(ans)
00944b1b7af980ca2de2f8323dbb14e4d5204c39
b96705008/py-lintcode-exercise
/basic/ch2/sqrt2.py
730
4.34375
4
""" Description Implement double sqrt(double x) and x >= 0. Compute and return the square root of x. Notice You do not care about the accuracy of the result, we will help you to output results. Example Given n = 2 return 1.41421356 """ from __future__ import division def sqrt(x): if x == 0.: return 0. elif x == 1.: return 1. threshold = 1e-12 # check if x > 1 (ex. 2) or < 1 (ex. 0.25) start = 1. end = x if x < 1: start = x end = 1 while end - start > threshold: mid = start + (end - start) / 2. mid_2 = mid * mid if mid_2 == x: return mid_2 elif mid_2 < x: start = mid else: end = mid return (start + end) / 2 print sqrt(4.) print sqrt(2.) print sqrt(0.25) print sqrt(0.5)
f817e534466fa3338ac319d44fd7d17467f0e7f3
jkfer/LeetCode
/Accounts_Merge.py
1,714
3.859375
4
# https://leetcode.com/problems/accounts-merge/ # 721 # Medium - Failed """ Refered solution: Must spend more time to understand DFS solution. """ import collections class Solution: def accountsMerge(self, accounts): email_to_name = {} graph = collections.defaultdict(set) for acc in accounts: name = acc[0] for email in acc[1:]: # add all other emails of a person to the first email # graph of one email to every other graph[acc[1]].add(email) # add the first email to every other email # graph of every other email to one email graph[email].add(acc[1]) # map every email to name email_to_name[email] = name seen = set() ans = [] # go through the graph keys(emails): for email in graph: # if email is not seen, add it to seen and: if email not in seen: seen.add(email) # create the stack stack = [email] component = [] while stack: node = stack.pop() component.append(node) for nei in graph[node]: if nei not in seen: seen.add(nei) stack.append(nei) ans.append([email_to_name[email]] + sorted(component)) return ans accounts = [["John", "[email protected]", "[email protected]"], ["John", "[email protected]"], ["John", "[email protected]", "[email protected]"], ["Mary", "[email protected]"]] S = Solution() print(S.accountsMerge(accounts))
675f5a2e4872029d91aa1303ff228e59748bd517
supermitch/Chinese-Postman
/chinesepostman/my_iter.py
436
3.96875
4
"""Iterator related helper functions.""" def flatten_tuples(iterable): """ Flatten an iterable containing several tuples, into a single tuple. Sum all tuples, which "extends" them, with empty tuple as start value. """ return sum(iterable, ()) def all_unique(iterable): """Returns True if all items in an iterable are unique.""" seen = set() return not any(x in seen or seen.add(x) for x in iterable)
e2f8d709a76f7bb2677ba2721d038f0c03a42d34
jayeshhiray1/PythonBasicsCode
/Scope_LifetimeVariables.py
645
3.9375
4
def my_func(): x = 10 print("Value inside function:",x) x = 20 my_func() print("Value outside function:",x) #user defined function def add_numbers(x,y): sum = x + y return sum #Global vs. Local variables num1 = 5 num2 = 6 print("The sum is", add_numbers(num1, num2)) total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print ("Inside the function local total : ", total) return total; # Now you can call sum function sum( 10, 20 ); print("Outside the function global total : ", total)
868987ee02a2528060bb9a85b8907b5548b475cf
daydreamboy/HelloPython
/python_basic/13_argparse_arguments_set_variable_name.py
524
3.5625
4
# Usage: # $ python3 13_argparse_arguments_set_variable_name.py -v 1 -s 3 import argparse # Create the parser my_parser = argparse.ArgumentParser() # Add the arguments # Note: dest to rename variable name for the argument my_parser.add_argument('-v', '--verbosity', action='store', type=int, dest='my_verbosity_level') my_parser.add_argument('-s', '--silent', action='store', type=int) # Execute the parse_args() method args = my_parser.parse_args() print(vars(args)) print(args.my_verbosity_level) print(args.silent)
0f844c9b80e20250f51b7b9c8b5d4f3ce308f02c
mdelmas/adventOfCode2019
/day5/part2.py
1,710
3.71875
4
import math def add(a, b): return a + b def multiply(a, b): return a * b operations = { 1: add, 2: multiply } def runIntcodeProgram(program): i = 0 while i < len(program): opcode = program[i] % 100 if opcode == 99: break if opcode == 1 or opcode == 2 or opcode == 7 or opcode == 8: param1 = program[i+1] if math.floor(program[i]/100) % 10 else program[program[i+1]] param2 = program[i+2] if math.floor(program[i]/1000) % 10 else program[program[i+2]] if opcode == 1 or opcode == 2: program[program[i+3]] = operations[opcode](param1, param2) elif opcode == 7: program[program[i+3]] = 1 if param1 < param2 else 0 elif opcode == 8: program[program[i+3]] = 1 if param1 == param2 else 0 i += 4 elif opcode == 3: program[program[i+1]] = int(input()) i += 2 elif opcode == 4 : param = program[i+1] if math.floor(program[i]/100) % 10 else program[program[i+1]] print("Diagnostic code is " + str(param)) i += 2 elif opcode == 5 or opcode == 6: param1 = program[i+1] if math.floor(program[i]/100) % 10 else program[program[i+1]] param2 = program[i+2] if math.floor(program[i]/1000) % 10 else program[program[i+2]] if opcode == 5 and param1 != 0 or opcode == 6 and param1 == 0: i = param2 else: i += 3 return program[0] program = [int(x) for x in open("./input").readlines()[0].split(',')] result = runIntcodeProgram(program)
4b32d1a8fcf1aefd547f9ab82d9b0dd5a84123c3
robbintt/PythonScraper
/json_aggregator_test_old/json_data_aggregator.py
4,368
3.703125
4
import json import os import md5 """ Purpose: This module is designed to combine all the json files in a directory into one json file. """ directory_to_use = "./sfbay_data_052013/" ### include a trailing / output_path_and_filename = "./sfbay_data_052013.json" def import_file ( json_file_name, directory_to_use ): """ Pass this function a "xyz.json" filename to import it and return it as a variable. This function is looped over during the function, process_the_directory in order to campture all data in the target directory. """ target_file = directory_to_use + json_file_name json_file = open( target_file, 'r' ) json_as_dict = json.load( json_file ) json_file.close() return ( json_as_dict ) def get_file_names ( directory_explored ): """ Get all xyz.json filenames in the prescribed directory. This module assumes all json files in the prescribed directory are to be combined. This function will return a list of filenames 'xyz.json' This module is currently configured to explore the directory this module is in. """ # get a list of ALL files in the specified directory file_name_list = os.listdir( directory_explored ) # declare the list which will contain only the name of all json files json_files_list = [] # store all the files with .json at the end in json_files_list for each in file_name_list: if each[-5:] == ".json": json_files_list.append( each ) else: pass # return just the files with .json at the end return ( json_files_list ) def process_the_directory ( directory_with_json_files, filename_list ): """ Process all json files in directory_with_json_files """ # Declare the list which will contain each json dictionary list_containing_json_dicts = [] # All dict data from all json files goes into list_containing_json_dicts for each in filename_list: list_containing_json_dicts.append( import_file( each, directory_with_json_files ) ) """ this segment of the module just checks the md5 keys used as dict keys for duplicates, and then zips the dictionary back together. If there is a duplicate, it currently keeps the first one in, which is currently based on the order of filenames in filename_list. Eventually, this should be decided based on the timepoint or the html in the data tuple. Or something... update: 052313 TAR: The scraper has been changed to notice duplicate data on the fly. This doesn't precede the need for collision detection here. The best route for this software is to develop a error log that will alert the administrator when there is a collision and allow a person to solve the collision. It could potentially attempt to solve simple collision cases first, e.g. if everything is identical or most things are sufficiently identical, or if some data is missing from one and not the other. """ combined_md5_tracker = [] combined_list_of_jsons = [] for each_dict in list_containing_json_dicts: for each_key in each_dict.iterkeys(): if each_key not in combined_md5_tracker: combined_md5_tracker.append( each_key ) combined_list_of_jsons.append( each_dict[each_key] ) else: pass # This dict is the the combined data, with no overlaps based on md5 keys. return dict( zip( combined_md5_tracker, combined_list_of_jsons )) def export_dict_to_json ( dict_to_export, output_path_and_filename ): """ Generic json dump function, needs expanded This portion of the function is easily served in the portion of the original code dedicated to exporting to a json. """ json_file = open ( output_path_and_filename, "w" ) json.dump( dict_to_export, json_file ) json_file.close() return () # Get the list of json files in the directory specified. filename_list = get_file_names( directory_to_use ) compiled_dict = process_the_directory( directory_to_use, filename_list ) # Export the final compiled dictionary as a json file. export_dict_to_json( compiled_dict, output_path_and_filename)
165fc82345e16c57527fd629e0ef572fb091636c
mikeyii/pyimgbot
/grabPixels.py
2,100
3.75
4
#!/usr/bin/env python3 # grabpixels.py - grab pixels and save them with name from pymouse import PyMouse from PIL import ImageDraw, ImageGrab from string import Template m = PyMouse() retina = True def isYes(value): return value.lower() in ('y', 'yes') def savePixel(): x, y = m.position() im = ImageGrab.grab() if retina: x = x * 2 y = y * 2 pixel = im.getpixel((x, y)) pixelStr = '({}, {}, {}, {})'.format(pixel[0], pixel[1], pixel[2], pixel[3]) changeDistance = 'y' while isYes(changeDistance): distance = input('Enter distance(5):') if distance == '': distance = 5 else: distance = int(distance) result = generateImage(pixel, im, distance) print('Catched ', len(result)) im.show() save = input('Do you want to save it?(y): ') or 'y' if isYes(save): name = input('Write name for that pixel: ') s = Template('"$name": {"pixelcolor": $pixel, "distance": $distance},\n') with open("grabPixels.txt", "a") as myfile: myfile.write(s.substitute(name=name, pixel=pixelStr, distance=distance)) changeDistance = 'n' else: changeDistance = input('Do you want to changeDistance?(n): ') def generateImage(pixel, im, distance = 5): draw = ImageDraw.Draw(im) result = [] prev = (0, 0) for x in range(im.width): for y in range(im.height): if im.getpixel((x, y)) == pixel: if x - prev[0] < distance and y - prev[1] < distance: continue # print(x, y) draw.ellipse((x - 20, y - 20, x + 20, y + 20), outline='red') result.append((x, y)) prev = (x, y) return result def main(): print('Press Ctrl+C to exit') try: while True: input('Press Enter to save pixel') # Blocks until you press esc. savePixel() except KeyboardInterrupt: print('\nDone.') if __name__ == "__main__": main()
f22cd99f4430523b8320bd4a7416c4ce45e1cb61
SUPERPANDA-ORANGE/leetcode
/two sum/two_sum.py
624
3.671875
4
class Solution: """ @param: numbers: An array of Integer @param: target: target = numbers[index1] + numbers[index2] @return: [index1 + 1, index2 + 1] (index1 < index2) """ def twoSum(self, numbers, target): # write your code here list1 = [] for index in range(len(numbers)-1): i = 1 while i < len(numbers) - index: if numbers[index] + numbers[index + i] == target: list1.append(index + 1) list1.append(index + i + 1) return list1 else: i+=1
109b446b6866d1210a767d35f37ad6b25b835d3b
luginin-Ivan/dz-by-algoritm-
/18.py
174
3.765625
4
a = int(input("введите a :")) b = int(input("введите b :")) c = int(input("введите c :")) min=a if min>b: min=b elif min>c: min =c print(min)
55e88070c73c02f933c8abf3bafef1aff8ef90ec
Th0rt/study-programing-skill
/chapter4/question12.py
1,079
3.765625
4
def count_root(threshold, tree): return _count_root(threshold, tree.root) def _count_root(threshold, node, interims=[], root_count=0): if node is None: return root_count interims.append(0) # node単体の値を計算対象に入れるため、0を加える equals, smalls = add_and_filter( nums=interims, additional=node.value, threshold=threshold ) root_count += len(equals) if node.left: root_count += _count_root(threshold, node.left, smalls) if node.right: root_count += _count_root(threshold, node.right, smalls) return root_count def add_and_filter(nums, additional, threshold): """ numsの各値にaddtionalを加算し、threshold比較する。 その後、thresholdと比較し、thresholdと等しい値と、thresholdより小さい数を返す。 """ equals = [] smalls = [] for num in nums: t = num + additional if t < threshold: smalls.append(t) if t == threshold: equals.append(t) return equals, smalls
d9c16334cae02d7ba2379cbef76b5a082a3140ee
EMI322585/ILZE_course
/PYTHON/list_functions.py
1,654
3.703125
4
import json def print_introduction(): print("Ja vēlaties apskatīt sarakstu, nospiediet R (Read)") print("Ja vēlaties pievienot piezīmi, nospiediet A (Add)") print("Ja vēlaties iziet no saraksta, nospiediet X (Exit)") print("Ja vēlaties izdzēst kādu piezīmi, nospiediet D (Delete)") print("Ja vēlaties izdzēst visu sarakstu, nospiediet C (Clear)") print("Ja vēlaties labot piezīmes saturu, nospiediet U (Update)") def read_from_database(file_to_read): try: list = [] with open(file_to_read, "r") as data_file: list = json.loads(data_file.read()) except (ValueError, OSError): list = [] return list def write_to_database(file_to_write, data): with open(file_to_write, "w") as data_file: data_file.write(json.dumps(data)) def print_list(list): if len(list) == 0: print("Jūsu saraksts ir tukšs.") return None ix = 1 for item in list: print("{}.piezīme ir {}".format(ix, item)) ix += 1 def delete_from_list(list): delete = input("Lūdzu izvēlieties piezīmes kārtas nr, kuru vēlaties dzēst:") delete = int(delete) print("Jūs izvēlējāties piezīmi nr: " + str(delete)) print("Vai tiešām vēlaties to dzēst? J/N") choice2 = input("Ievadiet J vai N:...") if choice2.lower() == "j": list.remove(str(delete)) print("Piezīme ir izdzēsta.") if choice2.lower() == "n": print("Piezīme netika izdzēsta.") def update_list(list): update = input("Lūdzu izvēlieties piezīmes nr, kuru vēlaties atzīmēt kā izdarītu") list.update(["Darīts"])
a4d68e273a655c76ac0aac68a2d92b4c15aa5757
KendallWeaver/3670ScriptingForAnimationAndGames
/Nov 15 Lecture/Nov15LectureScript.py
1,204
4.09375
4
#Classes #Other Classes can inherit attributes from other classes. #dot operator can access components from other classes to use. import maya.cmds as cmds #you have class variables and instance variables #self is a special work to create an instance #its referring back to the template itself #so feet = 4 is the template for everything. doing self. indicates that one instance is different, while chaning the #feet will make it change everything. #at least I think that's what's happening class Animal(): #every class should start with this. it's to initialize an object and how it's constructed #everyone function should have the sself in front of it, so python knows you are talking about the method in that #instance. def __init__(self, colour, name): #this is a constructor #this is where you can define the variables for the object #these attributes have to be assigned self.colour = colour self.name = name #look at locatorTool_2 for more details regarding it. #but when creating attributes inside a class, you should proceed most variables with self. #Animal('brown', 'charley') mytool = LocatorTool() help(mytool) mytool.create()
50fa7aba73e43848677698f646ea10b5abb67d34
montse139/Lottery
/lottery.py
389
3.640625
4
import random numbers = [] amount_numbers = [] print "Welcome to the Lottery numbers generator!" user_numbers = int(raw_input("Please enter the amount of random numbers that you would like to have: ")) for i in range(user_numbers): amount_numbers.append(i) for i in range(1,100): numbers.append(i) print random.sample(numbers, len(amount_numbers)) print "END"# Lottery # Lottery
41cddb365ff1bdcd28670f0b344a8f2e6a684295
muyawei/DataAnalytics
/Data_analystic/test/read_text.py
466
3.8125
4
# coding:utf-8 f = open("foo.txt") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: print line, # 后面跟 ',' 将忽略换行符 # print(line, end = '')   # 在 Python 3中使用 line = f.readline() f.close() for line in open("foo.txt"): print line, f = open("c:\\1.txt", "r") lines = f.readlines()#读取全部内容 for line in lines: print line
4f8a1083ff281ffe89d98a8202803669370dd3db
Achyu02/CompetitiveProgramming
/Week1/Day1/apples.py
1,492
3.875
4
def get_maximum(stock_prices): if len(stock_prices) < 2: raise ValueError('Minimum of 2 prices') minimum = stock_prices[0] maximum = stock_prices[1] - stock_prices[0] for i in xrange(1, len(stock_prices)): present = stock_prices[i] profit = present - minimum maximum = max(maximum, profit) minimum = min(minimum, present) return maximum # Tests import unittest class Test(unittest.TestCase): def test_price_goes_up_then_down(self): actual = get_maximum([1, 5, 3, 2]) expected = 4 self.assertEqual(actual, expected) def test_price_goes_down_then_up(self): actual = get_maximum([7, 2, 8, 9]) expected = 7 self.assertEqual(actual, expected) def test_price_goes_up_all_day(self): actual = get_maximum([1, 6, 7, 9]) expected = 8 self.assertEqual(actual, expected) def test_price_goes_down_all_day(self): actual = get_maximum([9, 7, 4, 1]) expected = -2 self.assertEqual(actual, expected) def test_price_stays_the_same_all_day(self): actual = get_maximum([1, 1, 1, 1]) expected = 0 self.assertEqual(actual, expected) def test_one_price_raises_error(self): with self.assertRaises(Exception): get_maximum([1]) def test_empty_list_raises_error(self): with self.assertRaises(Exception): get_maximum([]) unittest.main(verbosity=2)
0136a499188854124db0c33462c19340ee5a5911
ukoloff/sorts.py
/algo/bubble.py
313
3.890625
4
# # Bubble sort # def sort(array): for i in range(1, len(array)): swapped = False for j in range(len(array) - i): if array[j] > array[j + 1]: swapped = True array[j], array[j + 1] = array[j + 1], array[j] if not swapped: break
f5917ad3d88f72824b7c86a1726616a7c74c3d27
sidv/Assignments
/Shanu_Abraham/16_aug_assigment_16/string_10_files.py
678
4.15625
4
# Write the above string into 10 files data3.txt,data4.txt and so on.. string = "A computer is a machine that can be programmed to carry out sequences of arithmetic or logical operations automatically. Modern computers can perform generic sets of operations known as programs. These programs enable computers to perform a wide range of tasks. A computer system is a complete computer that includes the hardware operating system main software and peripheral equipment needed and used for full operation. This term may also refer to a group of computers that are linked and function together" for i in range(3,14): fd = open(f"data{i}.txt","w") fd.write(string) fd.close()
5769f17439f6672335ba2781b6121e54d5ab5da0
kryptn/euler
/p36.py
203
3.546875
4
def palendrome(n): n = str(n) if n == n[::-1]: return True return False def answer(limit): return sum([x for x in xrange(limit+1) if palendrome(x) and palendrome(bin(x)[2:])])
2e5014838b9e44b85b4ec5638df5c47c5b1df818
ronny-souza/Lista-Exercicios-05-Python
/Exercicio03.py
325
3.859375
4
# QUESTÃO 03 - Crie uma função que receba do usuário a base (b) e o expoente ​(n), e calcule e retorne ​b​^n. def calculoPotencia(base, expoente): return base**expoente base = int(input("Digite o valor da base: ")) expoente = int(input("Digite o valor do expoente: ")) print(calculoPotencia(base, expoente))
f9eacc43ab2bde0bee2419b7775de855db7a5698
zipxup/ZeroToHero_Python
/HelloWorld/DisplayText.py
590
3.546875
4
print('The capybara is the worlds largest rodent') print("It's a beautiful day in the neighborhood") print('It"s a beautiful day in the neighborhood') print('It\'s a beautiful day in the neighborhood') print("""Hickory Dictory Dock! The mouse ran up the clock I finally find a good video to learn python""") #\\ is useful to show \ on the screen print("is there a difference with \\ and \ ") print("I want to show \\n") print(""" There once was a movie star icon who preferred to sleep with the light on. They learned how to code a device that sure glowed and lit up the night using Python! """)
cd7b277f59f9e49839edb72772b661219ec4c45a
zjxpirate/Daily-Upload-Python
/Binary_Trees/******Binary_Trees_is_symmetric.py
691
4.09375
4
from Binary_Trees_node import BinaryTreeNode def is_symmetric(tree): def check_symmetric(subtree_0, subtree_1): if not subtree_0 and not subtree_1: return True elif subtree_0 and subtree_1: return (subtree_0.data == subtree_1.data and check_symmetric(subtree_0.left, subtree_1.right) and check_symmetric(subtree_0.right, subtree_1.left)) # One subtree is empty, and the other is not. return False return not tree or check_symmetric(tree.left, tree.right) b = BinaryTreeNode(1, BinaryTreeNode(2, BinaryTreeNode(4), BinaryTreeNode(5)), BinaryTreeNode(2, BinaryTreeNode(5), BinaryTreeNode(4))) print(is_symmetric(b))
0de3301077d96c59425ddecdd4306db9fb24e5af
YinongLong/Data-Structures-and-Algorithm-Analysis
/problems/interviews-questions-analysis/judge_pop_order.py
466
3.5625
4
# -*- coding: utf-8 -*- from __future__ import print_function class Solution(object): def IsPopOrder(self, pushV, popV): stack = [] pop_idx = 0 for item in pushV: stack.append(item) while stack and stack[-1] == popV[pop_idx]: stack.pop() pop_idx += 1 if stack: return False return True s = Solution() print(s.IsPopOrder([5, 2, 3, 7], [3, 5, 2, 7]))
d65f5c3eab3d0a687dc4668a99b434c3f9061713
nikita2697/python_practice
/tut_14.py
308
3.9375
4
#while loop """" i=0 while(i<45): print(i,end=" ") i=i+1 #break and continue if i==42: break """ j=0 while(True): #print("enter number") j = j + 1 num= int(input("enter number")) if(num>10): print("num grater than 10") break else: continue
76e62f7ac5b738a99ec1144b759623f9ab5324a4
Aasthaengg/IBMdataset
/Python_codes/p02383/s433411245.py
563
4.0625
4
def north(d): return [d[1], d[5], d[2], d[3], d[0], d[4]] def east(d): return [d[3], d[1], d[0], d[5], d[4], d[2]] def south(d): return [d[4], d[0], d[2], d[3], d[5], d[1]] def west(d): return [d[2], d[1], d[5], d[0], d[4], d[3]] numbers = list(map(int, input().split())) directions = list(input()) for d in directions: if d == "N": numbers = north(numbers) elif d == "E": numbers = east(numbers) elif d == "S": numbers = south(numbers) elif d == "W": numbers = west(numbers) print(numbers[0])
ac8aa5c4d6a25a71a9797779113d2381d456ae7d
ngr/sandbox
/python/performance/pattern_search.py
1,233
3.71875
4
""" Benchmark speed of searching the substring in data using different approaches. """ import random import re import string import sys import time from collections import defaultdict PATTERN = 'hello world elisha and nick 123 BAZOOKA' DATA_SIZE = 1000000 NUM_TESTS = 1000 NUM_DATASETS = 10 if sys.version_info < (3, 7): raise SystemExit('Sorry, this code need Python 3.7+ in order to measure nanoseconds') # Build random SAMPLES htmls = ["".join([random.choice(string.ascii_letters + string.digits + ' ') for _ in range(DATA_SIZE)]) for _ in range(NUM_DATASETS)] pattern = re.compile(PATTERN) def find_in(p, data): return True if p in data else False def find_re(p, data): return re.match(p, data) def find_re_compiled(_, data): return re.match(pattern, data) result = defaultdict(float) for method in [v for k, v in locals().items() if k.startswith('find_')]: for _ in range(NUM_TESTS): for html in htmls: st = time.perf_counter_ns() _ = method(PATTERN, html) result[method.__name__] += time.perf_counter_ns() - st result = {k: v / (NUM_TESTS * NUM_DATASETS) for k, v in result.items()} print(f"Average method execution time (ns): {result}")
898889d64cd7ed95fcf1f8612c11ea536cb639d5
qiyon/leetcode
/algorithms_001-050/005_Longest-Palindromic-Substring/py_solution.py
723
3.5
4
##leetcode submission begin ----------------------- class Solution: # @param {string} s # @return {string} def longestPalindrome(self, s): subStr = "" for i in range(0, len(s)): for k in range(0,2): tmp = self.getSubStr(s, i, i+k) if len(tmp) > len(subStr): subStr = tmp return subStr def getSubStr(self, s, left, right): while left>=0 and right<len(s) and s[left]==s[right]: left -= 1 right += 1 return s[left+1 : right] ##leetcode submission end ----------------------- if __name__ == "__main__": slObj = Solution(); print slObj.longestPalindrome("good solution")
0d5a6b11ca60f8f45f50bf2d5d60ea4f544cfa61
xLuis190/Python-School-work
/anagrams.py
141
3.796875
4
def isAnagram(word1,word2): word1 = sorted(word1.lower()) word2 = sorted(word2.lower()) return "".join(word1) == "".join(word2)
7dd9b4487eaab12819da3dbc1954fe00698db59a
richierh/LearningPy
/GUIExamps/MyOwnProject/Model/objectdb.py
492
3.640625
4
#!usr/bin/env python # -*- coding: utf-8 -*- def insert(): # Will insert data return True def delete(): # Will delete data return True def erase(): # Will erase data return True class Cup: def __init__(self): self.__color = "hello" self._content = None # protected variable def fill(self, beverage): self._content = beverage def empty(self): self.content = None cup = Cup() cup.__color="eee" print cup.__color
d36f757509b3875639eedf853a2ff788f09e994b
muhammadmuzzammil1998/CollegeStuff
/MCA/Data Structures/Stack_pop_linkedlist.py
2,370
4.15625
4
class LinkedList: class Node: def __init__(self, data): self.data = data self.next = None def __str__(self): return str(self.data) def __init__(self): self.head = None def append(self, data): if self.head == None: self.head = self.Node(data) return self current = self.head while current.next != None: current = current.next node = self.Node(data) current.next = node return self def remove(self, data=None): if self.head == None: return self if data is None: data = self.peek() if self.head.data == data: self.head = self.head.next return self current = self.head while (current.next != None): if current.next.data == int(data): current.next = current.next.next return data current = current.next return None def peek(self): if self.head == None: return None peek_value = self.head.data if self.head.next == None: self.head = None return peek_value current = self.head while (current.next != None): current = current.next peek_value = current.data return peek_value def __str__(self): current = self.head traversal = "[ " while current != None: traversal += str(current) + " " current = current.next return traversal + "]" class Stack: def __init__(self, stack=LinkedList()): self._stack = stack def push(self, data): self._stack.append(int(data)) def pop(self): if self._stack.peek() is None: print("~~STACK UNDERFLOW~~") return None return self._stack.remove() def __str__(self): return str(self._stack) if __name__ == '__main__': stack = Stack() print("1. Push to stack") print("2. Pop stack") print("3. Print stack") while True: inp = input("Your choice: ") if inp == "1": stack.push(input(" Enter element: ")) elif inp == "2": print(" Element removed:", stack.pop()) else: print(stack)
3a52ac0ded59e4f41b4ac075d3f4a44f9ed23db8
lolilo/coding_exercises
/raw_input_from_terminal/arithmetic_progression.py
1,895
4.0625
4
# user_input = raw_input() # arithmetic progression. # two lines of raw input (stdin), first one being length of given progression, second the arithmetic progression # find the missing number and print it to stdout # Enter your code here. Read input from STDIN. Print output to STDOUT #user_input = user_input.split('\n') #print n # We're given the length of the given progression...how can I better use this information? # Oh, apparently it's needed for other programming languages. # Do I not need to transform stuff to an int list? # How can I reduce time complexity? def find_missing(n, ap): length_of_progression = int(n) ap = ap.split() # create a list of int for i in range(length_of_progression): ap[i] = int(ap[i]) init_diff = ap[1] - ap[0] for i in range(length_of_progression-1): this = ap[i] next = ap[i+1] curr_diff = next - this if curr_diff != init_diff: if next > this: # progression increasing if init_diff < curr_diff: # insert @ curr_diff return this + init_diff else: return ap[0] + curr_diff else: # progression decreasing if init_diff < curr_diff: # abs(init_diff) > abs(curr_diff), insert @ init_diff return ap[0] + curr_diff else: # missing number @ curr_diff return this + init_diff def loop(): while True: n = int(raw_input('n > ')) ap = raw_input('arithmetic progression > ') print find_missing(n, ap) def main(): loop() # print find_missing(n, ap) if __name__ == "__main__": n = "5" ap = "1 21 31 41 51" main() # 45 minutes. Finished with 18 minutes to spare. 7 test cases. # Didn't consider decreasing progression at first, so passed 5/7 tests. # Fixed easily enough.
86ae392fe301f37d3507499c72914a3c1b331f09
kmprashanthi/DataStructuresPractise
/chk_arr_sort.py
154
3.765625
4
def sorted_array(A): if len(A)==1: return True return ( A[0]<=A[1] and sorted_array(A[1:])) A = [1,2,3,10,5,6,7] print (sorted_array(A) )
ba416e47609c529d9f40edaaed023bf6759047c7
AndriiDiachenko/pyCheckIo
/1_Elementary/split-pairs.py
469
4.5625
5
''' Split the string into pairs of two characters. If the string contains an odd number of characters, then the missing second character of the final pair should be replaced with an underscore ('_'). Input: A string. Output: An iterable of strings. Example: split_pairs('abcd') == ['ab', 'cd'] split_pairs('abc') == ['ab', 'c_'] ''' def split_pairs(text: str) -> list: if len(text) % 2 !=0: text+="_" return [text[i: i+2] for i in range(0, len(text), 2)]
913d44d328637cc90b58c22aa5565fb1125ba0d8
xzpjerry/learning
/Coding/playground/sorting/linear_find_small.py
418
3.546875
4
#!/usr/bin/env python3 ''' Author: Zhipeng Xie Topic: Effect: ''' import random def test(datal): current_smallest = [datal[0]] for num in datal: if num > current_smallest[0]: current_smallest.pop() current_smallest.append(num) return current_smallest[0] if __name__ == '__main__': datal = [random.randrange(i ** 2) for i in range(1000, 2000)] print(test(datal))
f95899b13618e5afc9778ae333499451b5b911b6
Crismarquez/nlp
/utils/util.py
14,014
3.546875
4
""" This is the documentation for this module """ import random from typing import List from typing import Optional from typing import Dict import re import string import numpy as np import pandas as pd np.random.seed(0) def gen_vocabulary(corpus: List[str]) -> List[str]: """ get the corpus vocabulary Parameters ---------- corpus : list This list contains the tokenized corpus Returns ------- list unique word list. """ return list(set(corpus)) def gen_theta( vocabulary: List[str], dimension: int, seed: Optional[int] = None ) -> np.ndarray: """ Generate a vector that will contain the vector representacion for each word, both central word and context word, the first half related with central words and second part related with context words. Parameters ---------- vocabulary : list list of unique words in the corpus. dimension : int Size of dimension that will have each vector representation of words. seed : int, optional Set random generation. The default is None. Returns ------- numpy.ndarray Random vector with size: 2 * vocabulary size * dimention, contains the vector representation for each word. """ theta_size = 2 * len(vocabulary) * dimension if seed is not None: np.random.seed(seed) return np.random.uniform(-1, 1, theta_size) def find_index(word: str, vocabulary: List[str]) -> int: """ Find location of a word in the vocabulary list. Parameters ---------- word : str word to search. vocabulary : list list of unique words in the corpus. Returns ------- int Index value of word in the vocabulary list. """ return vocabulary.index(word) def find_location( word_index: int, theta: np.ndarray, dimension: int, central: bool = True ) -> List[int]: """ Find the location of a word in the theta vector in terms of start index and end index. Parameters ---------- word_index : int Index word in the vocabulary list, use find_index function to get this parameter. theta : numpy.ndarray Array that contains the vector representation of words, initially use gen_theta to get this parameter. dimension : int Size of dimension that have each vector representation of words. central : bool, optional To get central or context word, if the parameter is True, the return will be the location in theta for a central word, in another case the result will be for a context word. The default is True. Returns ------- list List with two elments, first element contain the index where start the vector representation of word_index in theta, the second element contains the index where end the vector of word_index. """ if central is True: start = word_index * dimension end = start + dimension else: start = len(theta) // 2 + word_index * dimension end = start + dimension return [start, end] def find_vector( word_index: int, theta: np.ndarray, dimension: int, central: bool = True ) -> np.ndarray: """ Extract the vector representation of a word in theta vector. Parameters ---------- word_index : int Index word in the vocabulary list, use find_index function to get this parameter. theta : numpy.ndarray Array that contains the vector representation of words, initially use gen_theta to get this parameter. dimension : int Size of dimension that will have each vector representation of words. central : bool, optional To get central or context representation, if the parameter is True, the return will be the vector representation in theta for a central word, in another case the result will be for a context word. The default is True. Returns ------- numpy.ndarray the vector representation in theta for word_index. """ start, end = find_location(word_index, theta, dimension, central) return theta[start:end] def random_dict( co_occurrences: Dict[str, int], sample_rate: float, ) -> Dict[str, int]: """ Select a random keys (central-context) and filter it in co_occurrences. Parameters ---------- co_occurrences : Dict[str, int] This dictionary contains the co-occurrence for each combination in the corpus between central and context word, the key is a string that contain the central word in the right and context word on the left, this words are separed by "<>" character. sample_rate: float To take a sample from cooccurrence. Returns ------- Dict[str, int] co_occurrency for filter keys, central or context. """ conexions = list(co_occurrences.keys()) n_samples = int(len(conexions) * sample_rate) sample = random.choices(conexions, k=n_samples) sample_dict = {choice: co_occurrences[choice] for choice in sample} return sample_dict def get_glove_vectors( vocabulary: List[str], theta: np.ndarray, central: bool = False ) -> Dict[str, list]: """ Organize the word vector representation in a dictionary. Parameters ---------- vocabulary : list list of unique words in the corpus. theta : numpy.ndarray Array that contains the vector representation of words. central : bool, optional Especificate filter in terms of central or context words. The default is False. it means the default return the context words. Returns ------- Dict[str, list] Dictionary that the key is the word and the value is the vector representation. """ dimension = len(theta) // 2 // len(vocabulary) data = {} for word in vocabulary: word_index = vocabulary.index(word) word_vector = find_vector(word_index, theta, dimension, central=central) data[word] = list(word_vector) return data def get_labels(word_label: Dict[str, str]) -> List[str]: """ Obtain the labels related in the model. Parameters ---------- word_label : Dict[str, str] Dictionary that contain the classification of words, the key represent the word and the value is the label or topic. Returns ------- List[str] This list contain all posible labels in the model given. """ return list(set(word_label.values())) def gen_theta_class_words(labels: List[str], dimension: int) -> Dict[str, np.ndarray]: """ Create initial parameters theta, represent the weights for model the labels. Parameters ---------- labels : List[str] This list contain all posible labels in the model given. dimension : int Size of dimension that will have each vector of weights. Returns ------- label_vector = Dict[str, np.ndarray] Dictionary where the key represent the label and tha value represents the vector of weights. """ return {label: np.random.uniform(-1, 1, dimension) for label in labels} def gen_grandient(theta: Dict[str, np.ndarray]) -> Dict[str, int]: """ Generate the dictionary in order to save the futures values for the gradient, useful to avoid check if the key exist when the gradient is updating. Parameters ---------- theta : Dict[str, np.ndarray] Dictionary where the key represent the label and tha value represents the vector of weights. Returns ------- Dict[str, int] DESCRIPTION. """ return {label: 0 for label in theta.keys()} def filter_vocabulary(df: pd.DataFrame, f_vocabulary: List[str]): """ filter words from a Dataframe Parameters ---------- df : pd.DataFrame Dataframe where the keys are the words. f_vocabulary : List[str] List of words tha want to filter in the dataframe. Returns ------- df_ind : TYPE DESCRIPTION. """ df_ind = df.loc[df.index.intersection(f_vocabulary)] return df_ind def df_to_dict(dataframe: pd.DataFrame) -> Dict[str, list]: """ transform a data frame to a dictionary where the keys are the index and the values are the rows. Parameters ---------- dataframe : pd.DataFrame DESCRIPTION. Returns ------- Dict[str, Union[list, str, float]] DESCRIPTION. """ dataframe = dataframe.to_dict(orient="index") return {word: list(dataframe[word].values()) for word in dataframe.keys()} def gen_theta_dict( vocabulary: List[str], dimension: int ) -> Dict[str, Dict[str, np.ndarray]]: """ Create initial parameters theta, this dictionary contain two dictionary, first one related with central words and second one refers to context words. Parameters ---------- vocabulary : List[str] This list contain all vocabulary in the model given. dimension : int Size of dimension that will have each vector. Returns ------- Dict[str, Dict[str, np.ndarray]] Dictionary where the key represent the label and tha value represents the vector of weights. """ np.random.seed(0) theta = { "central": gen_theta_class_words(vocabulary, dimension), "context": gen_theta_class_words(vocabulary, dimension), } return theta def gen_grandient_dict(vocabulary: List["str"]) -> Dict[str, Dict[str, np.ndarray]]: """ Generate the dictionary with the same shape of theta.. Parameters ---------- theta : Dict[str, np.ndarray] Dictionary where the key represent the label and tha value represents the vector of weights. Returns ------- Dict[str, Dict[str, np.ndarray]] DESCRIPTION. """ gradient = { "central": {label: 0 for label in vocabulary}, "context": {label: 0 for label in vocabulary}, } return gradient def del_key(co_occurrences: Dict[str, int], key_del: str) -> Dict[str, int]: """ Detele some key from dictionary. Parameters ---------- co_occurrences : Dict[str, int] This dictionary contains the co-occurrence for each combination in the corpus between central and context word, the key is a string that contain the central word in the right and context word on the left, this words are separed by "<>" character. del_key : str Key that want to be deleted. Returns ------- None. """ return { key: value for key, value in co_occurrences.items() if key_del not in key.split("<>") } def get_vocabulary(co_occurrences: Dict[str, int]) -> List[str]: """ Create a list with the vocabulary involve in co_occurrence. Parameters ---------- co_occurrences : Dict[str, int] This dictionary contains the co-occurrence for each combination in the corpus between central and context word, the key is a string that contain the central word in the right and context word on the left, this words are separed by "<>" character. Returns ------- List[str] list of unique words. """ vocabulary = [] for key in list(co_occurrences.keys()): vocabulary.append(key.split("<>")[0]) vocabulary.append(key.split("<>")[1]) return list(set(vocabulary)) def clean_word(word: str) -> str: """ To only take leters and numbers Parameters ---------- word : str Word that want to clean. Returns ------- str Word. """ return re.sub("[^A-Za-z0-9]+", "", word).lower() def clean_phrase(phrase: str) -> str: """ Clean the phrase, punctuation ---------- word : str Word that want to clean. Returns ------- str Word. """ return re.sub("[%s]" % re.escape(string.punctuation), " ", phrase).lower() def drop_duplicate_key(co_occurrences: Dict[str, int]) -> Dict[str, int]: """ Drop the key when central and context words are the same. Parameters ---------- co_occurrences : Dict[str, int] This dictionary contains the co-occurrence for each combination in the corpus between central and context word, the key is a string that contain the central word in the right and context word on the left, this words are separed by "<>" character. Returns ------- Dict[str, int] Return the co-occurrence without duplicate keys. """ return { key: value for key, value in co_occurrences.items() if key.split("<>")[0] != key.split("<>")[1] } def columns2phrase(DataFrame: pd.DataFrame, use_cols: List[str]) -> List[str]: """ Takes a set of columns and concatenate the text for each row. Parameters ---------- DataFrame : pd.DataFrame DESCRIPTION. use_cols : List[str] DESCRIPTION. Returns ------- List[str] DESCRIPTION. """ text_mx = DataFrame[use_cols].values return [" ".join(text_mx[i]) for i in range(len(text_mx))] def metricsreport2df(reports: Dict[str, Dict]) -> pd.DataFrame: """ Transform the metrics report models to dataframe Parameters ---------- reports : Dict[str, Dict] This dictionary contains the report returns by sklearn.metrics.classification_repor, the key correspond to the model. Returns ------- DataFrame with the diferent metrics and models. """ dataframe = pd.DataFrame() for model in list(reports.keys()): df_temp = pd.DataFrame(reports[model]).transpose().reset_index() df_temp["model"] = model dataframe = pd.concat([dataframe, df_temp]) dataframe = dataframe.rename(columns={"index": "label/avg"}) return dataframe
719a920ca1f1be6fb3c3eab10bd718a3c82987d3
j-bro/comp479-project2
/src/main/python/collection/collection.py
1,885
3.59375
4
class CollectionInfo: def __init__(self, document_count=0, token_count=0, avg_doc_length=0): """ Class representing the collection info of a collection. :param document_count: the number of documents in the collection. :param token_count: the total number of tokens in the collection. :param avg_doc_length: the average length of documents in the collection. """ self.document_count = document_count self.token_count = token_count self.avg_doc_length = avg_doc_length @classmethod def from_file(cls, file_path): """ Serialize the object from the given file path. :param file_path: the path of the file to read from. :return: An instance of Collection representing the file at the given path. """ with open(file_path) as f: file_lines = f.readlines() for line in file_lines: line_split = line.replace('\n', '').split('=') if line_split[0] == "DocumentCount": document_count = int(line_split[1]) elif line_split[0] == "TokenCount": token_count = int(line_split[1]) elif line_split[0] == "AvgDocLength": avg_doc_length = float(line_split[1]) if not (document_count and token_count and avg_doc_length): raise Exception("Collection file invalid, must contain all of (DocumentCount, TokenCount, AvgDocLength)") return cls(document_count, token_count, avg_doc_length) def __str__(self): """ Represent the collection object as a string. :return: """ str_repr = "DocumentCount={}\n".format(self.document_count) str_repr += "TokenCount={}\n".format(self.token_count) str_repr += "AvgDocLength={}\n".format(self.avg_doc_length) return str_repr
67e2c1b5c55402291bda1efbfb47b4342846dd20
wsbrandow/Minor-Python-Projects
/List Median Finder.py
228
3.640625
4
def median(x): xsort = sorted(x) if len(xsort) % 2 == 0: right = len(xsort) / 2 left =(len(xsort) / 2) - 1 return (xsort[right] + xsort[left]) / 2.0 else: return xsort[len(xsort) / 2]
f9418dd9f10869570e937264b1f85cf984322cfa
techkids-c4e/c4e5
/Pham Quang Huy/26.6.2016/List_assignment1.py
531
4.125
4
color_list = ['Blue','Red','Black','Pink','Brown','Yellow'] print('My color list: ') print(color_list) print('Color_list at index 3: ',color_list[3]) i = input('Enter a number for 0-5: ') i = int(i) print('Your color: ',color_list[i]) print(color_list) for color in color_list: print(color) fav_color = input('Whats your favourite color: ') color_list.append(fav_color) t = color_list.index(fav_color) if t == 6 : print('Sorry, I could not find your color') else : print('Your color is at index ',t,' in my list')
2c9e176857eb46615f894edc7cec076325540a6c
AdamZhouSE/pythonHomework
/Code/CodeRecords/2840/60678/261461.py
305
3.546875
4
def countLuckyNum(string): count = 0 for i in string: if i == '4' or i == '7': count += 1 return count nANDk = input().split() n = int(nANDk[0]) k = int(nANDk[1]) nums =input().split() count = 0 for i in nums: if countLuckyNum(i) <= k: count += 1 print(count)
38adf9c060437b7097324986f7a2c0cd03b5f99b
noahfp/Project_Euler
/p063.py
283
3.71875
4
import math def power_digits(n, d): return [i**n for i in range(int(math.ceil(math.pow(10,(d-1)/float(n)))), int(math.ceil(math.pow(10,d/float(n)))))] # testing gives 9^21 largest power which is still 21 digits long. print sum([len(power_digits(n,n)) for n in range(1, 22)])
7d88ff4bef4119e9b77552109dc7132624a09db6
anton-dovnar/checkio
/ElectronicStation/words_order.py
2,057
4.15625
4
#!/home/fode4cun/.local/share/virtualenvs/checkio-ufRDicT7/bin/checkio --domain=py run words-order # You have a text and a list of words. You need to check if the words in a list appear in the same order as in the given text. # # Cases you should expect while solving this challenge: # # a word from the list is not in the text - your function should return False;any word can appear more than once in a text - use only the first one;two words in the given list are the same - your function should return False;the condition is case sensitive, which means 'hi' and 'Hi' are two different words;the text includes only English letters and spaces.Input:Two arguments. The first one is a given text, the second is a list of words. # # Output:A bool. # # # END_DESC import re def words_order(text: str, words: list) -> bool: indexes = [] for word in words: match = re.search(r'\b{}\b'.format(word), text) if match: indexes.append(match.start()) if len(set(indexes)) == len(words) and sorted(indexes) == indexes: return True return False if __name__ == '__main__': print("Example:") print(words_order('hi world im here', ['world', 'here'])) # These "asserts" are used for self-checking and not for an auto-testing assert words_order('hi world im here', ['world', 'here']) == True assert words_order('hi world im here', ['here', 'world']) == False assert words_order('hi world im here', ['world']) == True assert words_order('hi world im here', ['world', 'here', 'hi']) == False assert words_order('hi world im here', ['world', 'im', 'here']) == True assert words_order('hi world im here', ['world', 'hi', 'here']) == False assert words_order('hi world im here', ['world', 'world']) == False assert words_order('hi world im here', ['country', 'world']) == False assert words_order('hi world im here', ['wo', 'rld']) == False assert words_order('', ['world', 'here']) == False print("Coding complete? Click 'Check' to earn cool rewards!")
10cf227b643a0e70977c365f4fc36693c390626b
Pradas137/Python
/Examen/figuras_recursive.py
2,956
4.03125
4
def printstack(n, indent=0): if n > 0: printstack(n-1, indent+1) print(' '*indent + '* '*n) #printstack(3) printstack(3,5) #printstack(3,1) """ def draw_triangle(n): if n == 0: return '' else: return ("*" * n + '\n') + draw_triangle(n - 1) def main(): num = int(input("Entra un numero: ")) triangle = draw_triangle(num) print(triangle) main() # pascal normal def pascal(n): if n == 1: return [1] else: line = [1] previous_line = pascal(n-1) for i in range(len(previous_line)-1): line.append(previous_line[i] + previous_line[i+1]) line += [1] return line print(pascal(6)) #fibonacci dentro de pascal def fib_pascal(n,fib_pos): if n == 1: line = [1] fib_sum = 1 if fib_pos == 0 else 0 else: line = [1] (previous_line, fib_sum) = fib_pascal(n-1, fib_pos+1) for i in range(len(previous_line)-1): line.append(previous_line[i] + previous_line[i+1]) line += [1] if fib_pos < len(line): fib_sum += line[fib_pos] return (line, fib_sum) def fib(n): return fib_pascal(n,0)[1] for i in range(1,10): print(fib(i)) #cuadricula de fibonacci memo = {0:0, 1:1} def fib(n): if not n in memo: memo[n] = fib(n-1) + fib(n-2) return memo[n] def fib_index(*x): "" "encuentra el número natural i con fib (i) == n" "" if len(x) == 1: # iniciado por el usuario # buscar índice comenzando desde 0 return fib_index(x[0], 0) else: n = fib(x[1]) m = x[0] if n > m: return -1 elif n == m: return x[1] else: return fib_index(m, x[1]+1) # código del ejemplo anterior con las funciones fib () y find_index () print(" index of a | a | b | sum of squares | index ") print("=====================================================") for i in range(15): square = fib(i)**2 + fib(i+1)**2 print(f"{i:12d}|{fib(i):6d}|{fib(i+1):9d}|{square:14d}|{fib_index(square):5d}") """ def dibujo_rombo(valor): result1 = [" " * (valor - i) + "*" * (i + i - 1) for i in range(1, valor + 1)] return "\n".join(result1 + list(reversed(result1[:-1]))) # Llamada al método y entrada de datos entrada_numero = int(input("Introduzca un número: ")) print(dibujo_rombo(entrada_numero)) def dibujo2(n): print("Pattern 1") for a1 in range (0,n): for a2 in range (a1): print("*", end="") print() for a1 in range (n,0,-1): for a2 in range (a1): print("*", end="") print() n = 3 dibujo2(n) def rectangulo(): rows =int(input("How many rows? ")) cols = int(input("How many columns? ")) cnt = 0 for r in range(rows): for c in range(cols): cnt += 1 strToPrint = "*" * cnt cnt = 0 print(strToPrint) rectangulo()
2cb30a07cc8413bc72d12f4e1f7e9e34247ce9d2
Demoleas715/PythonWorkspace
/Notes/DistanceTable.py
161
3.609375
4
''' Created on Oct 8, 2015 @author: Evan ''' m=1 print("%10s %20s" % ("Mile:", "Kilometer:")) while m<10: k=1.609*m print("%10d %20f" % (m, k)) m+=1
5a25a910a2690359e89f937908a27940785d5a10
amrinder07/CAP930Autumn
/tuple.py
222
3.8125
4
#Tuples are immutable, store heterogeneous data me=("amrinder","male",23) print(me) print(me[1]) print(len(me)) print(me[:3]) print("male" in me) a1=123,'abc',69.69 print(a1) a,b,c=a1 #unpacking print(b)
e16c41fb112c8f763b123b352598906ca11915a3
MadWookie/Survivor-Bot
/utils/utils.py
278
3.765625
4
def wrap(to_wrap, wrap_with, sep=' '): return f"{wrap_with}{sep}{to_wrap}{sep}{wrap_with}" def unique(it, key): new = [] added = [] for i in it: k = key(i) if k not in added: new.append(i) added.append(k) return new
f07678c16dc8ecbea9bc0e114f3c17f54e41a6ce
from0to100/guess_num
/guess_answer.py
705
3.9375
4
# 產生一組隨機整數1~100 # 讓使用者重複猜 # 告知結果比答案大/小 # 答對的話終止程式,並印出答對了 # 印出答了幾次,讓使用者自己輸入起始和結束值 import random start = input('請輸入起始值:') end = input('請輸入結束值:') start = int(start) end = int(end) x = random.randint(start, end) count = 0 print('請從', start, '~', end,'間猜一個數字') while True: count += 1 # count = count + 1 num = input('請輸入數字: ') num = int(num) if num == x: print('恭喜你答對了!答案是', x, '!') break elif num > x: print('再猜小一點') elif num < x: print('再猜大一點') print('你已經猜了', count, '次')
2f0c489ff3f8cb4527b4202610e873e96a471fc9
joshuaknight/myprograms.com
/game/passage.py
1,262
3.59375
4
import forest class Passage(object): def start(self): print "\nAfter,Which you enter a dark passage and near a bush you find a shotgun" print "\nYou Take the shotgun,and go along the passage" print "\nYou are tired from walking and see a shelter" print "\nYou Go and take rest in the Shelter,Where you meet a Oldman" print "\nWho advices you to go along the journey and not take rest and threatens to kill you" print "\n What do you do ?" print "\n Select a Choice" print "\n\t * 1.be rude and stay" print "\t * 2.be calm and leave" print "\t * 3.shoot him with shotgun" s = Passage() return s.input() def input(self): get_input = raw_input(">") if (get_input == '1'): print "\nthe old man shoots you from behind now you are dead " mypass = Passage() return mypass.death() elif (get_input == '2'): print "\nyou leave the shelter and pass out in the road and eaten by a tiger" mypass = Passage() return mypass.death() elif (get_input == '3'): print "\nyou shoot him and take rest in the shelter" myforest = forest.Forest() myforest.start() else: print "Try again" mypass = Passage() return mypass.input() def death(self): print "Try Again !!!" print "=" * 50
da482ab10a752cd0e055843318f81877b92c6f16
TheoWckr/TaxiSolver
/brutforce_algorythm.py
425
3.515625
4
import math import random import gym env = gym.make('Taxi-v3') epis = 1 turn = 0 allR = 0 for i in range(epis): wait = True r = 0 while(wait) : s = env.reset() next_move = random.randint(0,5) s1, r, d, _ = env.step(next_move) if d == True: print('Won') wait = False; turn += 1 allR += r print("End") print(turn) print(allR)
1a9c2695fd3f195efd29be801ff73d4cd185f6e4
Dinaim/Week3-task9
/task9.py
501
4.0625
4
# Напишите функцию которая принимает число 'N' и # возвращает квадраты всех натуральных чисел кроме числа 'N', в порядке возрастания # например если число 'N' = 4 ,то должен выйти список из чисел: 0,1,4,9 def Number_N(): a = int(input()) new_list = [] for num in range(a): new_list.append(num**2) print(new_list) Number_N()
9587cd8cb1feaa250856098b0fb048aeea8b1489
chathuraw/slbiobot
/scripts/inserter
718
3.734375
4
#!/usr/bin/env python # This script reads a list of twitter screen names from NEW_FILE and # populates them in USER_LIST_FILE if they're missing there import os USER_LIST_FILE='users.txt' NEW_FILE='new.txt' fh = open(USER_LIST_FILE, 'r') fnew = open(NEW_FILE, 'r') orig=[] while 1: name = fh.readline().strip() if not name: break orig.append(name.lower()) _ = fh.readline() fh.close() fh = open(USER_LIST_FILE, 'a') count = 0 while 1: name = fnew.readline().strip().lower() if not name: break if name in orig: print "%s is already there" % name else: fh.write("%s\n-\n" % name) count += 1 print "%d total new entries" % count fh.close() fnew.close()
9e1a9b3f57c9dab0c5a1657216c5e041f055a051
tjatn304905/algorithm
/APS/6.Queue/queue.py
931
4.125
4
class Queue: def __init__(self): self.data = [] def enqueue(self, elem): self.data.append(elem) def dequeue(self): return self.data.pop(0) def is_empty(self): return not bool(len(self.data)) # 삭제 없이 단순히 맨 앞의 data 값을 리턴 def get_front(self): if self.is_empty(): return None else: return self.data[0] # 삭제 없이 단순히 맨 뒤의 data 값을 리턴 def get_rear(self): if self.is_empty(): return None else: return self.data[-1] q = Queue() q.enqueue(1) # None, q.data => [1] print(q.data) q.enqueue(2) # None, q.data => [1, 2] print(q.data) print(q.is_empty()) print(q.get_front()) # 1 print(q.get_rear()) # 2 q.dequeue() # 1, q.data => [2] print(q.data) q.dequeue() # 2, q.data => [] print(q.data) print(q.is_empty()) print(q.get_rear())
1fad13d7b9ceabf329cbc0f37ee11c7fb69ef3a6
elsud/homework-repository
/homework12/models.py
8,076
3.671875
4
"""Creating dabase main.db using SQLAlchemy and creating tables homework, homework_results, students, teachers in it. Also start session which should be closed. """ import datetime from sqlalchemy import ( Column, DateTime, ForeignKey, Integer, Interval, String, create_engine, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker engine = create_engine("sqlite:///homework12/main.db", echo=True) Session = sessionmaker(bind=engine) Base = declarative_base() class Homework(Base): """Class with text of homework and deadline. An instance of that class is created by teacher. It has references to teacher who create it and homework_result. :param teacher: instance of Teacher who created homework :type teacher: Teacher :param text: text of homework task :type text: str :param deadline: deadline for homework in days, it will be converted to timedelta :type deadline: int """ __tablename__ = "homeworks" id = Column(Integer, primary_key=True) text = Column(String) deadline = Column(Interval) created = Column(DateTime) teacher_id = Column(Integer, ForeignKey("teachers.id")) teacher = relationship("Teacher", back_populates="homeworks") results = relationship("HomeworkResult", back_populates="homework") def __init__(self, teacher: "Teacher", text: str, deadline: int): self.teacher = teacher self.text = text self.deadline = datetime.timedelta(days=deadline) self.created = datetime.datetime.now() def __repr__(self) -> str: """String representation for Homework. :return: the text and name of the teacher :rtype: str """ return f"Homework '{self.text}' from {self.teacher}" def is_active(self) -> bool: """Checking if homework can be done or it's too late. :return: can homework be done or not :rtype: bool """ return datetime.datetime.now() < self.deadline + self.created class HomeworkResult(Base): """Class with solution of homework. It is created by teacher after he checks solution of student. :param student: instance of Student whose solution it is :type student: Student :param homework: instance of Homework to which there's solution :type homework: Homework :param solution: solution of homework :type solution: str """ __tablename__ = "homeworkresults" id = Column(Integer, primary_key=True) author_id = Column(Integer, ForeignKey("students.id")) author = relationship("Student", back_populates="homework_results") homework_id = Column(Integer, ForeignKey("homeworks.id")) homework = relationship("Homework", back_populates="results") solution = Column(String) created = Column(DateTime) def __init__(self, student: "Student", homework: "Homework", solution: str): self.author = student self.homework = homework self.solution = solution self.created = datetime.datetime.now() def __repr__(self) -> str: """String representation for HomeworkResult. :return: text of the homework, name of the student and text of the solution :rtype: str """ return f"Solution for {self.homework.text}: {self.solution}" class Student(Base): """Class to represent student. Has first_name and last_name. Student can do homework :param first_name: first name of the student :type first_name: str :param last_name: last name of the student :type last_name: str """ __tablename__ = "students" id = Column(Integer, primary_key=True) first_name = Column(String) last_name = Column(String) homework_results = relationship("HomeworkResult", back_populates="author") def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name def __repr__(self) -> str: """String representation of the Student instance. :return: first name and last name :rtype: str """ return f"{self.first_name} {self.last_name}" def do_homework(self, homework: "Homework", solution: str) -> None: """Doing homework if it's not deadline and giving it to the teacher to check it. :param homework: an instance of Homework to do :type homework: Homework :param solution: solution for homework :type solution: str """ if not isinstance(homework, Homework): raise TypeError("You gave a not Homework object") if not homework.is_active(): raise DeadlineError("You are late") homework.teacher.check_homework(self, homework, solution) class Teacher(Base): """Class to represent teacher. Has first_name and last_name. Teacher can create homework and check solutions. :param first_name: first name of the teacher :type first_name: str :param last_name: last name of the teacher :type last_name: str """ __tablename__ = "teachers" id = Column(Integer, primary_key=True) first_name = Column(String) last_name = Column(String) homeworks = relationship("Homework", back_populates="teacher") def __init__(self, first_name: str, last_name: str): self.first_name = first_name self.last_name = last_name def __repr__(self) -> str: """String representation of the Teacher instance. :return: first name and last name :rtype: str """ return f"{self.first_name} {self.last_name}" def create_homework(self, text: str, deadline: int) -> Homework: """Creating Homework object and adding it to the table homework without commiting. :param text: text of the homework type text: str :param deadline: count of the days during which homework can be done :type deadline: int :return: an instance of Homework :rtype: Homework """ new_hw = Homework(self, text, deadline) session.add(new_hw) return new_hw @staticmethod def check_homework(student: "Student", homework: "Homework", solution: str) -> bool: """Checking if the length of solution is more than 5 symbols and adding HomeworkResult to the table without commiting if it's True. :param student: the student who is an author of the solution to check :type student: Student :param homework: the homework to check solution to it :type homework: Homework :param solution: the solution of the homework to check :type solution: str :return: boolean if this is a new solution and if its length is more than 5 symbols :rtype: bool """ if len(solution) > 5: is_exist = ( session.query(HomeworkResult) .filter( HomeworkResult.homework == homework, HomeworkResult.solution == solution, ) .all() ) if not is_exist: session.add(HomeworkResult(student, homework, solution)) return True return False @classmethod def reset_results(cls, homework: "Homework" = None) -> None: """Deleting solutions for given homework from table or clearing all homework_results table without commiting. :param homework: homework solutions for which should delete :type homework: Homework or None """ if homework: session.query(HomeworkResult).filter( HomeworkResult.homework == homework ).delete() else: session.query(HomeworkResult).delete() class DeadlineError(Exception): """Exception which raises when student try to do homework after deadline""" session = Session() if __name__ == "__main__": Base.metadata.create_all(engine) session.close()
c8231fdd48c7bc221dea3980f9fff5801760325a
matuse/PythonKnights
/Ch13/test.py
176
3.703125
4
import string line = "I! want. to, eat# some@ and$ then% some^ please?" for word in line.split(): print word.strip(string.punctuation).lower()
9bf6e9ef3f7487815562455940b630e76b3cf752
xcrema/python_workspace
/Input print Sum of three numbers/untitled16.py
318
3.875
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 8 11:25:04 2020 @author: Achyut Statement Write a program that takes three numbers and prints their sum. Every number is given on a separate line. Example input 2 3 6 Example output 11 """ a = (input()) b = (input()) c = (input()) print(int(a) + int(b) + int(c))
5a036f5bb1906fa46344e96a09a3052676f1e971
andrewteece/Data-Structures
/mbox.py
279
3.625
4
fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if not line.startswith('From ') :continue words = line.split() email = words[1] pieces = email.split('From') print pieces[0] #print "There were", pieces,"lines in the file with From as the first word"
a3910bf7f2bed827710c108209129e990e38b35c
Xinyuan-wur/algorithms-in-bioinformatics
/graphs/assignment3_skeleton.py
3,621
3.90625
4
#!/usr/bin/env python """ Author: Xinyuan Min Student nr: 950829573070 Script to: """ # Import statements # Implement your functions here def is_eulerian(graph): # use set() to get every distinct node in graph vertices = set() for key_value in graph.items(): vertices.add(key_value[0]) for value in key_value[1]: vertices.add(value) count_in_out = {} for vertex in vertices: # the first element of value of a vertex indicates its indegree # similarly, the second element represents a vertex's outdegree count_in_out[vertex] = [0, 0] # the length of value(list) of each node(key) is the outdegree of a vertex for node in graph: outdegree = len(graph[node]) count_in_out[node][1] = outdegree # indegree is the number of a node occurs as a value of other nodes for connected_node in graph[node]: count_in_out[connected_node][0] += 1 # a connected graph is Eulerian if all vertices is balanced eulerian = True for vertex in count_in_out: indegree = count_in_out[vertex][0] outdegree = count_in_out[vertex][1] if indegree != outdegree: eulerian = False break return eulerian, count_in_out def has_eulerian_path(graph): count_in_out = is_eulerian(graph)[1] semi_balanced = 0 eulerian_path = False for vertex in count_in_out: indegree = count_in_out[vertex][0] outdegree = count_in_out[vertex][1] if abs(indegree - outdegree) == 1: semi_balanced += 1 if semi_balanced <= 2: eulerian_path = True if eulerian_path == True: print('This graph has a Eulerian path') else: print('This graph does not have a Eulerian path') return eulerian_path def get_edges(graph): """Return a list of strings which contains all the edges in the graph :param a: :param node: :return: """ edges = [] for vertex in graph.keys(): connected_nodes = graph[vertex] for node in connected_nodes: edges.append(str(vertex + node)) return edges def get_next_edge(graph, node): candidate_nodes = graph[node] return node + candidate_nodes[0] unused_edges = get_edges(graph_822) used_edges = [] def find_eulerian_cycle(graph, unused_edges, node, used_edges): next_node = graph[node][0] choosen_edge = get_next_edge(graph, node) used_edges.append(choosen_edge) unused_edges.remove(choosen_edge) if len(graph[node]) == 1: graph.pop(node) else: graph[node].remove(next_node) if next_node != 'A': return find_eulerian_cycle(graph, unused_edges, next_node, used_edges) else: return used_edges, unused_edges,graph if __name__ == "__main__": # GRAPH FROM FIG 8.22 graph_822 = {'A':['B'],'B':['C'],'I':['H'],'H':['F'],'F':['G','E'],\ 'C':['I','J'],'G':['A'],'E':['J'],'J':['F','D'],'D':['C']} # A SLIGHTLY BIGGER GRAPH, NEEDED FOR Q8 bigger_graph = {1:[2], 2:[3], 3:[7,1],\ 4:[5,10],5:[6],6:[7],7:[8,9,11],\ 8:[4],9:[3,4],\ 10:[9],11:[12],12:[7]} # SPECTRUM FROM FIG 8.20 s = ['ATG','TGG','TGC','GTG','GGC','GCA','GCG','CGT'] # Question 1 if is_eulerian(graph_822)[0] == True: print('this graph is Eulerian') else: print('This graph is not Eulerian') # Question 2 has_eulerian_path(graph_822) # Put function calls, print statements etc. to answer the questions here # When we run your script we should see the answers on screen (or file)
6936bc798f8d1ad679ca75dbaf7fda90f5e09b77
MarkGasse/Huiswerk-TCTI-V2ALDS1-11_2018-
/week5/week5_1.py
6,407
3.5
4
class myqueue(list): def __init__(self, a=[]): list.__init__(self, a) def dequeue(self): return self.pop(0) def enqueue(self, x): self.append(x) class Vertex: def __init__(self, data): self.data = data def __repr__(self): # voor afdrukken return str(self.data) def __lt__(self, other): # voor sorteren return self.data < other.data import math INFINITY = math.inf # float("inf") def vertices(G): return sorted(G) def edges(G): return [(u, v) for u in vertices(G) for v in G[u]] v = [Vertex(i) for i in range(8)] G = {v[0]: [v[4], v[5]], v[1]: [v[4], v[5], v[6]], v[2]: [v[4], v[5], v[6]], v[3]: [v[7]], v[4]: [v[0], v[1], v[5]], v[5]: [v[1], v[2], v[4]], v[6]: [v[2], v[1]], v[7]: [v[3]]} G2 = {v[0]: [v[4], v[5]], v[1]: [v[4], v[5], v[6]], v[2]: [v[4], v[5], v[6]], v[4]: [v[0], v[1], v[5]], v[5]: [v[1], v[2], v[4]], v[6]: [v[2], v[1]]} G3 = {v[0]: [v[4], v[5]], v[1]: [v[4], v[6]], v[2]: [ v[5]], v[3]: [v[7]], v[4]: [v[0], v[1]], v[5]: [v[0], v[2]], v[6]: [v[1]], v[7]: [v[3]]} G4 = {v[0]: [v[1], v[3]], v[1]: [v[0], v[2]], v[2]: [ v[1], v[3], v[4]], v[3]: [v[0], v[2]], v[4]: [v[2], v[5], v[6]], v[5]: [v[4], v[6]], v[6]: [v[4] , v[5], v[7]], v[7]: [v[6]]} G5 = {v[0]: [v[1], v[2]], v[1]: [v[0], v[3]], v[2]: [ v[0], v[3]], v[3]: [v[1], v[2], v[4], v[6]], v[4]: [v[3], v[5], v[6], v[7]], v[5]: [v[4], v[6]], v[6]: [v[3], v[4] , v[5], v[7]], v[7]: [v[4], v[6]]} G6 = {v[0]: [v[2]], v[2]: [v[1], v[4]], v[4]: [v[2], v[6]], v[6]: [v[4]]} print("vertices(G):", vertices(G)) print("edges(G):", edges(G)) def clear(G): for v in vertices(G): k = [e for e in vars(v) if e != 'data'] for e in k: delattr(v, e) def BFS(G, s): V = vertices(G) s.predecessor = None s.distance = 0 for v in V: if v != s: v.distance = INFINITY # v krijgt het attribuut 'distance' q = myqueue() q.enqueue(s) # print("q:", q) while q: u = q.dequeue() for v in G[u]: if v.distance == INFINITY: # v is nog niet bezocht v.distance = u.distance + 1 v.predecessor = u # v krijgt het attribuut 'predecessor' q.enqueue(v) # print("q:", q) BFS(G, v[1]) def show_tree_info(G): print('tree:', end=' ') for v in vertices(G): print('(' + str(v), end='') if hasattr(v, 'distance'): print(',d:' + str(v.distance), end='') if hasattr(v, 'predecessor'): print(',p:' + str(v.predecessor), end='') print(')', end=' ') print() show_tree_info(G) def show_sorted_tree_info(G): print('sorted tree:') V = vertices(G) # V = [v for v in V if hasattr(v,'distance') and hasattr(v,'predecessor')] V.sort(key=lambda x: (x.distance, x.predecessor)) d = 0 for v in V: if v.distance > d: print() d += 1 print('(' + str(v) + ',d:' + str(v.distance) + ',p:' + str(v.predecessor), end='') print(')', end=' ') print() #show_sorted_tree_info(G) def path_BFS(G, u, v): BFS(G, u) a = [] if hasattr(v, 'predecessor'): current = v while current: a.append(current) current = current.predecessor a.reverse() return a print("path_BFS(G,v[1],v[7]):", path_BFS(G, v[1], v[7])) clear(G) print("\n------Opdracht week5_1------\n") def is_connected(G): notes = vertices(G) for pos in notes: check = path_BFS(G,v[0],pos) if check == []: return False return True print("Should be False: " , is_connected(G)) print("Should be True: " , is_connected(G2)) print("\n----------------------------") print("\n------Opdracht week5_2------\n") def no_cycles(G): seen = [] parent = -1 for i in vertices(G): for pos in G[i]: if pos in seen and parent == pos: return False else: seen.append(pos) parent = i return True print("should be True: ",no_cycles(G3)) print("should be False: ",no_cycles(G)) print("\n----------------------------") print("\n------Opdracht week5_3------\n") def get_bridges(G): bridges = [] E = edges(G) for edge in E: G[edge[0]].remove(edge[1]) G[edge[1]].remove(edge[0]) BFS(G,edge[0]) for v in vertices(G): if v == edge[1]: if v.distance == INFINITY: bridges.append(edge) G[edge[0]].append(edge[1]) G[edge[1]].append(edge[0]) return bridges #print("bridges: [(2,4),(4,2),(6,7),(7,6)] == ", get_bridges(G4)) print("\n----------------------------") print("\n------Opdracht week5_4------\n") def is_strongly_connected(G): reverse = {} if not is_connected(G): return False for pos in vertices(G): reverse[pos] = [] for pos in vertices(G): for value in G[pos]: reverse[value].append(pos) if not is_connected(reverse): return False return True print("should be False: ", is_strongly_connected(G)) print("should be True: ", is_strongly_connected(G2)) print("\n----------------------------") print("\n------Opdracht week5_5------\n") def is_Euler_graph(G): notes = vertices(G).copy() for i in notes: if int(str(i)) % 2 is not 0: return False return True print("Should be False: ", is_Euler_graph(G)) print("Should be True: ", is_Euler_graph(G6)) def get_Euler_circuit(G,s): C = list() circuit = list() C.append(s) circuit.append(s) while C: current = C.pop() for neighbor in G[current]: if len(C) > 0: continue elif (current,neighbor) in get_bridges(G): if len(G[current]) == 1: t = neighbor else: continue else: t = neighbor circuit.append(t) C.append(t) G[t].remove(current) G[current].remove(t) return circuit print(get_Euler_circuit(G5,v[0])) print("\n----------------------------")
f56e46a1e3603481980ac2c51d95663ef2b778a5
sujiea/hackerrank-codility
/cba.py
379
3.65625
4
import re def solution(S): # write your code in Python 3.6 print(re.search(r"(?!$)a*b*", S).groups(0)) if re.match(r"(?!$)a*b*", S).span()[1] == len(S): return True else: return False print(solution("aabbb")) print(solution("a")) print(solution("b")) print(solution("aa")) print(solution("bb")) print(solution("abba")) print(solution("ba"))
0ff1842d2cef8e1189d217725783094a7f56bcf7
rahil1303/dictionary_usingPython
/3_Update_and_Insert.py
173
4.0625
4
### Insert myDict = {"name": : "Eddy", "age" : 26} myDict['age'] = 27 print(myDict) ### Update myDict = {'name' : 'Eddy', 'age' : 26} myDict['city'] = London print(myDict)
32bef534ae031cddd4b94bc12aee2860bd2decb7
kashyap79/Python_beginner
/one.py
170
3.578125
4
print("Hello World") def add(a,b): return a+b def sub(a,b): return a-b def multiply(a,b): return a*b print"Bye World" def square(x): return x**2
90bb69bd2731ffdabc4b2c1ed951856be5a68d77
arun777888/classes
/while loop.py
2,594
4.03125
4
#reverse num ''' num= int(input("enter a number =")) num1=num rev= 0 while(num!=0): rem=num%10 rev=rev*10+rem num=num//10 print(rev) if num1==rev: print('num is pallindrome') ''' # factorial of num ''' num= int(input("enter a number =")) fact=1 while (num>0): fact=fact*num print(fact) num=num-1 ''' # fibonacci series ''' x=0 y=1 count=1 num= int(input("enter a number ")) while (count<=num): sum=x+y print(sum,end=' ') x=y y=sum count= count+1 ''' # table ''' i= 1 table =1 num= int(input(' enter num = ')) while(i<=10): table= num*i print(table) i=i+1 ''' # leap year ''' year = int(input('enter a year')) if year%4==0: if year%100==0: if year%400==0: print(year,' is leap year') else: print(year,' is not a leap year') else: print(year,' is leap year') else: print(year,' is not a leap year') ''' # nested while ''' table = int(input('enter a num =')) while table<6: print('tables of',table) mul = 1 while mul<=10: print(table,'*',mul,'=',table*mul) mul+=1 print() table+=1 ''' # using for loop ''' table =1 for i in range(4,8): for j in range(1,11): print(i,'*',j,'=',i*j) ''' # beak, continue ''' i=1 while i<10: if i ==5: break print(i) i=i+1 ''' i=10 while i>0: # i=i-1 if i ==5: continue print(i) i=i-1 ''' i =1 while i<20: if i %2 ==0: pass else: print(i) i=i+1 ''' # sum of digits using for loop ''' total = 0 num = input('enter a num = ') for i in range( 0, len(num)): total=total + int(num[i]) print(total) ''' # sum of digits using while loop ''' num= int(input('enter a number')) total=0 while num!=0: total = total + num%10 num = num//10 print(total) ''' # sum of natural num using while loop ''' total = 0 i=1 num = int(input('enter a number')) while i<num: total = total+i i=i+1 print(total) ''' # nested while ''' num1 = int(input('enter a num =')) num2 = int(input('enter a num =')) while num1<=num2: #print('tables of',num1) mul = 1 while mul<=10: print(num1,'*',mul,'=',num1*mul) mul+=1 print() num1+=1 '''
95e269801b0891dcaa05229255ae828f83118d81
rprtest/LearnPython
/report_generator.py
2,419
3.75
4
# i2p - Homework - 9 - File Manipulations and Exceptions # By: Roopa Prakash, submitted on: 07/04/2016 import csv from datetime import date def main(): # Sets to store unique values of oc member, region and office data_oc_member = set() data_region = set() data_office = set() # Open the contributions.csv and read it data_file = open('contributions.csv', 'rU') reader = csv.reader(data_file) # list to store all rows in the contributions.csv all_data = [] # store each row in file into all_data list, store unique values in region, oc member and office in sets for row in reader: all_data.append(row) if row[1] != 'OC_MEMBER': data_oc_member.add(row[1]) if row[2] != 'REGION': data_region.add(row[2]) if row[3] != 'OFFICE': data_office.add(row[3]) # close the data file after reading and storing data_file.close() # Milestone 1 and 2 - print number of unique values and the sorted values themselves print 'Number of unique values in REGION: ' + str(len(data_region)) s = ', ' print s.join(sorted(data_region)) print '' print 'Number of unique values in OC_MEMBER: ' + str(len(data_oc_member)) print s.join(sorted(data_oc_member)) print '' print 'Number of unique values in OFFICE: ' + str(len(data_office)) print s.join(sorted(data_office)) print '' # Milestone 3 and 4; list to store data to be written in results.csv write_data = [] # For each item in unique set of data_oc_member get the num_contrib, mean_contrib for item in data_oc_member: num_contrib = 0 mean_contrib = 0.0 for row in all_data: if item == row[1]: num_contrib += 1 mean_contrib = mean_contrib + float(row[4]) / num_contrib print 'OC Member: ' + str(item) print 'Num Contributions: ' + str(num_contrib) print 'Mean Contribution: ' + str(mean_contrib) print '' # appending the oc roll up calculation in write_data along with today's date write_data.append([item, num_contrib, mean_contrib, date.today().strftime('%m/%d/%Y')]) # Sort write_data and write it to results.csv write_data = sorted(write_data) write_data.insert(0, ['oc_member', 'num_contribs', 'mean_contribs', 'date']) write_data_file = open('results.csv', 'w') writer = csv.writer(write_data_file) writer.writerows(write_data) write_data_file.close() if __name__ == '__main__': main()
4dcac4cd194c25cb68a0d1aa5e4df24e6c735ef2
monkeybuzinis/Python
/6.string/14.py
229
3.84375
4
#14 s=input("write your name: ") new='' for i in range (1,len(s)): if(s[i-1]==" " and s[i].isalpha()): new+=s[i].upper() else: new+=s[i] if(s[0].isalpha): print(s[0].upper()+new) else: print(new)
45d1fcc08aa1ef9edfdab599bafc095f569d11e0
AlexLinGit/SICP-and-Other-Code
/Python Crash Course Exercises/chapter 9 - classes/electric_car_m.py
1,527
4.125
4
from cars import Cars class ElectricCar(Cars): """Represents aspects specific to electric cars""" def __init__(self, make, model, year): """Initializes attributes of the parent class""" super().__init__(model, make, year) self.battery = Battery() def fill_gas_tank(self): """Electric cars don't use gas""" print("NO GAS REQUIRED!") class Battery(): """Represents a battery""" def __init__(self, battery_size=70): """Initializes battery size""" self.battery_size = battery_size self.plus_kwh = 0 def read_battery(self): """Prints a description of the battery""" print("Battery wattage: " + str(self.battery_size) + "-kwh") def upgrade_battery(self, plus_kwh): """Upgrades the battery with number of kwh""" self.battery_size = self.battery_size + plus_kwh def car_range(self): """Prints a approximate range which the car can drive""" if self.battery_size <= 70: car_range = "from 150 to 200 miles" elif self.battery_size <= 85: car_range = "from 200 to 300 miles" elif self.battery_size <=95: car_range = "above 300 miles" elif self.battery <= 0: car_range = "This doesn't move" else: car_range = "unknown" if car_range == 'unknown': print("The range of this car is undetermined") elif car_range == "this doesn't move": print(car_range) else: print("\nThis car can go " + car_range + " away on a single charge of its ") print(str(self.battery_size) + "-kwh battery.")
0efa684de14be0d88a3c9f73735586dae2b039c4
iamzin/Study-Algorithm
/python/programmers/반복문/[12981_반복문_영어끝말잇기_1]천재승.py
544
3.578125
4
def solution(n, words): word_list=[] for i in range(0,len(words)): # 번호 number=i%n+1 # 차례 cnt=i//n+1 # 탈락조건 if len(words[i])==1 or (i>0 and words[i-1][-1]!=words[i][0]) or (words[i] in word_list): return [number,cnt] # 새로운 단어가 나오면 리스트에 넣어준다. word_list.append(words[i]) # print(word_list) return [0,0] print(solution(3,["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"]))
302fa80e70577b1208f230be138e116d4afb193f
dhalik/Econ102Quiz
/encode.py
1,446
3.53125
4
import struct; # Needed to convert string to byte import sys; import os.path; if (len(sys.argv) != 2): print("Run this utility as python encode.py <questionFile.xml>") sys.exit(0) filename = sys.argv[1] if (not os.path.isfile(filename)): print("File passed does not exist or is unusable") sys.exit(0) f = open(sys.argv[1],"rb") # Open the file in read binary mode s = "#ifndef __ORG__H__ \n #define __ORG__H__ \n char question_data[] = {" b = f.read(1) # Read one byte from the stream db = struct.unpack("b",b)[0] # Transform it to byte h = hex(db) # Generate hexadecimal string s = s + h; # Add it to the final code b = f.read(1) # Read one byte from the stream while b != "": s = s + "," # Add a coma to separate the array db = struct.unpack("b",b)[0] # Transform it to byte h = hex(db) # Generate hexadecimal string s = s + h; # Add it to the final code b = f.read(1) # Read one byte from the stream s = s + ",0x00" # Close the bracktes s = s + "}; \n #endif" # Close the bracktes f.close() # Close the file # Write the resultan code to a file that can be compiled fw = open("questionrepo.h","w"); fw.write(s); fw.close();
e81f88238850c81caa1f5979de7859bf837a072f
HBinhCT/Q-project
/hackerrank/Data Structures/Truck Tour/solution.py
788
3.875
4
#!/bin/python3 import os # # Complete the 'truckTour' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY petrolpumps as parameter. # def truckTour(petrolpumps): # Write your code here pump = 0 check = 0 for i in range(len(petrolpumps)): amount, distance = petrolpumps[i] check += amount - distance if check < 0: pump = i + 1 check = 0 return pump if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) petrolpumps = [] for _ in range(n): petrolpumps.append(list(map(int, input().rstrip().split()))) result = truckTour(petrolpumps) fptr.write(str(result) + '\n') fptr.close()
9bd186c344342ee48762c8da440b7f23c2214751
binchen15/python-tricks
/collections_demo/demo_OrderedDict.py
451
4.34375
4
from collections import OrderedDict #dict subclass that remembers the order in which that keys were first inserted. # order is not sort. # it can be used in conjunction with sorting to make a sorted dictionary d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} print("order by name") od = OrderedDict(sorted(d.items(), key=lambda x : x[0])) print(od) print('order by values') od = OrderedDict(sorted(d.items(), key=lambda x : x[1])) print(od)
a8f3afc912b923234b89973728a4fb03bfd276d5
best738/automate-your-page
/Project 2 Notes/Project_2_python.py
3,100
4.15625
4
def generate_concept_html(concept_title, concept_description): html_text_1 = """ <div class="concept"> <div class="concept_title"> """ + concept_title html_text_2 = """ </div> <div class="concept_description"> <p> """ + concept_description html_text_3 = """ </p> </div> </div>""" full_html = html_text_1 + html_text_2 + html_text_3 return full_html def make_html (concept): concept_title = concept[0] concept_description = concept[1] return generate_concept_html(concept_title, concept_description) programming_concepts = [['Python', "Python is a programming language to tell the computer what to do. Python code is input into another program (Python interpreter) that follows instructions in your code and it does that by following instruction in its own code. This is all done through you web browser. It uses very specific grammer rules, although much more specific than human language. This allows for unambiguous interpretations"], ['Variables and Strings', 'Variables give names to values. In other words its an assignment statement. An example would be <span class="code">this variable = 4</span>. The equals (=) sign does not mean equal as in mathematics, but rather means to take the value of. Variables improve code readability, give programmers a way to store values, and give a way to change a value easily. A string is a sequence of characters. For example <span class="code">"4" + "6"</span> would result in <span class="code">"46"</span>, not <span class="code">"10"</span>. Note the <span class="code">+</span> concatenates.'], ['Procedures', 'Procedures are also called functions. Procedures take an input(s), does something with the input, then produces and output. Procedures start with a line of code with the keyword <span class="code">def</span> and a function name followed by parameters in parentheses. Then we write what to do with input.'], ['If and While Statements', 'A Boolean Value outputs a True or False. For example,<span class="code">print 2 > 3</span> would produce an output of False. Other operators are <span class="code">!=</span> for not equal and <span class="code">==</span> is equal to. <span class="code">if</span> statements are used to make comparisons. <span class="code">While</span> statements create loops and dont stop running until a certain event occurs.'], ['Lists and For Loops', 'Lists can can contain strings, numbers, numbers and strings, and other lists. Lists can be mutated, meaning we can change its value after it is created. We can also append to a list, which adds an element to the end of the loop. The plus (+) operator essentially concatentes two list to create a new list. For loops loop through the elements in the list. Length (len) determines the number of characters in a string or the number of elements in a list.'] ] def make_html_for_all_concepts (all_concepts): html = "" for concept in all_concepts: concept_html = make_html (concept) html = html + concept_html return html print make_html_for_all_concepts (programming_concepts)
5d2f625c5929ceb77aa801770935878a3b906d91
mnmhouse/php_scraping
/scrapy_web/scrapy.py
1,227
3.578125
4
from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import sys url = "http://www.pythonscraping.com/pages/warandpeace.html" # # import re # # pages = set() # def getLinks(pageUrl): # global pages # html = urlopen('http://www.sina.com') # bsObj = BeautifulSoup(html) # for link in bsObj.findAll("a",href=re.compile("^(/wiki/)")): # if 'href' in link.attrs: # BeautifulSoup 的使用 # html = urlopen("http://www.sina.com") # print(BeautifulSoup(html).h1) # Error handle def getText(url): try: html =urlopen(url) except HTTPError as e: print(e) return None try: bsObj = BeautifulSoup(html) title = bsObj.body.h1 except AttributeError as e: print(e) return None return title title = getText("http://www.pythonscraping.com/exercises/exercise1.html") if title == None: print("Title could not find") else: print(title) # BeautifulSoup Find all,findAll def iteratorText(): htmlAll = urlopen(url) bsObject = BeautifulSoup(htmlAll) listtest = bsObject.findAll("span",{"class":"red"}) for item in listtest: print(item.getText()) iteratorText()
417320d54018187b4eb91097abe43022a96f8813
xiaxiaochao1103/test_demo
/study_ex/20200123.py
10,940
4.125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- # 86、找到某dict种包含指定key的dict.根据drink找到他的上级dict,即eat,并返回eat的内容 # dict_data = { # "name": "smith", # "age": 22, # "hobby": { # "read": "book", # "watch": "video", # "eat": { # "food": "中国菜", # "drink": "water", # }, # "play": { # "game": "football", # "game1": "basketball" # } # }, # "school": { # "a": 1, # "b": 2, # "c": 3, # "d": 4 # } # } # # # def find_some_dict(d, key, result=None): # if result is None: # result = [] # for k, v in d.items(): # if k == key: # result.append(v) # else: # print(result) # if isinstance(v, dict): # find_some_dict(v, key, result) # return result # # # print(find_some_dict(dict_data, "eat")) # 87、递归倒序打印1-10 # def print_num(n): # if n >= 1: # print(n) # print_num(n-1) # # # print_num(10) # 88、递归升序打印1-10 # def print_num(n): # if n >= 1: # print_num(n-1) # print(n) # # # print_num(10) # 89、把你知道的所有变量类型做一个赋值操作 # a = 1 # b = 'a' # c = 1.5 # d = None # e = 1 + 5j # f = [1, 2, 3] # g = (1, 2, 3) # h = {'a': 1, 'b': 2} # i = set([1, 2, 3, 4]) # j = '' # k = True # 90、请基于数字类型,使用2个数字分别实现+ - * / % //的操作 # x = 4 # y = 2 # print(x+y) # print(x-y) # print(x*y) # print(x/y) # print(x % y) # print(x//y) # 91、将一个字符串"0",转换为数字类型,将1转换为数字类型 # a = "0" # print(int(a)) # # b = "1" # print(int(b), float(b)) # 92、读入一个数字,并判断是否正数,是的话打印“是正数!”,否则打印“不是正数” # num = int(input('请输入一个数字:')) # if num > 0: # print('是正数') # else: # print('非正数') # 93、 随机产生一个整数,1-100范围内 # import random # a = random.randint(1, 100) # print(a) # 94、 随机产一个小数,0-1内 # import random # a = random.random() # print(a) # 95、随机产生一个小数,1-100内 # import random # a = random.uniform(1, 100) # print(a) # 96、 随机产生一个字母,随机产生2个字母,随机产生3个字母。 # import random # # 随机产生一个字母 # word = chr(random.randint(97, 122)) # print(word) # # # 随机产生两个字母 # for i in range(2): # word = chr(random.randint(97, 122)) # print(word, end='') # print() # # 随机产生三个字母 # for i in range(3): # word = chr(random.randint(97, 122)) # print(word, end='') # 97、读入一个数字,判断是否奇数还是偶数。 # num = int(input('请输入一个数字:')) # if num % 2 == 0: # print('它是偶数') # else: # print('它是奇数') # 98、 输入10个数字,算一下累加和 # numbers = input('请输入10个数字(以空格分开):') # num = numbers.split(' ') # result = 0 # for i in num: # result += int(i) # # print(result) # 99、 使用ASCII码 输出小写26个字母,a-z # for i in range(97, 123): # print(chr(i), end="") # 100、使用ASCII码 输出大写26个字母,A-Z # for i in range(ord("A"), ord("Z") + 1): # print(chr(i), end="") # 101、使用ASCII码 输出大小写26个字母,a-zA-Z # for i in range(97, 123): # # print(chr(i), end="") # # print(chr(i - 32), end=" ") # 102、从列表中随机取一个元素 # import random # l = list(range(100)) # print(random.choice(l)) # 103、遍历一个列表[1,2,3,4,5,1],请判断列表里面是否有1,有的话打印find it,没有的话提示,没有1. # l = [2, 2, 3, 4, 5, 2] # for i in l: # if i == 1: # print("find it") # break # else: # print("not has 1") # 104、遍历一个字符串"abdfsasd",请判断列表里面是否有a,有的话打印find it,没有的话提示,没有"a" # s = "abdfsasd" # for v in s: # if v == "a": # print("find it") # break # else: # print("not has a") # 105、计算一个字符串"abdfsasd"有几个a # s = "abdfsasd" # print(s.count("a")) # 106、输入高考的5个成绩,700 # 以上,打印可以上清华大学了,600 - -700 # 打印,可以上重点大学了,500 - -600 # 可以上一本了,400 - 500, 打印可以上大专了,400 # 以下打印请重头再来。 # 107、从1遍历到10,计算有几个偶数 # count = 0 # for i in range(1, 11): # if i % 2 == 0: # count += 1 # print(count) # # 108、死循环从键盘输入内容,并打印,当输入“.”的时候退出循环 # while True: # cmd = input("请输入输入指令:") # if cmd == ".": # break # else: # print(cmd) # 109、列表[1, 3, 5, 7, 9], 请将之拼接为一个字符串。 # lis = [1, 3, 5, 7, 9] # print("".join([str(i) for i in lis])) # 110、将"13579"的字符串转换为一个列表 # string = "13579" # print(list(string)) # print([int(i) for i in list(string)]) # 111、将"13579"的字符串的数字求和一下 # string = "13579" # print(sum([int(i) for i in list(string)])) # 112、判断一个字符串是否包含非数字内容 # def is_digit_not_in(s): # for i in s: # if not i.isdigit(): # print("包含非数字内容") # return True # # # print(is_digit_not_in("1235d")) # 113、写一个函数,实现两个数相加,函数参数a, b # def add_num(a, b): # if isinstance(a, (int, float)) and isinstance(b, (int, float)): # return a + b # else: # print("参数错误") # return -1 # # # print(add_num(1, 4)) # print(add_num(1.3, 4)) # print(add_num(2, 4.5)) # print(add_num(2, "2")) # 114、判断一个四位的数字,是否可以被2和5同时整除,如果可以打印可以整除,否则打印不可以整除 # def divisible_2or5(s): # if isinstance(s, (int, float)): # if s % 2 == 0 and s % 5 == 0: # print("可以整除") # else: # print("不可以整除") # else: # print("参数错误") # # # divisible_2or5(10) # divisible_2or5(9) # divisible_2or5("10") # 115、随机生成一个4位长度的整数数字,判断是否同事包含1和0 # import random # s = "".join([str(random.randint(0, 9)) for i in range(4)]) # print(s) # if "0" in s and "1" in s: # print("同时包含1和0") # else: # print("未同时包含1和0") # # # random_number = random.randint(1000,9999) # print(random_number) # if "1" in str(random_number) and "0" in str(random_number): # print("True") # else: # print("False") # 116、生成一个随机的8位密码,要求4个字母和4数字 # import string # import random # random_list = [] # for i in range(4): # random_list.append(str(random.randint(0, 9))) # random_list.append(random.choice(list(string.ascii_letters))) # # random.shuffle(random_list) # print("".join(random_list)) # 117、求25这个数字可以整除的所有数字 # def divisible_list(num): # res = [] # for i in range(1, num+1): # if num % i == 0: # res.append(i) # return res # # # print(divisible_list(25)) # 118、 输入a, b, c三个数,求最大的那个 # a, b, c = 1, 2, 3 # # if a < b: # a, b = b, a # if a < c: # a, c = c, a # if b < c: # b, c = c, b # # print(a, b, c) # print(a) # 119、 随机生成一个1 - 10的整数,然后你输入一个值去比对,如果大了,打印大了,小了打印小了,等于则打印。 # import random # input_num = int(input("请输入一个1 - 10的整数:")) # random_num = random.randint(1, 10) # print(random_num) # if input_num > random_num: # print("大了") # elif input_num < random_num: # print("小了") # elif input_num == random_num: # print(random_num) # 120、 基于第一题,限定一下猜的次数不超过3次 # import random # for i in range(3): # input_num = int(input("请输入一个1 - 10的整数:")) # random_num = random.randint(1, 10) # print(random_num) # if input_num > random_num: # print("大了") # elif input_num < random_num: # print("小了") # elif input_num == random_num: # print(random_num) # 121、于第二题,打印一下一共猜了多少次。 # import random # count = 0 # for i in range(3): # input_num = int(input("请输入一个1 - 10的整数:")) # random_num = random.randint(1, 10) # count += 1 # print(random_num) # if input_num > random_num: # print("大了") # elif input_num < random_num: # print("小了") # elif input_num == random_num: # print(random_num) # # # print(count) # 122、生成一个列表["1a", "2b", "3c", "4d", "5e"] # res = [] # for i in range(5): # res.append(str(i + 1) + chr(97 + i)) # # print(res) # 123、生成一个列表["z1", "y2", "x3", "w4", "v5"] # res = [] # for i in range(5): # res.append(chr(122 - i) + str(i + 1)) # # print(res) # 124、将一个字符串的奇数坐标的字母拼成一个字符串。 # s = "1sdkjlj111" # print(s[1::2]) # 125、将一个字符串首字母、最后一个字母和中间字母,三个字符串拼成一个字符串。 # s = "abcde" # result_str = s[0] + s[len(s)//2] + s[-1] # print(result_str) # 126、将一个列表[1,2,3,4,5]每个元素值扩大10倍后,在每个元素后面加上“abc”三个字母放到列表里面。 # lis = [1, 2, 3, 4, 5] # for i in range(len(lis)): # lis[i] = str(lis[i] * 10) + "abc" # # print(lis) # 127、两个列表[1, 2, 3, 4, 5], ["a", "b", "c", "d", "e"],讲两个列表元素拼成一个字典,第一个列表元素做key, # list1 = [1, 2, 3, 4, 5] # list2 = ["a", "b", "c", "d", "e"] # data = {} # for i in range(len(list1)): # data[list1[i]] = list2[i] # # print(data) # 128、一个字典{1:"a",2:"b",3:"c"},拼成一个列表[1,"a",2,"b",3,"c"] # data = {1: "a", 2: "b", 3: "c"} # res = [] # for key, value in data.items(): # res.extend([key, value]) # # print(res) # 129、使用for循环生成一个二维列表,[[1, 2, 3], [4, 5, 6], [7, 8, 9]] # num = 1 # res = [] # for i in range(3): # temp_list = [] # for j in range(3): # temp_list.append(num) # num += 1 # res.append(temp_list) # # print(res) # 130、将列表中[[1, 2, 3], [4, 5, 6], [7, 8, 9]]的所有奇数进行求和 # def sum_odd(para, res=0): # for i in para: # if isinstance(i, int): # if i % 2 == 1: # res += int(i) # elif isinstance(i, (list, tuple)): # res += sum_odd(i) # return res # # # lis1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # lis2 = [[1, 2, 3, [1, [1, 3]]], [4, 5, 6, [1.0, (1,)]], [7, 8, 9]] # print(sum_odd(lis1)) # print(sum_odd(lis2))
8b30d86175b2eb7b9e0c757da4fb33aaf01d6360
alejamorenovallejo/retos-phyton
/Ejercicio/Retos/Reto2.py
2,132
3.859375
4
respuesta = "s" while respuesta == "s" or respuesta == "S" or respuesta == "si" or respuesta == "SI": #Declaracion de Variables cotizacion=[] suma = 0 #Solicitud NIT,Nombre y Valor for indice in range(5): nit = input("Ingrese el NIT: ") while nit == '': nit = input("Ingrese el NIT: ") nombre = input("Ingrese el Nombre: ") while nombre=='': nombre = input("Ingrese el Nombre: ") valor=int(input("Ingrese el Valor: ")) try: while (valor == 0) : valor = input("Escribe un Valor: ") except: print ("Se deben ingresar valores númericos") valor = int(input("Escribe un Valor: ")) #Creación del arreglo cotizacion.append([nit,nombre,valor]) # Se Inicializa y se asume que tanto el mayor valor de cotizacion como el menor valor de cotización están en el primer elemento; mayor = cotizacion[0][2] menor = cotizacion[0][2] # Se recorre la matriz para obtener el valor mayor y menor de la cotización for fila in cotizacion: suma = suma + fila[2] valor=fila[2] if(valor >= mayor) : mayor = valor cotizacion_mayor = cotizacion.index(fila) if(valor <= menor) : menor = valor cotizacion_menor = cotizacion.index(fila) # promedio de las cotizaciones promedio = suma / len(cotizacion) # Imprimir resultado de la cotización mas baja y la más alta y el promedio print("Cotización más baja") print("Nit: ",cotizacion[cotizacion_menor][0]) print("Nombre: ",cotizacion[cotizacion_menor][1]) print("Valor: ",cotizacion[cotizacion_menor][2]) print("Cotización más alta") print("Nit: ",cotizacion[cotizacion_mayor][0]) print("Nombre: ",cotizacion[cotizacion_mayor][1]) print("Valor: ",cotizacion[cotizacion_mayor][2]) print("Promedio: ", promedio) # se pregunta nuevamente si desea ingresar otra cotización respuesta = input("\n¿Desea realizar más cotizaciones? (si/no) ")
65f97399be1c7e6375f45a2cb80213f7e6adaf09
dennerepin/StochNetV2
/stochnet_v2/utils/errors.py
793
3.5
4
class ShapeError(Exception): """Exception raised for errors in the input shape. Attributes: message -- explanation of the error """ def __init__(self, message='Wrong shape!'): self.message = message class DimensionError(Exception): """Exception raised for errors concerning the dimension of the used spaces. Attributes: message -- explanation of the error """ def __init__(self, message='Wrong dimensions!'): self.message = message class NotRestoredVariables(Exception): """Exception raised when trying to use model without loading trained variables. Attributes: message -- explanation of the error """ def __init__(self, message='Model variables not restored!'): self.message = message
7cc301e602806d8e8fa38a198c678a6e57924f55
ParalogyX/combinations_permutations
/combperm.py
9,746
4.125
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 16 11:36:21 2021 Functions to calculate combinaions and permutations @author: vpe """ import itertools def factorial(n): """ Calculates factorial of n Parameters ---------- n : int Positive integer. Returns ------- factorial : int Factorial of n. """ if n < 0 or type(n) != int: raise RuntimeError("Wrong arguments") factorial = 1 if int(n) >= 1: for i in range (1,int(n)+1): factorial = factorial * i return factorial class combinaionsAndPermutations(object): def __init__(self, collection, typeOfCombination = 1, r = 1): """ Initialization of combinaionsAndPermutations. Parameters ---------- collection : list, tuple, str or dict Not empty iterable collection of items used for combinations. typeOfCombination : 1, 2, 3 or 4, optional 1 - Combination With Repetition. 2 - Combination Without Repetition. 3 - Permutation With Repetition. 4 - Permutation Without Repetition. The default is 1. r : positive int, optional Amount of items in combination. The default is 1. Raises ------ RuntimeError If collection is not iterable, or typeOfCombination is not 1, 2, 3 or 4, or r is more than lenght of collection, generates RuntimeError "Wrong arguments". Returns ------- None. """ if (type (collection) not in (list, tuple, str, dict) or typeOfCombination not in (1,2,3,4) or not 0 < r <= len(collection)): raise RuntimeError("Wrong arguments") self.collection = collection self.typeOfCombination = typeOfCombination self.r = r self.n = len(collection) def SetCollection(self, collection): """ Update a collecion. Automatically decreases Amount of items in combination (r) in case current value is bigger, than collection lenght Parameters ---------- collection : Not empty list, tuple, str or dict Iterable collection of items used for combinations. Raises ------ RuntimeError If collection is not iterable generates RuntimeError "Wrong arguments". Returns ------- None. """ if type (collection) not in (list, tuple, str, dict): raise RuntimeError("Wrong arguments") self.collection = collection self.n = len(collection) if self.r > self.n: self.r = self.n def SetTypeOfCombination(self, typeOfCombination): """ Update type of combination Parameters ---------- typeOfCombination : 1, 2, 3 or 4. 1 - Combination With Repetition. 2 - Combination Without Repetition. 3 - Permutation With Repetition. 4 - Permutation Without Repetition. Raises ------ RuntimeError If typeOfCombination is not 1, 2, 3 or 4 generates RuntimeError "Wrong arguments". Returns ------- None. """ if typeOfCombination not in (1,2,3,4): raise RuntimeError("Wrong arguments") self.typeOfCombination = typeOfCombination def SetItemsInCombination(self, r): """ Update amount of items in combination Parameters ---------- r : positive int Amount of items in combination.. Raises ------ RuntimeError If r is more than lenght of collection, generates RuntimeError "Wrong arguments". Returns ------- None. """ if not 0 < r <= len(self.collection): raise RuntimeError("Wrong arguments") self.r = r def GetCollection(self): """ Returns collection Returns ------- list, tuple, str or dict. Current collection of items. """ return self.collection def GetTypeOfCombination(self): """ Returns name of type of combination 1 - Combination With Repetition. 2 - Combination Without Repetition. 3 - Permutation With Repetition. 4 - Permutation Without Repetition. Returns ------- str Type of combination. """ option = {1: "Combination With Repetition", 2: "Combination Without Repetition", 3: "Permutation With Repetition", 4: "Permutation Without Repetition"} return option[self.typeOfCombination] def GetItemsInCombination(self): """ Returns ------- int Amount of items in combination. """ return self.r def GetAmountOfElements(self): """ Returns ------- int Lenght of collection. """ return self.n def AmountOfCombinations(self): """ Calculates amount of all possible combinations of selected type Returns ------- int Amount of combinations. """ option = {1: CombinationWithRepetition, 2: CombinationWithoutRepetition, 3: PermutationWithRepetition, 4: PermutationWithoutRepetition} return option[self.typeOfCombination](self.n, self.r) def AllCombinations(self, maxLines = 10): """ Returns list of all possible combinatios of selected type, limited by maxLines. WARNING: Large maxLines (more than ~10000000) can cause memory issues and freezing. Always check AmountOfCombinations() before and setup good maxLines. Parameters ---------- maxLines : int, optional Limitation of output. The default is 10. Returns ------- result : list First maxLines of all possible combinations. """ option = {1: itertools.combinations_with_replacement, 2: itertools.combinations, 3: itertools.product, 4: itertools.permutations} result = [] i = 0 if self.typeOfCombination == 3: for comb in itertools.product(self.collection, repeat = self.r): result.append(comb) i += 1 if i >= maxLines: break else: for comb in option[self.typeOfCombination](self.collection, self.r): result.append(comb) i += 1 if i >= maxLines: break return result def CombinationWithRepetition(n, r): """ Calculates amount of combinations of r in n variables with repetition is possible E.g n=4 (1,2,3,4), r=2, variants: 11 12 13 14 22 23 24 33 34 44 Order doesn't matter!!! 21 = 12 Parameters ---------- n : int Amount of different types. Positive integer. r : int Amount of selected types. Positive integer, less or equal n. Returns ------- int Amount of combinations. """ if type(n) != int or type(r) != int or (n <= 0) or not 0 < r <= n: raise RuntimeError("Wrong arguments") return int(factorial(n+r-1)/(factorial(r) * factorial(n-1))) def CombinationWithoutRepetition(n, r): """ Calculates amount of combinations of r in n variables without repetition is possible E.g n=4 (1,2,3,4), r=2, variants: 12 13 14 23 24 34 Order doesn't matter!!! 21 = 12 Parameters ---------- n : int Amount of different types. Positive integer. r : int Amount of selected types. Positive integer, less or equal n. Returns ------- int Amount of combinations. """ if type(n) != int or type(r) != int or (n <= 0) or not 0 < r <= n: raise RuntimeError("Wrong arguments") return int(factorial(n)/(factorial(r) * factorial(n-r))) def PermutationWithRepetition(n, r): """ Calculates amount of permutaions of r in n variables with repetition is possible E.g n=4 (1,2,3,4), r=2, variants: 11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44 Order does matter!!! 21 != 12 Parameters ---------- n : int Amount of different types. Positive integer. r : int Amount of selected types. Positive integer, less or equal n. Returns ------- int Amount of permutaions. """ if type(n) != int or type(r) != int or (n <= 0) or not 0 < r <= n: raise RuntimeError("Wrong arguments") return int(n**r) def PermutationWithoutRepetition(n, r): """ Calculates amount of permutaions of r in n variables without repetition is possible E.g n=4 (1,2,3,4), r=2, variants: 12 13 14 21 23 24 31 32 34 41 42 43 Order does matter!!! 21 != 12 Parameters ---------- n : int Amount of different types. Positive integer. r : int Amount of selected types. Positive integer, less or equal n. Returns ------- int Amount of combinations. """ if type(n) != int or type(r) != int or (n <= 0) or not 0 < r <= n: raise RuntimeError("Wrong arguments") return int(factorial(n)/factorial(n-r))