blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d20d83e3811c57dafa56630c2413e727c444ec10
medamer/cs-module-project-hash-tables
/lecture/fib.py
306
3.53125
4
# 0 1 1 2 3 5 8 13 21 34 55 ... # # fib(0): 0 # fib(1): 1 # fib(n): fib(n-1) + fib(n-2) # cache = {} def fib(n): if n <= 1: return n if n not in cache: cache[n] = fib(n-1) + fib(n-2) return cache[n] for i in range(100): print(f'{i:3} {fib(i)}') """ def foo(a, x, b): cache[(a,x,b)] = ... """
3e65667502f49752e3731b9551442e20ddcfd287
livneniv/python
/Week 10 - Tuples/assn-10_2.py
574
3.671875
4
fname = raw_input ("Enter file name to be examined: ") #getting the file name from the user fhand=open(fname) counts = dict() for line in fhand: line = line.rstrip() if line =='' : continue #guardian pattern (checking if a line is blank) words = line.split() if words[0] != 'From' :continue time = words[5] hours = time[0:2] counts[hours]=counts.get (hours,0)+1 lst = list() for key,val in counts.items(): lst.append((key,val)) #append the keys and values of the dictionary to the new list lst.sort() for key,val in lst: print key,val #print counts
892b5628d15e7603ac4f91745077b7c2c77027ce
Lalitaeranki/UCI-Work
/06-Python-APIs/2/Activities/11-Ins_WorldBankAPI/Unsolved/Ins_WorldBankAPI.py
424
3.625
4
# coding: utf-8 # In[2]: # Dependencies import requests url = "http://api.worldbank.org/v2/" format = "json" # Get country information in JSON format countries_response = requests.get(f"{url}countries?format={format}").json() # First element is general information, second is countries themselves countries = countries_response[1] # In[3]: # Report the names for country in countries: print(country["name"])
5fc75b9f016f34471e3cfa24113b2703d9799e57
ssshow16/tetris_ri
/othello/square.py
829
4.125
4
class Square(object): """ Represents one square of an othello board. Instance variables: value - If a disk is placed, its value, else None is_valid_move - boolean if the current player can play here flipped_disks - if the current player plays here, which disks will flip to their color """ def __init__(self, value=None): """ Initialize Square. Optional arguments: value - current value of square, default None """ self._value = value self.is_valid_move = False self.flipped_disks = [] @property def value(self): return self._value @value.setter def value(self, value): self._value = value self.is_valid_move = False self.flipped_disks = []
cb766307ed33ed927bdddfc9f7268cc4c7b0fdc4
lizhihui16/aaa
/pbase/day19/shili/myinteder.py
419
3.578125
4
class MyInteger: def __init__(self,value): self.data=int(value) def __int__(self): '''此方法必须返回整数''' return self.data def __float__(self): return float(self.data) a1=MyInteger('100') i=int(a1) #将MyInteger类型转为整数 print(i) f=float(a1) #a1.__float__() print(f) c=complex(a1) #a1.__complex__() print(c) d=bool(a1) #a1.__bool__() print(d)
ff88055a5ef82696d5e13b35c1e711b032736500
nelsonmpyana/Espoir333--A6-grade-average-calculator
/calc.py
331
3.90625
4
n=int(input("Amount of grades entering?: ")) a=[] for i in range(0,n): elem=int(input("Enter Dave's grade: ")) a.append(elem) avg=sum(a)/n print("Dave grade average",round(avg,2)) for i in range(0,n): elem=int(input("Enter Sara's grade: ")) a.append(elem) avg=sum(a)/n print("Sara's grade average",round (avg,2))
7f72a2798b6b7ef850679f27546c0043eff6ec08
htutk/python
/mergePdf.py
3,404
4.25
4
#! python3 # mergePdf.py - merges PDF files together to make a single pdf import PyPDF2, os, sys if len(sys.argv) < 2: print(""" To use mergePdf.py, Enter mergePdf <pdf1.pdf> <pdf2.pdf> ... <pdfn.pdf>. NOTES: 1. Make sure to include .pdf extension. 2. Merge the files in order given. """) else: pdfList = sys.argv[1:] # check to see if .pdf extension are added for file in pdfList: if not file.endswith('.pdf'): sys.exit('Make sure to include .pdf extension...') print() print('Where are the files located?') print("Enter in the format of C:\\\\folder\\\\folder...") directory = input() while True: try: os.chdir(directory) break except: print('Please enter a valid directory... Enter \'q\' to exit...') directory = input() if directory.lower() == 'q': sys.exit() # check to see every file is in the directory given print() for file in pdfList: print('Checking...') if file not in os.listdir(): sys.exit(file + ' cannot be found in ' + str(os.getcwd())) pdfWriter = PyPDF2.PdfFileWriter() # loop thru all the pdf files print('Initializing...') print() for file in pdfList: pdfReader = PyPDF2.PdfFileReader(open(file, 'rb')) # if the file is encrypted if pdfReader.isEncrypted: print('Oh O!, ' + file + ' is encrypted...') print('Do you happen to know the password? (Y/N): ', end='') knownPassword = input() while True: if knownPassword.upper() == 'Y': print('Enter the password: ', end='') password = input() while not pdfReader.decrypt(password): print('Sorry, the password is incorrect... ' + 'Enter \'q\' to exit...') password = input() if password.lower() == 'q': sys.exit() break elif knownPassword.upper() == 'N': print('Sorry, the encrypted pdf requires a password...') sys.exit() else: print('Please enter Y/N: ', end='') knownPassword = input() # get all pages for page in range(pdfReader.numPages): pdfWriter.addPage(pdfReader.getPage(page)) print() print(file + ' is now added...') print() # name the merged file print() print('How would you like to name the merged file? ' + 'Please include .pdf extension: ') outputFileName = input() # check two things: # 1. ends with .pdf # 2. is valid filename while True: try: while not outputFileName.endswith('.pdf'): print('Please include .pdf extension...') outputFileName = input() pdfOutput = open(outputFileName, 'wb') break except: print('Please enter a valid file name...') outputFileName = input() print() print('Done....!') pdfWriter.write(pdfOutput) pdfOutput.close()
5a0c9b8b5bb0acda50a4298b910522974c1d7729
PrestonFawcett/Pig_Game
/pig.py
1,851
4.125
4
#!/usr/bin/env python3 """ Pig game written in Python. """ __author__ = 'Preston Fawcett' __email__ = 'ptfawcett@csu.fullerton.edu' __maintainer__ = 'PrestonFawcett' import time from player import Player from functions import error from functions import rearrange from functions import start_turn def main(): """ Main function for game. """ # Asking how many players num_of_players = 0 while num_of_players < 2 or num_of_players > 4: num_of_players = int(input('How many players (2-4)?: ')) if num_of_players < 2 or num_of_players > 4: error() # Initializing players players = [] if num_of_players == 2: answer = input('Is player 2 a computer? (y/n): ') players.append(Player(input('\nEnter your name: '), False)) if answer == 'y': players.append(Player('John Scarne', True)) else: players.append(Player(input('\nEnter your name: '), False)) else: for i in range(0, num_of_players): players.append(Player( input('\nPlayer {} enter your name: '.format(i + 1)), False)) # Creating turn order turn_order = rearrange(players) print('\n------Turn Order------') for i in range(0, num_of_players): print('{}. {}'.format((i + 1), turn_order[i].name)) # Start Pig game current = 0 while not turn_order[current].winner: print('\n*******SCOREBOARD*******') for i in range(0, num_of_players): print(turn_order[i]) print('************************') print('\n{}\'s turn.'.format(turn_order[current].name)) time.sleep(1) start_turn(turn_order[current]) if not turn_order[current].winner: current = (current + 1) % num_of_players print('{} wins!'.format(turn_order[current].name)) if __name__ == '__main__': main()
00753e89471e7a431fb581755336c8494875ce75
vikramlance/Python-Programming
/hackerRank/day11-2DArrays.py
1,893
4.21875
4
''' Objective Today, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video! Context Given a 6×6 2D Array, A: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in A to be a subset of values with indices falling in this pattern in A's graphical representation: a b c d e f g There are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass' values. Task Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum. Input Format There are 6 lines of input, where each line contains 6 space-separated integers describing 2D Array A; every value in A will be in the inclusive range of −9 to 9. Output Format Print the largest (maximum) hourglass sum found in A. Sample Input 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 2 4 4 0 0 0 0 2 0 0 0 0 1 2 4 0 Sample Output 19 Explanation A contains the following hourglasses: 1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 2 0 2 4 2 4 4 4 4 0 1 1 1 1 1 0 1 0 0 0 0 0 0 2 4 4 0 0 0 0 0 2 0 2 0 2 0 0 0 0 2 0 2 4 2 4 4 4 4 0 0 0 2 0 0 0 1 0 1 2 1 2 4 2 4 0 The hourglass with the maximum sum (19) is: 2 4 4 2 1 2 4 ''' #!/bin/python import sys arr = [] for arr_i in xrange(6): arr_temp = map(int,raw_input().strip().split(' ')) arr.append(arr_temp) #print sum (arr[0]) p=[] for i in range(0,4): for j in range (0,4): m=0 for k in range (0,3): for l in range (0,3): #print i, j, k, l m= m+ (arr[j+l][i+k]) n=m-arr[j+1][i]-arr[j+1][i+2] p.append(n) print max(p)
0bfceb8a70068e598fed045ccb48db716d3acc58
robertpatrick6/PathfindingMaze
/MazeMaker/maze_creation.py
6,770
3.9375
4
import random def create_maze(size): ''' Creates a maze within the given grid. Grid elements are 0s and 1s, with 0s being the path and 1s being the start_walls ''' GRID_SIZE = size # Create grid grid = [] for i in range(GRID_SIZE): grid.append([]) for j in range(GRID_SIZE): grid[i].append(1) def set_next_node(current_node): ''' Recursively work through grid and set paths ''' def invalid_node(node, direction): ''' Returns true if given node is invalid ''' # Check that node isn't border node if (node[0] <= 0 or node[0] >= len(grid[0]) - 1 or node[1] <= 0 or node[1] >= len(grid) - 1): return True # Check that new node isn't already passable elif (grid[node[0]][node[1]] == 0): return True # Check adjacent nodes else: for i in range(0, 2): for j in range(-1, 2): if (direction == 0): if ((node[0]+j,node[1]-i) != node): if (grid[node[0]+j][node[1]-i] == 0): return True elif (direction == 1): if ((node[0]+i,node[1]+j) != node): if (grid[node[0]+i][node[1]+j] == 0): return True elif (direction == 2): if ((node[0]+j,node[1]+i) != node): if (grid[node[0]+j][node[1]+i] == 0): return True else: if ((node[0]-i,node[1]+j) != node): if (grid[node[0]-i][node[1]+j] == 0): return True # Valid node return False # Determine direction of new node direction = random.randrange(4) # Set new node if direction == 0: next_node = (current_node[0], current_node[1] - 1) elif direction == 1: next_node = (current_node[0] + 1, current_node[1]) elif direction == 2: next_node = (current_node[0], current_node[1] + 1) else: next_node = (current_node[0] - 1, current_node[1]) new_direction = direction while (True): if (not invalid_node(next_node, new_direction)): # Set next node as passable grid[next_node[0]][next_node[1]] = 0 # Find next node set_next_node(next_node) # Update to new direction new_direction = (new_direction - 1) % 4 # Check if a full rotation has been done if (new_direction == direction): return # Set new node if new_direction == 0: next_node = (current_node[0], current_node[1] - 1) elif new_direction == 1: next_node = (current_node[0] + 1, current_node[1]) elif new_direction == 2: next_node = (current_node[0], current_node[1] + 1) else: next_node = (current_node[0] - 1, current_node[1]) # Determine start position start_wall = random.randrange(4) if start_wall % 2 == 0: start_position = random.randrange(1, len(grid) - 1) else: start_position = random.randrange(1, len(grid[0]) - 1) if start_wall == 0: start_coord = (start_position, 0) elif start_wall == 1: start_coord = (len(grid) - 1, start_position) elif start_wall == 2: start_coord = (start_position, len(grid[0]) - 1) else: start_coord = (0, start_position) grid[start_coord[0]][start_coord[1]] = 0 # Recurse through grid set_next_node(start_coord) # Determine end position end_wall = random.randrange(4) if end_wall % 2 == 0: exit_position = random.randrange(1, len(grid) - 1) else: exit_position = random.randrange(1, len(grid[0]) - 1) while (end_wall == start_wall and exit_position == start_position): end_wall = random.randrange(4) if end_wall % 2 == 0: exit_position = random.randrange(1, len(grid) - 1) else: exit_position = random.randrange(1, len(grid[0]) - 1) if end_wall == 0: if (grid[exit_position][1] != 0): if (exit_position <= GRID_SIZE // 2): while(grid[exit_position][1] != 0): exit_position = (exit_position+1) % GRID_SIZE else: while(grid[exit_position][1] != 0): exit_position = (exit_position-1) % GRID_SIZE exit_coord = (exit_position, 0) elif end_wall == 1: if (grid[GRID_SIZE - 2][exit_position] != 0): if (exit_position <= GRID_SIZE // 2): while(grid[GRID_SIZE - 2][exit_position] != 0): exit_position = (exit_position+1) % GRID_SIZE else: while(grid[GRID_SIZE - 2][exit_position] != 0): exit_position = (exit_position-1) % GRID_SIZE exit_coord = (len(grid) - 1, exit_position) elif end_wall == 2: if (grid[exit_position][GRID_SIZE - 2] != 0): if (exit_position <= GRID_SIZE // 2): while(grid[exit_position][GRID_SIZE - 2] != 0): exit_position = (exit_position+1) % GRID_SIZE else: while(grid[exit_position][GRID_SIZE - 2] != 0): exit_position = (exit_position-1) % GRID_SIZE exit_coord = (exit_position, len(grid[0]) - 1) else: if (grid[1][exit_position] != 0): if (exit_position <= GRID_SIZE // 2): while(grid[1][exit_position] != 0): exit_position = (exit_position+1) % GRID_SIZE else: while(grid[1][exit_position] != 0): exit_position = (exit_position-1) % GRID_SIZE exit_coord = (0, exit_position) grid[exit_coord[0]][exit_coord[1]] = 0 return grid
fb16cad572a746ca1bb1bfce07e47b71e5ebe0cd
dorbengoose/Python-Challenge
/PyPoll/main.py
3,770
4.4375
4
# # 1 .- Import Modules from Python Library (as in the Classroom) # #Allows to create the Open to Destination for the Bank.csv File to main.py import os # As in the Classroom # # Import Module to be able to read a CSV File in Python save as bank_statement import csv # As in the Classroom import collections # Imports the counter method for selecting data # # Define the CSV Path, same directory as main.py (To Read it easier) poll = os.path.join("..", "Python-Challenge", "PyPoll", "Poll.csv") # # 2.-Variables and names Directory # #"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # # total_votes: List, includes Calculates the Total Votes # # poll_py: The poll list into Python # # tvi: Total Votes as Integer # #"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # # # # 3 .- Develop the Executions # # Instruction to extract the data separated by comma('). Saving into .py extension with open(poll, newline='') as poll: # # CSV reader specifies delimiter and variable that holds contents # # As in the Class poll_py = csv.reader(poll, delimiter=',') print(poll_py) # # Read the header row first (skip this step if there is now header) poll_header = next(poll_py) print(f"Poll Header: {poll_header}") # Defining Column 2 for Candidates Column total_votes = [row[2] for row in poll_py] # ****************************************************** # From Collections module as extracted from Python.org # ****************************************************** # Arrange the values in order according to ocurrence total_votes.sort() # Get the len from the list for getting total votes y = len(total_votes) print(f'The total Votes are: {y}') # Gets the whole ranking in to candidates_ranking list candidates_ranking = collections.Counter(total_votes) # Prints the whole candidate ranking print(f'The WHOLE ELECTION RESULTS are as follows:\n {candidates_ranking}') # Separate each Candidate values khan = int(candidates_ranking['Khan']) correy = int(candidates_ranking['Correy']) li = int(candidates_ranking['Li']) # Double quotes for O'Tooley otooley = int((candidates_ranking["O'Tooley"])) # Assigning an integer to tvi, Total Voters Integer tvi = int(y) # Calculating Percentages for each Candidate against total_votes, printing print('The winner is Khan with: {:.0%}'.format( khan/tvi) + ','+f' {khan} votes') print('The second place is for Correy with: {:.0%}'.format( correy/tvi) + ','+f' {correy} votes') print('The third place is for Li with: {:.0%}'.format( li/tvi) + ','+f' {li} votes') print("The fouth place is for O'Tooley with: {:.0%}".format( otooley/tvi) + ','+f' {otooley} votes') print(f'The absolute winner is Khan : {khan}') # EXPORTINT TO FILE TEXT NAMED RESULTS ELECTIONS # SYSTEM Module, from Python.org import sys sys.stdout = open('../Python-Challenge/PyPoll/Results_Elections.txt', 'w') print(f'The total Votes are: {y}') print(f'The WHOLE ELECTION RESULTS are as follows:\n {candidates_ranking}') print('The winner is Khan with: {:.0%}'.format( khan/tvi) + ','+f' {khan} votes') print('The second place is for Correy with: {:.0%}'.format( correy/tvi) + ','+f' {correy} votes') print('The third place is for Li with: {:.0%}'.format( li/tvi) + ','+f' {li} votes') print("The fouth place is for O'Tooley with: {:.0%}".format( otooley/tvi) + ','+f' {otooley} votes') print(f'The absolute winner is Khan: {khan}') sys.stdout.close()
b019d7e94d47f5dd0b983ef74de88adb13f4a283
Sunflower411/complex-network-course-work
/hw6/Xing An Ass 6/Round6_centrality-measures-for-undirected-networks (1).py
15,712
3.5
4
#!/usr/bin/env python # coding: utf-8 # # Round 6. Centrality measures for undirected networks # # In this exercise, we get familiar with some common centrality measures by applying them to undirected networks (although these measures can all be generalized also to directed networks). # # Below, we list and define the measures used in this exercise: # 1. degree $k(i)$: Number of neighbors of node $i$ # 2. betweenness centrality $bc(i)$: Number of shortest paths between other nodes of the network that pass through node $i$. However, if there exist several shortest paths between a given pair of nodes, then the contribution of that node pair to the betweenness of $i$ is given by the fraction of those paths that contain $i$. The betweenness scores are also normalized by $(N-1)(N-2)$, i.e. the number of all node-pairs of the network, excluding pairs that contain $i$ (because paths starting or ending in node $i$ do not contribute to the betweenness of $i$), which is the maximum possible score. Formally, if $\sigma_{st}$ is the number of shortest paths from $s$ to $t$ and $\sigma_{sit}$ the number of such paths that contain $i$, then $\big[bc(i) = \frac{1}{(N-1)(N-2)}\sum_{s\neq i} \sum_{t\neq i} \dfrac{\sigma_{sit}}{\sigma_{st}}\big]$. # 3. closeness centrality $C(i)$: Inverse of the average shortest path distance to all other nodes than $i$: $\bigg[C(i) = \dfrac{N-1}{\sum\limits_{v\neq i}d(i,v)}\bigg]$. # 4. $k$-shell $k_s(i)$: Node $i$ belongs to the $k$-shell, if it belongs to the $k$-core of the network but does not belong to the $k+1$-core. The $k$-core is the maximal subnetwork (i.e. the largest possible subset of the network's nodes, and the links between them) where all nodes have at least degree $k$. In other words, the 1-core is formed by removing nodes of degree 0 (isolated nodes) from the network, the 2-core is formed by removing nodes of degree 1 and iteratively removing the nodes that become degree 1 or 0 because of the removal, the 3-core is formed by removing nodes of degree less than 3 and those nodes that become of degree less than 3 because of the removals, and so on. The 1-shell is then the set of nodes that was removed from the 1-core to obtain the 2-core. # 5. eigenvector centrality $e(i)$: Eigenvector centrality is a generalization of degree that takes into account the degrees of the node's neighbors, and recursively the degrees of the neighbors of neighbors, and so on. It is defined as the eigenvector of the adjacency matrix that corresponds to the largest eigenvalue. # # To get you started, you may use this notebook OR the accompanying Python template `centrality_measures_for_undirected_networks.py` available in MyCourses. The usage of the notebook or template is **optional**. Then you only need to fill in the required functions. Some of the functions do NOT need modifications. You may start your solution after the subtitle "**Begin of the Exercise**" down below. # # In addition to returning a short report of your results (including the visualizations), return also your commented Python code or notebook. Remember to label the axes in your figures! # In[21]: import numpy as np import networkx as nx import matplotlib as mpl import matplotlib.pylab as plt from matplotlib import gridspec import pickle # In[13]: def create_scatter(x_values, y_values, x_label, y_label, labels, markers): """ Creates a scatter plot of y_values as a function of x_values. Parameters ---------- x_values: np.array y_values: list of np.arrays x_label: string y_label: string a generic label of the y axis labels: list of strings labels of scatter plots markers: list of strings Returns ------- No direct output, saves the scatter plot at given figure_path """ assert x_values.size , 'Bad input x_values for creating a scatter plot' fig = plt.figure() ax = fig.add_subplot(111) for y_val, label, marker in zip(y_values, labels, markers): ax.plot(x_values, y_val, ls='', marker=marker, label=label) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.grid() ax.legend(loc=0) return fig # In[22]: def visualize_on_network(network, node_values, coords_path, titles, cmap='YlOrRd', node_size=50, font_size=8, scale=500): """ Creates visualizations of the network with nodes color coded by each of the node values sets. Parameters ---------- network: networkx.Graph() node_values: list of lists coords_path: path to a file containing node coordinates titles: list of strings cmap: string node_size: int font_size: int scale: int used to calculate the spring layout for node positions Returns ------- No direct output, saves the network visualizations at given path """ assert node_values[0].size, "there should be multiple values per node" # This is the grid for 5 pictures gs = gridspec.GridSpec(3, 4, width_ratios=(20, 1, 20, 1)) network_gs_indices = [(0, 0), (0, 2), (1, 0), (1, 2), (2,0)] cbar_gs_indices = [(0, 1), (0, 3), (1, 1), (1, 3), (2, 1)] # Loading coordinates from the file with open(coords_path, 'rb') as f: #coords = pickle.load(f, encoding='latin1') coords = pickle.load(f, encoding='latin1') # Loop over different value sets for node_val, title, network_gs_index, cb_gs_index in zip(node_values, titles, network_gs_indices, cbar_gs_indices): # Draw the network figure ax = plt.subplot(gs[network_gs_index[0], network_gs_index[1]]) nx.draw(network, pos=coords, node_color=node_val, cmap=cmap, node_size=node_size, font_size=font_size, edgecolors='black') # Draw the colorbar (cb) cmap = plt.get_cmap('OrRd') norm = mpl.colors.Normalize(vmin=np.min(node_val), vmax=np.max(node_val)) scm = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) plt.colorbar(scm, ax=ax) ax.set_title(title) plt.tight_layout() #retun fig THis is a error before providing by the teacher return plt # ## Data # Let us load the data from the right folder and assign the names for all the plots we will save. If you run this notebook in your machine, please specify the right folder. # In[23]: # Select data directory import os if os.path.isdir('/coursedata'): course_data_dir = '/coursedata' elif os.path.isdir('../data'): course_data_dir = '../data' else: # Specify course_data_dir on your machine course_data_dir = 'some_path' # YOUR CODE HERE #raise NotImplementedError() print('The data directory is %s' % course_data_dir) # # Begin of the exercise # Write your code here to compute the requested network properties # ### a. Centrality measures (pen and paper) # Your first task is to compute/reason without a computer the first 4 centrality measures of the above list for the network shown in Fig. 1 (i.e. using pen-and-paper; note that you do not need to compute the eigenvector centrality, as one then would need to compute the eigenvalues of a 5×5 matrix which can be a bit painful). In your computations, use the definitions given above and show also intermediate steps where necessary. # In[24]: from IPython.display import Image fig = Image(filename=('/coursedata/small_net_for_uw_centralities.png')) fig # ### b. Centrality measures (NetworkX) # Use NetworkX to compute all five centrality measures for the networks shown in Fig 2 (small_cayley_tree.edg, larger_lattice.edg, small_ring.edg) as well as for the Karate club network (karate_club_network_edge_file.edg). Then, visualize betweenness, closeness, k-shell, and eigenvector centrality as a function of degree in a scatter plot for each of the networks. For easier visual comparison of the measures, you should normalize the k-shell values by dividing them by the maximal k-shell value. # **Hint**: For some of the networks, the power iteration algorithm used by NetworkX to calculate eigenvector centrality may not converge. In this case, increase the value of the tolerance (tol) parameter of `eigenvector_centrality()` until the iteration converges. # In[25]: from IPython.display import Image fig = Image(filename=('/coursedata/small_model_networks_larger_lattice.png')) fig # In[32]: def get_centrality_measures(network, tol): """ Calculates five centrality measures (degree, betweenness, closeness, and eigenvector centrality, and k-shell) for the nodes of the given network. Parameters ---------- network: networkx.Graph() tol: tolerance parameter for calculating eigenvector centrality Returns -------- [degree, betweenness, closeness, eigenvector_centrality, kshell]: list of numpy.arrays """ degree = [] betweenness = [] closeness = [] eigenvector_centrality = [] kshell = [] degree_dic = nx.degree_centrality(network) betweenness_dic = nx.betweenness_centrality(network) closeness_dic = nx.closeness_centrality(network) eigenvector_dic = nx.eigenvector_centrality(network,tol = tol) k_dic = nx.core_number(network) #print(k_dic) for node in network: degree.append(degree_dic[node]) betweenness.append(betweenness_dic[node]) closeness.append(closeness_dic[node]) eigenvector_centrality.append(eigenvector_dic[node]) kshell.append(k_dic[node]) #for i in sorted (degree_dic.keys()): #degree.append(degree_dic[i]) #for i in sorted (betweenness_dic.keys()): #betweenness.append(betweenness_dic[i]) #for i in sorted (closeness_dic.keys()): #closeness.append(closeness_dic[i]) #for i in sorted (eigenvector_dic.keys()): #eigenvector_centrality.append(eigenvector_dic[i]) #for i in sorted (k_dic.keys()): #kshell.append(k_dic[i]) degree = np.asarray(degree) betweenness = np.asarray(betweenness) closeness = np.asarray(closeness) eigenvector_centrality = np.asarray(eigenvector_centrality) kshell = np.asarray(kshell) #print(degree_dic) #print(degree) #TODO: Using networkX functions calculate the different centrality measures. Each of these networkx functions return a dictionary of nodes with the centrality measure of the nodes as the value. # Then you should sort all the measures with same nodewise order as in network.nodes() and add them to their corresponding list defined above. Also notice that at the end, get_centrality_measures() # function should return a list of numpy arrays. # YOUR CODE HERE #raise NotImplementedError() return [degree, betweenness, closeness, eigenvector_centrality, kshell] # In[33]: # Set-up all the names network_paths = ['small_ring.edg', 'larger_lattice.edg', 'small_cayley_tree.edg', 'karate_club_network_edge_file.edg'] coords_paths = ['small_ring_coords.pkl', 'larger_lattice_coords.pkl', 'small_cayley_tree_coords.pkl', 'karate_club_coords.pkl'] network_names = ['ring', 'lattice', 'cayley_tree', 'karate'] x_label = 'Degree k' y_label = 'Centrality measure' labels = ['betweenness centrality', 'closeness centrality', 'eigenvector centrality', 'normalized k-shell'] markers = ['.', 'x', '+', 'o'] scatter_base_path = 'centrality_measures_scatter' titles = ['Degree $k$', 'Betweenness centrality', 'Closeness centrality', 'Eigenvector centrality', '$k$-shell'] network_base_path = './network_figures' # In[34]: fig_index = 0 tol = 10**-1 # tolerance parameter for calculating eigenvector centrality for (network_path, network_name, coords_path) in zip(network_paths, network_names, coords_paths): network_path2 = os.path.join(course_data_dir, network_path) if network_name == 'karate': network = nx.read_weighted_edgelist(network_path2) else: network = nx.read_edgelist(network_path2) # Calculating centrality measures [degree, betweenness, closeness, eigenvector_centrality, kshell] = get_centrality_measures(network, tol) kshell_normalized = kshell/float(np.max(kshell)) # normalization for easier visualization # Scatter plot y_values = [betweenness, closeness, eigenvector_centrality, kshell_normalized] scatter_path = scatter_base_path + '_' + network_name + '.png' fig = create_scatter(degree, y_values, x_label, y_label, labels, markers) fig.savefig(scatter_path) # ### c. Visualization # To highlight the differences between the centrality measures, plot five visualizations for all the networks studied in part b (the ring lattice, the 2D-lattice, the Cayley tree and the Karate club network), each time using one of the centrality measures to define the colors of the network nodes. To make the visualization easier, coordinates of the nodes are provided in .pkl files (`small_cayley_tree_coords.pkl`, `larger_lattice_coords.pkl`, `small_ring_coords.pkl`, `karate_club_coords.pkl`). # In[35]: fig_index = 0 tol = 10**-1 # tolerance parameter for calculating eigenvector centrality for (network_path, network_name, coords_path) in zip(network_paths, network_names, coords_paths): network_path2 = os.path.join(course_data_dir, network_path) coords_path2 = os.path.join(course_data_dir, coords_path) if network_name == 'karate': network = nx.read_weighted_edgelist(network_path2) else: network = nx.read_edgelist(network_path2) # Calculating centrality measures [degree, betweenness, closeness, eigenvector_centrality, kshell] = get_centrality_measures(network, tol) kshell_normalized = kshell/float(np.max(kshell)) # normalization for easier visualization # Network figures network_figure_path = network_base_path + '_' + network_name + '.png' all_cvalues = [degree, betweenness, closeness, eigenvector_centrality, kshell] fig=visualize_on_network(network, all_cvalues, coords_path2, titles) fig.savefig(network_figure_path) # In[20]: fig_index = 0 tol = 10**-1 # tolerance parameter for calculating eigenvector centrality for (network_path, network_name, coords_path) in zip(network_paths, network_names, coords_paths): network_path2 = os.path.join(course_data_dir, network_path) coords_path2 = os.path.join(course_data_dir, coords_path) if network_name == 'karate': network = nx.read_weighted_edgelist(network_path2) else: network = nx.read_edgelist(network_path2) # Calculating centrality measures [degree, betweenness, closeness, eigenvector_centrality, kshell] = get_centrality_measures(network, tol) kshell_normalized = kshell/float(np.max(kshell)) # normalization for easier visualization # Network figures network_figure_path = network_base_path + '_' + network_name + '.png' all_cvalues = [degree, betweenness, closeness, eigenvector_centrality, kshell] fig=visualize_on_network(network, all_cvalues, coords_path2, titles) fig.savefig(network_figure_path) # ### d. Comparison # Based on the results of parts a and b, how do these centralities differ from each other? To answer the questions, you should pick some representative nodes and try to explain why different centrality measures rank these nodes # differently regarding their centralities. In your answer, briefly all the networks visualized in part c. # In[ ]:
646c429ff71aec515083c840a9375a170e153d21
Kieran-Egan/GlobalHack
/rps.py
1,138
4.1875
4
import random print("Welcome to Rock Paper Scissors! Type the number that corresponds to the item you want to choose.") player = input("1 = Rock, 2 = Paper, 3 = Scissors, Shoot! ") print("Your choice is:") if player == 1: print("Rock") elif player == 2: print("Paper") elif player == 3: print("Scissors") else: print("You didn't type in a valid number. Try again!") # break break break break break break break break break break break break break print("The computer chose:") diceThrow = random.randrange(1, 3) computer = diceThrow if computer == 1: print("Rock") elif computer == 2: print("Paper") elif computer == 3: print("Scissors") else: print("You didn't type in a valid number. Try again!") # break break break break break break break break break break break break break if player - computer == -1: print("You lost. Try again!") elif player - computer == -2: print("You win!") elif player - computer == 0: print("You tied") elif player - computer == 1: print("You win!") elif player - computer == 2: print("You lost. Try again!") else: print("An error has occured!")
2ff8bacfe89d668e90b6cd3bd0304a339ded9c03
caspar/PhysicsLab
/10_Midterm/least_squares_fit.py
1,117
4.125
4
# Lab 0 # Linear Least Squares Fit # Author Caspar Lant import numpy as np import matplotlib.pyplot as plt # load csv file DATA = "MidtermSheet.csv"; measurement, pressure, temperature, uncertainty = np.loadtxt(DATA, skiprows=1, unpack=True, delimiter=','); # plot temperature vs. pressure + error bars plt.ylabel("Pressure (kPa)"); plt.xlabel("Temperature (K)"); plt.title("Temperature vs. Pressure"); plt.errorbar(pressure, temperature, uncertainty, linestyle = ':', mec='r', ms=0, ecolor = "red"); # linear least squares fit line def least_squares_fit (x, y): xavg = x.mean() slope = ( y * ( x - xavg)).sum() / (x*(x-xavg)).sum() intercept = y.mean()-slope*xavg return slope, intercept slope, intercept = least_squares_fit(temperature, pressure); # create arrays to plot y1 = slope * 200 + intercept; # y1 = m(x1) + b y2 = slope * 0 + intercept; # y2 = m(x2) + b x_range = [0, 200]; # array of x values y_range = [y2, y1]; # array of y values print("slope: %d intercept: %d", slope, intercept) # show the graph plt.plot(y_range, x_range, color="blue"); plt.show();
e3c5b84cf361f8b972431ab7a4747506c9ede2ce
bssrdf/pyleet
/T/TaskScheduler.py
1,936
3.984375
4
''' Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks. Return the least number of units of times that the CPU will take to finish all the given tasks. Example 1: Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 Explanation: A -> B -> idle -> A -> B -> idle -> A -> B There is at least 2 units of time between any two same tasks. Example 2: Input: tasks = ["A","A","A","B","B","B"], n = 0 Output: 6 Explanation: On this case any permutation of size 6 would work since n = 0. ["A","A","A","B","B","B"] ["A","B","A","B","A","B"] ["B","B","B","A","A","A"] ... And so on. Example 3: Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2 Output: 16 Explanation: One possible solution is A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A Constraints: 1 <= task.length <= 104 tasks[i] is upper-case English letter. The integer n is in the range [0, 100]. ''' from collections import defaultdict class Solution(object): def leastInterval(self, tasks, n): """ :type tasks: List[str] :type n: int :rtype: int """ cnt = [0]*26 for t in tasks: cnt[ord(t)-ord('A')] += 1 cnt.sort() i, mx, tn = 25, cnt[-1], len(tasks) while i >= 0 and cnt[i] == mx: i -= 1 return max(tn, (mx-1)*(n+1)+25-i) if __name__ == "__main__": print(Solution().leastInterval(["A","A","A","B","B","B"], 2))
bbc89cd0cc9700d89cb9eab55afa8e340bdbc814
alexandraback/datacollection
/solutions_2464487_1/Python/xmk/circle.py
904
3.515625
4
f=open("input") ff=open("output", "w") readint=lambda :int(f.readline()) readintarray=lambda :map(int, f.readline().split()) T=readint() def slow(r,t): s=n=0 while True: s += 2*(r+2*n) +1 if s<=t: n+=1 else: return n def isqrt(x): if x < 0: raise ValueError('square root not defined for negative numbers') n = int(x) if n == 0: return 0 a, b = divmod(n.bit_length(), 2) x = 2**(a+b) while True: y = (x + n//x)//2 if y >= x: return x x = y def fast(r,t): n=(isqrt( (2*r-1)**2 + 8*t )-2*r+1)/4 return n for casex in range(T): r,t = readintarray() print >>ff, "Case #%d:"%(casex+1), fast(r,t) ff.close() print "done" """ i=1 to n (2*r+2*n-1)*n<=t 2*n*n+(2*r-1)*n - t <=0 n= -(2*r-1)+sqrt( (2*r-1)^2 + 4*2*t) /4 2*(r+2*(i-1))+1 <=t """
f6264000ce5b47699b3cb627f8548ccbb14d5184
mulays/PythonPractise
/PythonPractise/RegEx.py
705
3.78125
4
import re # Refered link : http://www.thegeekstuff.com/2014/07/python-regex-examples string = "this is my new name \nplate" stringreg = r"this is my new name \nplate" print string print stringreg re.match(r'dog','dog cat dog mouse dog') match = re.match(r'cat','dog cat dog mouse dog') print match match = re.search(r'cat','dog cat dog cat dog') print match.group(0) match = re.findall(r'cat','dog cat dog cat dog') print match match = re.search(r'pune', 'dog cat dog cat pune cat cat cat') print match.start() print match.end() *** Remote Interpreter Reinitialized *** >>> this is my new name plate this is my new name \nplate None cat ['cat', 'cat'] 16 20 >>>
d17b9895fe5c0d05370dae7c23251c8c899223c7
godringchan/Python_base_GodRing
/old/异常的处理.py
267
3.515625
4
class BigError(BaseException): pass def big(): b = input("int") b = int(b) try: if b > 100: raise BigError else: print("right") except BigError: print("cuowu") if __name__ == "__main__": big()
5e0ba62968c405d003d2dc67c1141206c6887c4f
tharunsai241/python_ds
/selection_sort.py
693
3.953125
4
print("selection sort") ar=[176,-272,-272,-45,269,-327,-945,176] #->[0,1,6,64,12]->[0,1,6,12,64] #swap 1st element ->last #increment counter #considering the first element itself min index as it is sorted for i in range(len(ar)): min=i #we assumed the first element is in right place(sorted) #print(min) #this for is for traversing and then selecting the minimum element for j in range(i+1,len(ar)): if ar[min] > ar[j]: #we assigned the minimum index now if not this condition will not satisfy stays out itself min=j #swapping the elements as well as incrementing the counter ar[i],ar[min]=ar[min],ar[i] print(ar)
a413996c648729400a710513c30e381f0b081242
Lishitha/python-projects
/ifexmpl.py
390
3.953125
4
"""num = int(input("enter a number")) if num < 0: print("nmbr is negtv") elif num == 0: print("nmbr is zero") else: print("nmber id postv")""" menu = ["meals","biriyani","ghee rice"] print(menu) order =int(input("menu number : ")) if order == 1: print("meals") elif order == 2: print("biriyani") elif order == 3: print("ghee rice") else: print("not available")
d2f6c5b3932a3bc65cc50eb30bbee08e117705ba
zarkle/code_challenges
/fcc_pyalgo/03_largest_sum.py
801
3.9375
4
""" Largest Sum Take an array with positive and negative integers and find the largest continuous sum of that array. https://leetcode.com/problems/maximum-subarray/ """ def largest_sum(nums): if not nums: return largest = temp = nums[0] temp = nums[0] for num in nums[1:]: if temp + num > num: temp += num else: temp = num if temp > largest: largest = temp return largest # youtube solution--slower but slightly less memory used def largest_sum(nums): if not nums: return largest = temp = nums[0] for num in nums[1:]: temp = max(temp + num, num) largest = max(temp, largest) return largest print(largest_sum([7, 1, 2, -1, 3, 4, 10, -12, 3, 21, -19])) # returns 38
e754afd1fa6bde7bebad7c632da837e626230d46
keepangry/ai_algorithm
/ProbabilisticGraphicalModel/MaximumEntropy/character_tagging.py
1,323
3.546875
4
# encoding: utf-8 ''' @author: yangsen @license: @contact: 0@keepangry.com @software: @file: character_tagging.py @time: 18-10-2 下午1:03 @desc: 迈向 充满 希望 的 新 世纪 —— 一九九八年 新年 讲话 ( 附 图片 1 张 ) ==> 迈/B 向/E 充/B 满/E 希/B 望/E 的/S 新/S 世/B 纪/E —/B —/E 一/B 九/M 九/M 八/M 年/E 新/B 年/E 讲/B 话/E (/S 附/S 图/B 片/E 1/S 张/S )/S ''' import codecs import sys def character_tagging(input_file, output_file): input_data = codecs.open(input_file, 'r', 'utf-8') output_data = codecs.open(output_file, 'w', 'utf-8') for line in input_data.readlines(): word_list = line.strip().split() for word in word_list: if len(word) == 1: output_data.write(word + "/S ") else: output_data.write(word[0] + "/B ") for w in word[1:len(word) - 1]: output_data.write(w + "/M ") output_data.write(word[len(word) - 1] + "/E ") output_data.write("\n") input_data.close() output_data.close() if __name__ == '__main__': if len(sys.argv) != 3: print("Please use: python character_tagging.py input output") sys.exit() input_file = sys.argv[1] output_file = sys.argv[2]
135e79eeba26824596c4524b22c127ce2d76080b
davychiu/brainfood
/project_euler/problem7.py
302
3.765625
4
def sqrt(n): return n**0.5 def isprime(n): for x in range(2, int(sqrt(n))+1): if n % x == 0: return False return True primes = [2,3,5,7,11,13] n = max(primes) + 2 while len(primes) < 10002: if isprime(n): primes.append(n) n = n + 2 print primes[10000]
55d38a18dd2fa1aa5e7209ca72c06baf85299fae
Darshnadas/100_python_ques
/DAY13/day13.49.py
581
4.1875
4
""" Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. """ class Shape: def __init__(self): pass def area(self): return 0 class Square(Shape): def __init__(self,l): self.length = l def area(self): return self.length * self.length l = int(input("Enter a length: ")) ar = Square(l) print(ar.area()) print(Square(l).area())
ceebe6d12081a58b9854972b9848a315575a443e
saltosaurus-zz/PUMA
/Functions/SLDTperceptron.py
1,687
3.859375
4
## A single-layer, dual-target perceptron ### INPUT: numAttributes is the number of features we're looking at # Examples is a list of feature vectors # Targets is a list of binary (0 or 1) target values for the given examples ### OUTPUT: A list of weights that has a length equal to numAttributes import dotProduct def perceptron(numAttributes, Examples, Targets): print "Computing weights..." weight = [] eta = 0.1 # Learning rate epsilon = 0.5 # Threshold value passNum = 1 for i in range(numAttributes): # Initialize weights to 0 weight.append(0.0) error = 1 error_count = -1 iteration = 1 errors = [] while error_count < 30: # Until our weights are perfect... print "On pass number {0}...".format(passNum) passNum += 1 error_count = 0 for i in range(len(Examples)): # Go through each example... dotProd = dotProduct.dotProduct(Examples[i],weight) # Compute a dot product of the example in question and the current weight vector result = dotProd > epsilon # Is the product closer to 1 or 0 and class accordingly error = Targets[i] - result # Is the classification wrong? if error != 0: error_count += 1 for j in range(len(weight)): weight[j] += eta * error * Examples[i][j] # Update weights if it was wrong errors.append([iteration,error_count]) iteration += 1 if error_count < 25: break f = open("../DataFiles/errors.txt",'w+') # Record the errors for value in errors: print>>f,value f.close() return weight
d4f879560088a06b251b25eb95eba9aa137f6bb1
niranjan-nagaraju/Development
/python/codechef/collatz.py
282
3.671875
4
#!/usr/bin/python def collatz(n): len = 0 while n != 1: if (n & 1): n = 3*n + 1 else: n = n / 2 len = len + 1 return len+1 max = 0 for i in range(1,1000001): num = collatz(i) if (num > max): max = num maxnum = i # print i, num, max, maxnum print max, maxnum
6fff9f57b22b14a265bf6d347d6e45a6c6332700
JakeHuneau/ProjectEuler
/PE55.py
632
3.5625
4
def check_palindrome(st): return str(st) == str(st)[::-1] def add_reverse(i): return i + int(str(i)[::-1]) def check_lychrel(i, iterations): lychrel = True i = add_reverse(i) for n in range(iterations): if check_palindrome(i): lychrel = False break i = add_reverse(i) return lychrel def check_lychs(check_to): lychs = [] for i in range(1, check_to+1): if check_lychrel(i, 50): lychs.append(i) return lychs if __name__ == '__main__': lychs = check_lychs(10000-1) print(len(lychs))
bfcadc65357ebbb36757e88777ace60d3c5f339d
Einar-Storvestre/min-python
/kem e best .py
1,513
3.5
4
import turtle wn = turtle.Screen() bird = turtle.Turtle() bird.speed(13) bird.pensize(4) bird.color("black") bird.setpos(-75, 0) bird.fillcolor("pink") bird.begin_fill() for i in [0, 1, 2]: bird.circle(30, 360) bird.forward(1) bird.forward(174) bird.left(120) bird.end_fill() bird.penup() bird.forward(175) bird.pendown() bird.begin_fill() bird. left (300) for i in [0, 1, 2]: bird.circle(30, 360) bird.forward(175) bird.left(120) bird.fillcolor("pink") bird.end_fill() bird.forward(25) bird.right(90) bird.fillcolor("PeachPuff") bird.begin_fill() bird.end_fill() #for i in [0, 1, 2]: #bird.fd(125) #bird.left(90) bird.end_fill() bird.pendown() bird.color("orange") bird.fillcolor("white") bird.begin_fill() bird.end_fill() bird.hideturtle() bird.penup() bird.forward(300) bird.pendown() bird.left(90) bird.forward(100) bird.left(90) bird.forward(100) bird.back(100) bird.left(90) bird.forward(100) bird.left(270) bird.forward(100) bird.backward(100) bird.left(270) bird.forward(50) bird.left(90) bird.forward(100) bird.penup() bird.forward(50) bird.pendown() bird.left(90) bird.forward(50) bird.back(100) bird.forward(100) bird.penup() bird.forward(20) bird.pendown() bird.fillcolor("pink") bird.begin_fill() bird.circle(15, 360) bird.end_fill() style = ('Courier', 30, 'italic') bird.write('kem e best!', font=style, align='center') bird.penup() bird.left(90) bird.forward(100) bird.pendown() bird.write('einar!', font=style, align='center') wn.exitonclick()
db0072f363dda67b8a66117c8e3444c06b4ed0ac
Devlan/learn_python
/double_num().py
169
3.640625
4
# coding: utf-8 def double_num(): j =1 while j <= 100: if j%2 == 0: print(j) j +=1 else: j += 1
2f494fc42df03821cda5598c6fed49a10253354d
FernandoPicazo/sfdc_api
/sfdc_api/utils/string_utils.py
241
3.5
4
import re def camel_to_snake_case(in_string): regex_str = r"(.+?)([A-Z])" def match_to_snake(match): return match.group(1).lower() + '_' + match.group(2).lower() return re.sub(regex_str, match_to_snake, in_string, 0)
1049a5173800efb9d7777eab12d9ba9c306b1788
neeraj-haresh-harjani/Python-Image-Classification
/Image_Classification.py
11,628
3.59375
4
import numpy as np from sklearn.datasets import fetch_openml #mnist_784 is the dataset of images that are 28x28 #Bunch is a dictionary containing objects, key-data container pair mnist = fetch_openml('mnist_784') #data table is 2 by 2 array with 70,000 images, each image is represented by a #row of 784 numbers, why 784? coz images are 28x28=784 number or 784 features in ML terms #All 784 numbers are single array, see lab5 YT video data = mnist['data'] target= mnist['target'] #Graphical tool from matlab import matplotlib import matplotlib.pyplot as plt #A random digit some_digit = data[36000] some_digit_image = some_digit.reshape(28,28) from PIL import Image im = Image.open('tesla.png') #tesla_np is 3dimensional array - width,height and depth because image is color image tesla_np = np.array(im) #np.zeroes creates a numpy array full of zeroes #exmp is 3 dimensional rgba array exmp = np.zeros([100,200,4], np.uint8) exmp[: ,:100] = [255, 0, 0, 255] exmp[:,100:] = [0, 0, 255, 255] #Image class is used to convert it into image myimg = Image.fromarray(exmp) myimg.save('myimg3.png') exmp[:,:100,3]=np.arange(300,400) exmp[:,100:,3]=np.arange(450,550) myimg4 = Image.fromarray(exmp) myimg.save('myimg4.png') tesla_np[:,:,1]=0 tesla2 = Image.fromarray(tesla_np) tesla2.save('tesla3.png') sdi = Image.fromarray(some_digit_image) #imshow is image show plt.imshow(sdi) plt.axis('off') plt.show() target[36000] #cmap is color map, to put color in variation of number, 5 will be light, 100 will be dark #range of colors for numbers #matplotlib.cm.binary is binary colors ( black and white) #matplotlib.cm.spring is pink and yellow #interpolation is blending of colors plt.imshow(some_digit_image,cmap=matplotlib.cm.spring,interpolation='nearest') plt.axis('off') plt.show() data_train=data[:60000] target_train = target[:60000] data_test = data[60000:] target_test = target[60000:] np.unique(some_digit ,return_counts=True) np.random.permutation(4) shuffle = np.random.permutation(60000) data_train=data_train[shuffle] target_train=target_train[shuffle] target_train_5 = target_train == '5' np.unique(target_train_5) from sklearn.linear_model import SGDClassifier sgd = SGDClassifier(random_state=100) sgd.fit(data_train, target_train_5) sgd.predict([some_digit]) #This is Cross Validation. we use k-folds here. k folds is number of times #training data will be spilt, and each spilt will be considered as test #data to ensure data is not biased sub_all = np.random.permutation(60000) sub_1 = sub_all[0:20000] sub_2 = sub_all[20000:40000] sub_3 = sub_all[40000:60000] sub_1[0:5] sub_2[0:5] sub_3[0:5] d_train_1 = data_train[sub_1] d_train_2 = data_train[sub_2] d_train_3 = data_train[sub_3] t_train_1 = target_train_5[sub_1] t_train_2 = target_train_5[sub_2] t_train_3 = target_train_5[sub_3] #axis=0 is used to command that just stack a np array on top of other #Iteration 1 where second and third subset are training and 1st subset is test cd1 = np.append(d_train_2 , d_train_3 , axis=0) ct1 = np.append(t_train_2 ,t_train_3 ,axis=0) sgd.fit(cd1, ct1) pred1 = sgd.predict(d_train_1) #Data container must be of same dimension to do vector maths; here pred1 and t_train_1 has the same length #hence we can do vector maths and use pred1 = t_train_1 #when we apply sum function for true or false, sum functions adds up true as 1 and false as 0 n_correct = sum(pred1==t_train_1) n_correct/len(pred1) #0.96565 #waj = np.arange(5) #trump = np.array([0,2,2,5,4]) #sum(waj==trump) #Iteration 2 where first and third subset are training and 2nd subset is test cd2 = np.append(d_train_1 , d_train_3 , axis=0) ct2 = np.append(t_train_1 ,t_train_3 ,axis=0) sgd.fit(cd2, ct2) pred2 = sgd.predict(d_train_2) n_correct2 = sum(pred2==t_train_2) n_correct2/len(pred2) #0.9613 #Iteration 3 where first and second subset are training and 3rd subset is test cd3 = np.append(d_train_1 , d_train_2 , axis=0) ct3 = np.append(t_train_1 ,t_train_2 ,axis=0) sgd.fit(cd3, ct3) pred3 = sgd.predict(d_train_3) n_correct3 = sum(pred3==t_train_3) n_correct3/len(pred3) #0.9648 from sklearn.model_selection import cross_val_score cross_val_score(sgd,data_train ,target_train_5 ,cv=3,scoring='accuracy') #array([0.9546, 0.9586, 0.9673]) pred1[(pred1==True) & (t_train_1==True)] = False pred2[(pred2==True) & (t_train_2==True)] = False pred3[(pred3==True) & (t_train_3==True)] = False n_correct = sum(pred1==t_train_1) n_correct/len(pred1) #0.8952 n_correct = sum(pred2==t_train_2) n_correct/len(pred2) #0.88555 n_correct = sum(pred3==t_train_3) n_correct/len(pred3) #0.9025 from sklearn.model_selection import cross_val_predict predict_5=cross_val_predict(sgd,data_train,target_train_5,cv=3) len(predict_5) np.unique(predict_5) from sklearn.metrics import confusion_matrix confusion_matrix(target_train_5 ,predict_5) #array([[53433, 1146], # [ 1244, 4177]]) #precision score = TP/(TP+FP) -> accuracy of +ve predictions #recall score = TP/(TP+FN); its also called sensitivity or True positive rate (TPR) #5s precision = 3939/(3939 + 580) #non-5s precision = 53999/(53999+1482) from sklearn.metrics import precision_score , recall_score precision_score(target_train_5 ,predict_5) #0.7847078715010333 recall_score(target_train_5 ,predict_5) #0.7705220439033389 #f1 score is harmonic mean F1 = 2/((1/precision) + (1/recall)) #= 2(precision*recall/(precision+recall)) #= TP/(TP + ((FN+FP)/2)) from sklearn.metrics import f1_score f1_score(target_train_5 ,predict_5) #0.7775502606105734 #ended at slide 34 class_scores=cross_val_predict(sgd,data_train,target_train_5,cv=3,method='decision_function') class_scores from sklearn.metrics import precision_recall_curve precisions, recalls, thresholds = precision_recall_curve(target_train_5, class_scores) #matplotlib example x=np.array([1,2,3,4,5]) plt.plot(x) plt.show() y=x**2 y plt.plot(x,y,label='y') plt.legend() plt.show() z=np.array([5,4,3,2,1]) plt.plot(x,y,label='y') plt.plot(x,z,label='z') plt.legend() plt.show() ############### #Precision and recalls have 1 extra value purely for aesthetics; for graphs len(thresholds) len(precisions) len(recalls) precisions[-1] recalls[-1] #x=[1,2,3,4,5] #x[-3] #x[:-1] plt.plot(thresholds,precisions[:-1],label='precisions') plt.plot(thresholds,recalls[:-1],label='recalls') plt.legend() plt.show() #xlim and ylim are functions to set x or y axis from 0 to 1 plt.plot(recalls,precisions) plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0 ,1]) plt.xlim([0 ,1]) plt.show() precisions[precisions>=.9] thresholds[precisions[:-1]>=.9] threshold_90=thresholds[precisions[:-1]>=.9].min() predict_5_90=class_scores>threshold_90 np.unique(predict_5_90) precision_score(target_train_5 ,predict_5_90) #0.9002812579902838 recall_score(target_train_5 ,predict_5_90) #0.6495111603025272 #Receiving Operating Characteristics (ROC); it uses recall vs FPR from sklearn.metrics import roc_curve fpr, recall, thresholds = roc_curve(target_train_5,class_scores) #plt.aaxis is similar to lim plt.plot(fpr,recall) plt.plot([0,1],[0,1]) plt.axis([0 ,1 ,0 ,1]) plt.xlabel('False Positive Rate') plt.ylabel('Recall') plt.show() #Diagonal line is the 50% AUC #AUC is area under curve from sklearn.metrics import roc_auc_score roc_auc_score(target_train_5,class_scores) #.9623642844389065; coz we have few positive 5s #We use PR curve when we have much less actual 5s; or we care about False positives #ROC is used otherwise from sklearn.ensemble import RandomForestClassifier rfc = RandomForestClassifier(random_state=100) #predict_proba doent give you scores; it gives probability whether it is non 5 or it is 5 forest_scores=cross_val_predict(rfc,data_train,target_train_5,cv=3,method='predict_proba') forest_scores[0] fpr_f, recall_f, thresholds_f = roc_curve(target_train_5,forest_scores[:,1]) plt.plot(fpr,recall,label='sgd') plt.plot([0,1],[0,1]) plt.plot(fpr_f,recall_f,label='rf') plt.axis([0 ,1 ,0 ,1]) plt.xlabel('False Positive Rate') plt.ylabel('Recall') plt.show() roc_auc_score(target_train_5,forest_scores[:,1]) #0.9922931870858716 predict_5_rf=cross_val_predict(rfc,data_train,target_train_5,cv=3) precision_score(target_train_5 ,predict_5_rf) #0.9871368374362386 recall_score(target_train_5 ,predict_5_rf) #0.8210662239439218 f1_score(target_train_5 ,predict_5_rf) #0.8964753272910373 sgd.fit(data_train,target_train) sgd.predict([some_digit]) #Here we get 4 as the highest value, so some digit is 4 scores = sgd.decision_function([some_digit]) #array([[-836368.4535247 , -461981.66956632, -660256.15197058, # -148855.65250873, -137458.04986937, -154654.76568534, # -864502.26667054, -245167.9063152 , -149510.01775103, # -233700.77221455]]) #argmax gives max values of scores np.argmax(scores) sgd.classes_ #array(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], dtype='<U1') from sklearn.multiclass import OneVsOneClassifier ovo=OneVsOneClassifier(SGDClassifier(random_state=100)) ovo.fit(data_train,target_train) ovo.predict([some_digit]) len(ovo.estimators_) ovo.decision_function([some_digit]) #array([[ 1.5 , 4.01086892, 0.50210079, 5.22484016, 8.31545536, # 5.11411311, -0.43998285, 5.13308383, 7.3219439 , 8.3175768 ]]) cross_val_score(sgd,data_train ,target_train ,cv=3,scoring='accuracy') #array([0.86552689, 0.86179309, 0.86117918]) import pandas as pd predict_m=cross_val_predict(sgd,data_train,target_train,cv=3) ps =precision_score(target_train ,predict_m,average=None) rs =recall_score(target_train ,predict_m,average=None) df = pd.DataFrame({'precision':ps,'recall':rs}) precision_score(target_train ,predict_m,average='macro') recall_score(target_train ,predict_m,average='macro') precision_score(target_train ,predict_m,average='micro') recall_score(target_train ,predict_m,average='micro') rfc.fit(data_train,target_train) rfc.predict([some_digit]) rfc.predict_proba([some_digit]) predict_rf=cross_val_predict(rfc,data_train,target_train,cv=3) psrf =precision_score(target_train ,predict_rf,average=None) rsrf =recall_score(target_train ,predict_rf,average=None) dfrf = pd.DataFrame({'precision':psrf,'recall':rsrf}) predict_o=cross_val_predict(ovo,data_train,target_train,cv=3) pso =precision_score(target_train ,predict_o,average=None) rso =recall_score(target_train ,predict_o,average=None) dfo = pd.DataFrame({'precision':pso,'recall':rso}) a=np.array([5,8,2,6,10,5]) a.mean() a.std() from sklearn.preprocessing import StandardScaler scaler = StandardScaler() data_train_s = scaler.fit_transform(data_train) data_train[:5] #array([[0., 0., 0., ..., 0., 0., 0.], # [0., 0., 0., ..., 0., 0., 0.], # [0., 0., 0., ..., 0., 0., 0.], # [0., 0., 0., ..., 0., 0., 0.], # [0., 0., 0., ..., 0., 0., 0.]]) cross_val_score(sgd,data_train_s ,target_train ,cv=3,scoring='accuracy') #array([0.91016797, 0.90904545, 0.91078662]) predict_ms=cross_val_predict(sgd,data_train_s,target_train,cv=3) pss =precision_score(target_train ,predict_ms,average=None) rss =recall_score(target_train ,predict_ms,average=None) dfs = pd.DataFrame({'precision':pss,'recall':rss}) cnf=confusion_matrix(target_train ,predict_ms) plt.imshow(cnf, cmap = plt.cm.gray) plt.plot() plt.imshow(cnf, cmap = plt.cm.spring) plt.plot() cnf.sum() cnf.sum(axis=1) #array([5923, 6742, 5958, 6131, 5842, 5421, 5918, 6265, 5851, 5949]) row_sums=cnf.sum(axis=1,keepdims=True) cnf_p = cnf/row_sums plt.imshow(cnf_p, cmap = plt.cm.gray) plt.plot() np.fill_diagonal(cnf_p,0) plt.imshow(cnf_p, cmap = plt.cm.gray) plt.plot() plt.imshow(cnf_p, cmap = plt.cm.spring) plt.plot()
cc6eed1656c5f7fe6e675aa79af467b33ac7dfbf
Greensly/InfoGeneral
/Python Exercise/Exercises N°1/longitudCadena.py
454
3.96875
4
matriz = [] filas = int(input("Cantidad de Filas: ")) Columnas = int(input("Cantidad de Columnas: ")) for i in range(filas): matriz.append([0]*Columnas) for x in range (filas): for y in range(Columnas): matriz[x][y]= int(input("Ingrese número para fila: [%i] columna [%i]"%(x,y))) print (matriz) print (len(matriz)) #print (matriz[0][0]) #print (matriz[0][1]) #print (matriz[0][2]) #print (matriz[0][3]) """Otro tipo de comentario"""
255d7a66f4b37947bd99e0ab8515898b72b6e77f
meghnaraswan/PythonAssignments
/Ch4_Strings/palindrome2.py
679
4.21875
4
#palindromes import string #get user input original_str = input("Input a string: ") #process string for plaindrome check #make string lowercase modified_str = original_str.lower() #remove punctuation and whitespace bad_chars = string.punctuation + string.whitespace for char in bad_chars: #iterate over bad character string modified_str = modified_str.replace(char, "") #plaindrome visualization print("Original string: "+original_str) print("Modified string: "+modified_str) print("Reversed string: "+modified_str[::-1]) #check forward and reverse if modified_str == modified_str[::-1]: print("Palindrome!") else: print("Fail! You do not have a palindrome.")
919d34d7ba37773c9010445fea6e9d77d073c41f
Pau1Robinson/asteroids
/main.py
4,386
3.71875
4
#!/usr/bin/env python3 ''' ########################### # # # PyGame Asteroids # # # ########################### ''' import pygame import asteroids_var import asteroids_classes #### Set everything up #### # initialise pygame pygame.init() #Define the screen, display caption and clock screen = pygame.display.set_mode((asteroids_var.WIDTH, asteroids_var.HEIGHT)) pygame.display.set_caption("Asteroids") clock = pygame.time.Clock() #Initialise classes ship = asteroids_classes.space_ship(512, 384, 270) bullets = asteroids_classes.bullets() asteroids = asteroids_classes.asteroids() #Initialise fonts my_font = pygame.font.SysFont(asteroids_var.font_name, asteroids_var.font_px) game_over_font = pygame.font.SysFont(asteroids_var.font_name, 100) #Declare the varables for tracking the score and state of the ship score = 0 ship_dead = False #Declare the bools to track key presses d_press = False a_press = False w_press = False s_press = False q_press = False e_press = False p_press = False space_press = False #### Game loop #### running = True while running: #FPS limit clock.tick(asteroids_var.FPS) #### Game loop part 1: Event handling ##### for event in pygame.event.get(): if event.type == pygame.QUIT: running = False break elif event.type == pygame.KEYDOWN: #Set the key presses to True when the key is pressed if event.key == pygame.K_d: d_press = True elif event.key == pygame.K_a: a_press = True elif event.key == pygame.K_w: w_press = True elif event.key == pygame.K_s: s_press = True elif event.key == pygame.K_q: q_press = True elif event.key == pygame.K_e: e_press = True elif event.key == pygame.K_SPACE: space_press = True elif event.key == pygame.K_p: p_press = True elif event.type == pygame.KEYUP: #Set the key presses to False when the key is released if event.key == pygame.K_d: d_press = False if event.key == pygame.K_a: a_press = False if event.key == pygame.K_w: w_press = False elif event.key == pygame.K_s: s_press = False elif event.key == pygame.K_q: q_press = False elif event.key == pygame.K_e: e_press = False #### Game loop part 2: Updates ##### #Checks if the keys are press and call the ship methods if they are if e_press is True: ship.rotate_right() if q_press is True: ship.rotate_left() if w_press is True: ship.move_forward() if s_press is True: ship.move_backward() if d_press is True: ship.move_right() if a_press is True: ship.move_left() if p_press is True: pygame.image.save(screen, "screenshot.jpg") if space_press is True: bullets.bullet_fired(ship.shoot()) space_press = False #### Game loop part 3: Draw ##### screen.fill(asteroids_var.WHITE) #Check if the ship is alive if ship_dead is False: #Draw the ship, bullets and add new asteroids ship.draw_ship() ship_dead = ship.check_collision(asteroids.list_asteroids) bullets.draw_bullets() asteroids.add_asteroids() score += (asteroids.asteroid_collision(bullets.list_bullets)) #Draw the asteroids and update the score asteroids.draw_asteroids() #Check if the ship is dead and show the game over message if it is if ship_dead is True: game_over_message = game_over_font.render(f'You Died', True, (255, 0, 0)) screen.blit(game_over_message, (350, 200)) #Render the fps counter and the score in the top left corner fps = my_font.render(str(f'{int(clock.get_fps())} score: {str(score)}'), True, (0,0,0)) screen.blit(fps, (10, 10)) # after drawing, make the drawing visible pygame.display.flip() #### Clean up and close program #### # close the window pygame.quit()
353c79d58ce0f80691b93ea06445b7e8ac8c5952
jmachuca131281/Python
/pythonProject/algoritmo4.py
255
4.1875
4
caracter = str(input(print("Ingrese un caracter: "))) if "a" == caracter or "e" == caracter or "i" == caracter or "o" == caracter or "u" == caracter: print("El carácter ingresado es Vocal") else: print("El carácter ingresado NO es una vocal")
a4e9a651ca5c2140249d55b2b94e82e81ad9653e
jfgr27/Decision-Tree-Assignment
/eval.py
9,241
3.890625
4
############################################################################## # CO395: Introduction to Machine Learning # Coursework 1 Skeleton code # Prepared by: Josiah Wang # # Your tasks: # Complete the following methods of Evaluator: # - confusion_matrix() # - accuracy() # - precision() # - recall() # - f1_score() ############################################################################## import numpy as np import dataReader as dr import classification as cp class Evaluator(object): """ Class to perform evaluation """ @staticmethod def getAccuracyOfDecisionTree(decisionTree, attributes, groundTruths): predictions = decisionTree.predict(attributes) confusionMatrix = Evaluator.confusion_matrix(predictions, groundTruths) return Evaluator.accuracy(confusionMatrix) @staticmethod def confusion_matrix(prediction, annotation, class_labels=None): """ Computes the confusion matrix. Parameters ---------- prediction : np.array an N dimensional numpy array containing the predicted class labels annotation : np.array an N dimensional numpy array containing the ground truth class labels class_labels : np.array a C dimensional numpy array containing the ordered set of class labels. If not provided, defaults to all unique values in annotation. Returns ------- np.array a C by C matrix, where C is the number of classes. Classes should be ordered by class_labels. Rows are ground truth per class, columns are predictions. """ if not class_labels: class_labels = np.unique(annotation) confusion = np.zeros((len(class_labels), len(class_labels)), dtype=np.int) ####################################################################### # ** TASK 3.1: COMPLETE THIS METHOD ** ####################################################################### # iterate through rows and columns of the confusion matrix row = 0 col = 0 # storing count of when true letter is equal to some predicted letter for trueLetter in class_labels: for predictedLetter in class_labels: counter = 0 for index in range(np.size(prediction)): if trueLetter == annotation[index] and predictedLetter == prediction[index]: counter += 1 confusion[row][col] = counter col += 1 col %= len(class_labels) row += 1 row %= len(class_labels) return confusion @staticmethod def accuracy(confusion): """ Computes the accuracy given a confusion matrix. Parameters ---------- confusion : np.array The confusion matrix (C by C, where C is the number of classes). Rows are ground truth per class, columns are predictions Returns ------- float The accuracy (between 0.0 to 1.0 inclusive) """ ####################################################################### # ** TASK 3.2: COMPLETE THIS METHOD ** ####################################################################### # accuracy is given by instanceWhen(TRUTH == PREDICTED) / ALL EVENTS truePostive = np.trace(confusion) allEvents = np.sum(confusion) # divide by 0 check if truePostive == 0 or allEvents == 0: return 0 else: return truePostive / allEvents @staticmethod def precision(confusion): """ Computes the precision score per class given a confusion matrix. Also returns the macro-averaged precision across classes. Parameters ---------- confusion : np.array The confusion matrix (C by C, where C is the number of classes). Rows are ground truth per class, columns are predictions. Returns ------- np.array A C-dimensional numpy array, with the precision score for each class in the same order as given in the confusion matrix. float The macro-averaged precision score across C classes. """ # Initialise array to store precision for C classes p = np.zeros((len(confusion),)) ####################################################################### # ** TASK 3.3: COMPLETE THIS METHOD ** ####################################################################### # precision (per characteristic) == TRUTH / TOTAL PREDICTION THAT LETTER index = 0 for letterIndex in range(np.size(confusion[:, -1])): if np.sum(confusion[:, letterIndex]) == 0: p[index] = 0 else: p[index] = confusion[letterIndex][letterIndex] / np.sum(confusion[:, letterIndex]) index += 1 # finding average of the precision score for global macro_p = np.average(p) return p, macro_p @staticmethod def recall(confusion): """ Computes the recall score per class given a confusion matrix. Also returns the macro-averaged recall across classes. Parameters ---------- confusion : np.array The confusion matrix (C by C, where C is the number of classes). Rows are ground truth per class, columns are predictions. Returns ------- np.array A C-dimensional numpy array, with the recall score for each class in the same order as given in the confusion matrix. float The macro-averaged recall score across C classes. """ # Initialise array to store recall for C classes r = np.zeros((len(confusion),)) ####################################################################### # ** TASK 3.4: COMPLETE THIS METHOD ** ####################################################################### # recall (per characteristic) == TRUTH / TOTAL TIMES THAT WAS THE TRUE LETTER index = 0 for letterIndex in range(np.size(confusion[:, -1])): if np.sum(confusion[letterIndex]) == 0: r[index] = 0 else: r[index] = confusion[letterIndex][letterIndex] / np.sum(confusion[letterIndex]) index += 1 # finding average of the recall score for global macro_r = np.average(r) return r, macro_r @staticmethod def f1_score(confusion): """ Computes the f1 score per class given a confusion matrix. Also returns the macro-averaged f1-score across classes. Parameters ---------- confusion : np.array The confusion matrix (C by C, where C is the number of classes). Rows are ground truth per class, columns are predictions. Returns ------- np.array A C-dimensional numpy array, with the f1 score for each class in the same order as given in the confusion matrix. float The macro-averaged f1 score across C classes. """ # Initialise array to store recall for C classes f = np.zeros((len(confusion),)) ####################################################################### # ** YOUR TASK: COMPLETE THIS METHOD ** ####################################################################### precision, macro_p = Evaluator.precision(confusion) recall, macro_r = Evaluator.recall(confusion) index = 0 for letterIndex in range(np.size(confusion[:, -1])): f[index] = 2 * (precision[index] * recall[index]) / (recall[index] + precision[index]) index += 1 # finding average of the f1 for global macro_f = np.average(f) return f, macro_f @staticmethod def print_eval(train_data, test_data): data = dr.parseFile(train_data) x = data[0] y = data[1] tree = cp.DecisionTreeClassifier() tree.train(x, y) test = dr.parseFile(test_data) xtruth = test[0] ytruth = test[1] test = dr.mergeAttributesAndCharacteristics(xtruth, ytruth) predictions = tree.predict(test) e = Evaluator() a = e.confusion_matrix(ytruth, predictions) print("Confusion" + "\n" + str(a)) print("Accuracy: " + str(e.accuracy(a))) print("Recall: " + str(e.recall(a))) print("Precision: " + str(e.precision(a))) print("F1score: " + str(e.f1_score(a))) if __name__ == "__main__": print("RESULTS FOR TRAIN_FULL.TXT:") Evaluator.print_eval("data/train_full.txt", "data/test.txt") print("RESULTS FOR TRAIN_NOISY.TXT:") Evaluator.print_eval("data/train_noisy.txt", "data/test.txt") print("RESULTS FOR TRAIN_SUB.TXT:") Evaluator.print_eval("data/train_sub.txt", "data/test.txt")
3f1b1a66f0dd81481b450284fe218176a01b8080
JacobAMason/DnD
/BinaryEncodings.py
1,450
3.53125
4
# BinaryEncodings.py # Below are some Binary encodings for various client/server interactions import re class BinaryEncodings: """ returns True or False based on whether or not data is one of the binary encodings. """ def __init__(self): self.DISCONNECT = bytes("DIS", "utf-8") self.CONNECT = bytes("CON", "utf-8") self.MESSAGE = bytes("MSG", "utf-8") self.MAP = bytes("MAP", "utf-8") self._encodings = dict(self.__dict__) def parse(self, binary): """ Decodes a binary string. Returns a tuple list of data types and the data they contain. """ string = binary.decode() regexFormatStr = "(" for v in self._encodings.values(): regexFormatStr += re.escape(v.decode()) + "|" regexFormatStr = regexFormatStr[:-1] + ")" vector = re.split(regexFormatStr, string) vector.pop(0) packets = [] for i in range(0,len(vector),2): packets.append((vector[i], vector[i+1])) return packets def unpack(self, data): """ Emulates the old action of unpacking. This uses the above parsing tool, but only returns the first tuple. Why? Well.. The client can attempt to hack the server through use of the BinaryEncodings module. This prevents that. """ return self.parse(data)[0] BE = BinaryEncodings()
107e7c06cc78dba43eec43594b0828a78afaa088
nandadao/Python_note
/note/download_note/first_month/day16/exercise02.py
521
4.125
4
# 练习1:使用迭代思想,获取元组中所有元素("a","b","c") tuple01 = ("a", "b", "c") iterator = tuple01.__iter__() while True: try: item = iterator.__next__() print(item) except StopIteration: break # 练习2:使用迭代思想,获取字典中所有记录("a":1,"b":2,"c":3) dict01 = {"a": 1, "b": 2, "c": 3} iterator = tuple01.__iter__() while True: try: key = iterator.__next__() print(key,dict01[key]) except StopIteration: break
9e5e7c3a4ebae93fb0337ad9bac489c04c22b1bd
whitebeard4708/MiniProjectCZ1003
/Pandas v2.py
3,064
3.796875
4
import pandas as pd from pandas import DataFrame from load_data import * infocan = infocan.set_index('Canteen') df = df.set_index(['Canteen']) #takes in foodtype = ['Food1','food2' etc], pricerange = [lower, higher as floats/int], the search term # rating = int(1 to 5) or 0 if not specified def searchfood(foodtype, pricerange, rating, search, df): #copy the dataframe to temporary. search_df = df.copy() #filter by foodtype if foodtype != []: foodcond = search_df['Food Type'].isin(foodtype) search_df = search_df[foodcond] # filter by price range low_price = pricerange[0] high_price = pricerange[1] pricecond1 = search_df['Price'] >= low_price pricecond2 = search_df['Price'] <= high_price search_df = search_df[ pricecond1 & pricecond2 ] # filter by rating, shows all above specified rating if rating != 0: ratingcond = search_df['Rating'] >= rating search_df = search_df[ ratingcond ] # filter by menu Item if search != ' ': lst = search.lower().split() for word in lst: wordcond = search_df['Menu Item'].str.lower().str.contains(word) search_df = search_df[wordcond] # return the filtered DataFrame return search_df #function to sort by rating given the DataFrame filtered, the output is a list of indexes def sort_by_rating(filter_df): filter_df = filter_df.sort_values("Rating") return choose10(filter_df) #function to sort by price given the DataFrame filtered, the output is a list of indexes def sort_by_price(filter_df): filter_df = filter_df.sort_values("Price") return choose10(filter_df) #function to sort by distance based on the user location, the filtered DataFrame and the DataFrame containing #information about the canteen def sort_by_location(user_loc, filter_df, infocan): lst_loc = filter_df.index.unique() lst_dist = {} frames = [] for loc in lst_loc: #calculate the distance distance = ((user_loc[0] - infocan.loc[loc]['loc x'])**2 + (user_loc[1] - infocan.loc[loc]['loc y'])**2)**(1/2) #convert from bitmap to km (just giving an approximate of the distance) distance *= 0.0025 #create a new column in DataFrame to store all of the distances filter_df.at[loc,'Distance'] = distance #sort DataFrame according to the distance filter_df = filter_df.sort_values('Distance') #select top 10 location to show the user return choose10(filter_df) def choose10(filter_df): frames = [] count = 1 for loc in filter_df.index.unique(): a = filter_df.loc[loc] frames.append(a) if count == 10: break count += 1 if frames !=[]: #concatenate all the DataFrames selected return pd.concat(frames) else: return pd.DataFrame() result = searchfood([], [1,100], 1, 'Rice', df) #t = sort_by_location((441,430), result, infocan) #t = sort_by_price(result) #print(t)
6ac203950aa85af86763098637af1adadb4b5449
rogeriosilva-ifpi/teaching-tds-course
/programacao_estruturada/20192_166/Bimestral2_166_20192/Parte_1/Klebson e Izequiel/IPVA.py
502
3.890625
4
v_atual = int(input('Digite o valor atual do veículo: ')) ano_fabricacao = float(input('Digite o ano de fabricação: ')) ano= 2020 - ano_fabricacao if ano <5: v_fin = v_atual * (2.5/100) print('é o valor com IPVA a ser pago',v_fin) elif ano == 5 and ano <11: des = v_atual * (15/100) print(des,'é o valor com o desconto do carro a ser pago') elif ano == 11 and ano <16: seg_des = v_atual * (20/100) print('esse é o valor a ser pago: ',seg_des) else: print('Isento')
32b615f1d5e11c68d947a3bf96c7e23bc55455b1
AdamZhouSE/pythonHomework
/Code/CodeRecords/2529/60608/241229.py
526
3.8125
4
def swap(a, b): tem = array[a] array[a] = array[b] array[b] = tem def func9(start, end): if start == end: item = int("".join(array[:])) if item & (item - 1) == 0: flag[0] = "true" else: for index in range(start, end): swap(index, start) func9(start + 1, end) if flag[0] == "true": break swap(index, start) string = input() array = list(string) n = len(array) flag = ["false"] func9(0, n) print(flag[0])
1482e6d12e8fd8898b5f624c4a07654e5def740f
young24601/leetcode
/archive pre 2021/013. Roman to Integer.py
1,163
3.78125
4
#13. Roman to Integer #Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ #use similar strategy to #12 romanvalues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] intvalues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] index = 0 output = 0 ct = 0 while index < len(s): r = romanvalues[ct] i = intvalues[ct] if len(r) == 1 and r == s[index]: output += i index += 1 elif len(r) == 2 and index < len(s)-1 and r == s[index] + s[index+1]: output += i index += 2 else: ct += 1 return output s = Solution() assert s.romanToInt("III") == 3 assert s.romanToInt("IV") == 4 assert s.romanToInt("IX") == 9 assert s.romanToInt("LVIII") == 58 assert s.romanToInt("MCMXCIV") == 1994 assert s.romanToInt("MMMCMXCIX") == 3999 assert s.romanToInt("DCXXI") == 621
f6fdd2df57892d1eaebdad5567bb87bdb0c75943
AartiBhagtani/Algorithms
/recursion/sort_array.py
389
3.65625
4
from sys import stdin n = int(stdin.readline()) y = [int(x) for x in (stdin.readline().split())] def rec_sort(arr): if len(arr) == 1: return temp = arr.pop() rec_sort(arr) insert(arr, temp) def insert(arr, temp): if(len(arr) == 0 or arr[-1] <= temp): arr.append(temp) return temp2 = arr.pop() insert(arr, temp) arr.append(temp2) rec_sort(y) print(y)
8447c6afee790c022be93a0d947c679a82bf1491
WangYue7477/Python3Learn
/Base/SortedLearn.py
352
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/11 23:35 # @Author : WangYue # @File : SortedLearn.py # @Software: PyCharm l = [21,54,-98,32,-5] print(sorted(l)) print(sorted(l,key=abs)) name = ['bob', 'about', 'Zoo', 'Credit'] print(sorted(name)) print(sorted(name,key=str.lower)) print(sorted(name,key=str.lower,reverse=True))
1ad61adad79cb2e5c64106daf7ee4597cbc000b4
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/gmdnom011/question4.py
3,294
4.0625
4
# Program to find all palindromic primes in a given range # Nomsa Gamedze # 7 May 2014 import sys sys.setrecursionlimit (30000) import math def reverse_word(word, word2): if len(word2) < len(word): x = len(word) - len(word2) - 1 word2.append(word[x]) reverse_word(word, word2) return word2 def check_equal(wordA, wordB, a): if wordA[a] == wordB[a]: b = len(wordA) - 1 if a < b: a += 1 check_equal(wordA, wordB, a) return True else: return False def find_primes(x, primes, a, y): # x is the starting point, y is the ending point x = x primes = primes a = a y = y if x < y: if x == 2 or x == 3: primes.append(x) x += 1 find_primes(x, primes, 2, y) elif x == 1: x += 1 find_primes(x, primes, 2, y) if a <= int(math.sqrt(x)): if x % a == 0: x += 1 find_primes(x, primes, 2, y) if x % a != 0: a += 1 find_primes(x, primes, a, y) if a >= int(math.sqrt(x)): if x % a != 0: primes.append(x) x +=1 find_primes(x, primes, 2, y) if x % a == 0: x +=1 find_primes(x, primes, 2, y) primes = set(primes) primes = list(primes) return primes def is_palindrome(word): word2 = [] word = list(word) word3 = reverse_word(word, word2) answer = check_equal(word3, word, 0) return answer def keep_palindromes(many_primes, i, result): many_primes = many_primes i = i result = result prime = str(many_primes[i]) if i < (len(many_primes) - 1): if ispalindrome(prime): i += 1 result.append(prime) keep_palindromes(many_primes, i, result) else: i += 1 keep_palindromes(many_primes, i, result) return result def main(): start_pt = eval(input("Enter the starting point N:"'\n')) end_pt = eval(input("Enter the ending point M:"'\n')) print("The palindromic primes are:") x = start_pt + 1 primes = find_primes(x, [], 2, end_pt) pal_primes = keep_palindromes(primes, 0, []) pal_prime_list = '\n'.join(pal_primes) print(pal_prime_list) # main()
ff517b4c477e7804891df08606d1a025c3a929ac
jvalen92/Analisis-Numerico
/SolucionDeSistemasDeEcuaciones/tareas/grajales_alzate/matriz.py
987
3.609375
4
import numpy as np class MatrizUtilities: # Libreria para realizar calculos cientificos eficientes. def __init__(self): pass def get_matriz_aumentada(self, A, b): """ Retorna la matriz aumentada Ab. """ _b = np.array(b, dtype=float) _A = np.array(A, dtype=float) _Ab = np.insert(_A, _A.shape[1], _b, axis=1) return _Ab def det(self, A): """ Retorna el determinante de la matriz A. """ _A = np.array(A, dtype=float) if _A.shape[0] != _A.shape[1]: raise "La matriz debe ser cuadrada." _det = self.__det(_A, _A.shape[0]) return _det def __det(self, A, n): if n == 1: return A[0][0] resultado = 0.0 for i in range(0, n): eliminar_columna = [c for c in range(0, n) if c != i] resultado += (-1)**i * A[0][i] * self.__det(A[1:, eliminar_columna], n - 1) return resultado
d2784e5819e4b446fab0b7a7bd246bf1da4ae8ef
saiswaruprath/PYTHON
/half.py
255
3.875
4
hrs = input("Enter Hours:") rate = input("Enter Rate:") h = float(hrs) r = float(rate) def computepay(h,r): if h == 40: return h * r elif h > 40: return (40 * r + (h-40) * 1.5 * r) p = computepay(h,r) print("Pay",p)
387b8f42674dcf41df9a110c2ded1ed1fc215e4b
Sidharth4032/CSCI-1100
/HW/HW06/hw6Part1.py
5,849
4.125
4
""" Homework 6 Part 1 The purpose of this program is to read the name of two files: the first containing a dictionary of words and the second containing a list of words to autocorrect. The program will go through the list of words of the input file and decide whether the word preexists in the dictionary file, a letter in the word must be dropped, letters in the word must be swapped, a letter in the word must be replaced, or if there is no match whatsoever. Author: Samuel Marks CSCI 1100 Spring 2018 Version 1 """ def found(dictionary,word): ''' This function takes as argunments the dictionary inputted by the user, dictionary, and the current word being read by the input file, word, amd returns True if the word preexists in the dictionary and False otherwise. ''' if word in dictionary: return True else: return False def drop(dictionary,word): ''' This function takes as argunments the dictionary inputted by the user, dictionary, and the current word being read by the input file, word, and creates a new set of "words" by dropping a letter from that word and checks if any of those new "words" are present in the dictionary. If so, a print statement indicating that a letter was dropped is printed and True is returned. Otherwise, False is returned. ''' ##converting the dictionary list into a set and creating a new set for new "words" created after a letter is dropped dictionary = set(dictionary) drop_words = set() ##for lopp to create new "words" by dropping a letter from word and to add them to drop_words for i in range(len(word)): drop = word[:i] + word[i+1:] drop_words.add(drop) ##if statement checks to see if any words in drop_words are present in the dictionary if len(drop_words & dictionary) >= 1: correct = list(drop_words & dictionary) print("{:15s} -> {:15s} :DROP".format(word,correct[0])) return True else: return False def swap(dictionary,word): ''' This function takes as argunments the dictionary inputted by the user, dictionary, and the current word being read by the input file, word, and creates a new set of "words" by swapping two consecutive letters from that word and checks if any of those new "words" are present in the dictionary. If so, a print statement indicating that letters were swapped is printed and True is returned. Otherwise, False is returned. ''' ##converting the dictionary list into a set and creating a new set for new "words" created after consecutive letters are swapped dictionary = set(dictionary) swap_words = set() ##for loop to create new "words" by swapping consecutive letters and to add them to swap_words for i in range(len(word)-1): if i == 0: swap_words.add(word[i+1]+word[i]+word[2:]) else: swap_words.add(word[:i]+word[i+1]+word[i]+word[i+2:]) ##if statement checks to see if any words in swap_words are present in the dictionary if len(swap_words & dictionary) >= 1: correct = list(swap_words & dictionary) print("{:15s} -> {:15s} :SWAP".format(word,correct[0])) return True else: return False def replace(dictionary,word): ''' This function takes as argunments the dictionary inputted by the user, dictionary, and the current word being read by the input file, word, and creates a new set of "words" by replacing a letter from that word (starting from the end of the word) with all the letters in the alphabet and checks if any of those new "words" are present in the dictionary. If so, a print statement indicating that a letter was replaced is printed and True is returned. Otherwise, False is returned. ''' ##creating a list of all letter in the alphabet, converting the dictionary list into a set, and creating a new set for new "words" created after letters are replaced letters = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k','l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v','w', 'y', 'z' ] dictionary = set(dictionary) replace_words = set() ##for loop to create new "words" by replacing each letter in word with every letter in the alphabet starting fr0m the end of the word and to add those "words" to replace_words for i in range(len(word)-1,-1,-1): list_word = list(word) for l in range(len(letters)): list_word[i] = letters[l] new = "".join(list_word) replace_words.add(new) ##if statement checks to see if any words in replace_words are present in the dictionary if len(replace_words & dictionary) >= 1: correct = list(replace_words & dictionary) print("{:15s} -> {:15s} :REPLACE".format(word,correct[0])) return True return False ##input files d_file = input("Dictionary file => ") print(d_file) i_file = input("Input file => ") print(i_file) ##creating a list of all words present in the dictionary file (later this list will be converted to a set dictionary = [] for line in open(d_file): word = line.strip() dictionary.append(word) ##creating a list of all words present in the input file (later this list will be converted to a set inputs = [] for line in open(i_file): word = line.strip() inputs.append(word) ##for loop to check the proper action that should be taken for each word for word in inputs: if found(dictionary, word) == True: print("{:15s} -> {:15s} :FOUND".format(word,word)) elif drop(dictionary, word) == True: continue elif swap(dictionary, word) == True: continue elif replace(dictionary, word) == True: continue else: print( "{:15s} -> {:15s} :NO MATCH".format(word,word))
777e60fd4bffd3938c6ab62ac21d5f310c8855ec
Madhuram-S/python-challenge
/PyParagraph/main.py
1,970
4.0625
4
# task is to create a Python script to automate the analysis of any such passage using these metrics. Your script will need to do the following: # 1. Import a text file filled with a paragraph of your choosing. # 2. Assess the passage for each of the following: # 1. Approximate word count # 2. Approximate sentence count # 3. Approximate letter count (per word) # 4. Average sentence length (in words) #Import csv package for reading and writing into files import csv import os import re wcnt = 0 def wrdCnt(txt): return len(txt.split(" ")) txtToAnalyse = ["raw_data/paragraph_1.txt", "raw_data/paragraph_2.txt"] #txtToAnalyse = ["raw_data/paragraph_2.txt"] for p in txtToAnalyse: # filename to read data from and file to write the results txtFile = os.path.join(os.path.dirname(__file__), p) with open(txtFile, "r", newline ='') as fileObj: para = fileObj.read() fileObj.close() # replace whitespace chars para1 = re.sub(r'\n\n','', para) #Count # of sentences sentences = re.split(r'(?<=[.?!\"]) ?\s*?(?=[A-Z\"])', para1, re.M) #count word in sentences wordCnt = sum([wrdCnt(t) for t in sentences]) # chrCnt_withSpaces = len(para) # spacesCnt = para.count(" ") # chrCnt_only = chrCnt_withSpaces - spacesCnt # count letters excluding spaces chrCnt_only = len(re.sub(r"[\s]", "",para)) #calculate average letter cnt avgLetterCnt = chrCnt_only / wordCnt #calculate average word cnt / sentence avgSentLen = wordCnt / len(sentences) print(f"Paragraph Analysis for paragraph {p} starting as") print("\n") print(f"{para[0:50]}...") print("------------------------------------------------------------------") print(f"Approximate word count : {wordCnt}") print(f"Approximate Sentence count : {len(sentences)}") print(f"Average letter count (per word) : {round(avgLetterCnt,1)}") print(f"Average Sentence length : {round(avgSentLen,1)}") print("------------------------------------------------------------------")
75e967620a4d3d60563d4178262231ec334b3dc3
LeaneTEXIER/Licence_2
/S3/Codage/TP2/Answers2(Tp2).py
14,632
3.96875
4
##TEXIER Léane ##Groupe 1 import struct #Question 1: #La procédure print imprime les nombres entiers en base décimale. #Le format d'impression {:x} imprime les nombres entiers en base hexadécimale avec les lettres en miniscules. #Le format d'impression {:X} imprime les nombres entiers en base hexadécimale avec les lettres en majuscules. #Le format d'impression {:o} imprime les nombres entiers en base octale. #Question 2: print ("Question 2:") print("1331 en binaire est",bin(1331)) print("1331 en octale est",oct(1331)) print("1331 en hexadécimale est",hex(1331)) print("") #Question 3: #L'expression chr(ord('0') + n) vaut n quand n est compris entre 0 et 9. #L'expression chr(ord('0') + n) vaut des caractères (virgule, point d'interrogation, lettres,...) quand n est supérieur ou égale à 10. #Question 4: #Pour n compris entre 10 et 15, chr(ord('7')+n) vaut un caractère compris entre 'A' et 'F'. #Question 5: def integer_to_digit(n): """ Retourne le chiffre hexadécimal correspondant à n sous forme de caractère :param n: Entier décimal :type n: int :return: Chiffre n en hexadécimal :rtype: str :CU: n est un entier compris entre 0 et 15 inclus :Exemple: >>> integer_to_digit(15) 'F' >>> integer_to_digit(0) '0' """ assert (type(n)==int), "Le paramètre entré n'est pas un entier" assert (0<=n<=15), "L'entier entré n'est pas compris entre 0 et 15" if n<=9: return str(n) else: return chr(ord('7')+n) #Question 6: def integer_to_string(n,b): """ Retourne l'écriture de l'entier n en base b :param n: Entier à convertir :type n: int :param b: Base dans laquelle convertir l'entier n :type n: int :return: L'entier n en base b :rtype: str :CU: Les deux paramètres sont des entiers, b est compris entre 0 et 36 et n est positif ou nul :Exemple: >>> integer_to_string(2000,16) '7D0' >>> integer_to_string(15,21) 'F' """ assert (type(n)==int), "Le nombre à convertir n'est pas un entier" assert (type(b)==int), "La base entrée n'est pas un entier" assert (0<=n), "Le nombre à convertir n'est pas positif ou nul" assert (0<=b<=36), "La base entrée n'est pas compris entre 0 et 36" if b>=10: if n<=9: return str(n) elif n<b: return chr(ord('7')+n) else: return (integer_to_string(n//b,b)+integer_to_string(n%b,b)) else: if n<b: return str(n) else: return (integer_to_string(n//b,b)+integer_to_string(n%b,b)) #Question 7: print("Question 7:") for i in range (0,21): print("{:d}".format(i),"{:s}".format(":"),"{:s}".format(integer_to_string(i,2)),"{:s}".format(integer_to_string(i,8)),"{:s}".format(integer_to_string(i,16))) #Question 8: print ("") print ("Question 8:") print("Test de l'opérateur 'et' sur 0b1010 et 0b111 :", 0b1010 & 0b111) print("Test de l'opérateur 'ou' sur 0b1010 et 0b111 :",0b1010 | 0b111) print("Test de l'opérateur 'ou exclusif' sur 0b1010 et 0b111 :",0b1010 ^ 0b111) print("Test de l'opérateur 'non' sur 0b111 :",~0b111) print("Test du décalage à gauche (de 2) sur 0b1010 :",0b1010<<2) print("Test du décalage à droite (de 3) sur 0b1010:", 0b1010>>3) #Question 9: #La signification arithmétique de l'opération logique n<<1 est une multiplication par 2 de n. #La signification arithmétique de l'opération logique n>>1 est une division par 2 de n. #Question 10: def deux_puissances(n): """ Retourne la valeur de 2**n (à l'aide d'un opérateur logique) :param n: Puissance :type n: int :return: 2**n :rtype: int :CU: n est un entier positif ou nul :Exemple: >>> deux_puissances(12) 4096 >>> deux_puissances(9) 512 """ assert (type(n)==int), "Le paramètre entré n'est pas un entier" assert (n>=0), "L'entier entré n'est pas positif ou nul" return 1<<n #Question 11: #Pour savoir si un nombre est pair, il faut d'abord transformer ce nombre en binaire, on l'appelera b. #Puis, il faut tester: ((b>>1)<<1)==b. #Si c'est True ce nombre est pair, sinon il est impair. #Question 12: def integer_to_binary_str(n): """ Retourne l'écriture binaire de l'entier n sous forme de chaîne de caractères :param n: Entier à convertir :type n: int :return: L'entier n en binaire :rtype: str :CU: n est un entier positif ou nul :Exemple: >>>integer_to_binary_str(132) '10000100' >>> integer_to_binary_str(21) '10101' """ assert (type(n)==int), "Le paramètre entré n'est pas un entier" assert (n>=0), "L'entier entré n'est pas positif ou nul" b='' if n==0: b='0' else: while n>=1: b=str(n&1)+b n=n>>1 return b #Question 13: def binary_str_to_integer(b): """ Retourne l'entier correpondant au nombre binaire b :param b: Nombre binaire à convertir :type b: str :return: L'entier b en décimal :rtype: int :CU: b doit etre un nombre binaire :Exemple: >>> binary_str_to_integer('110100') 52 >>> binary_str_to_integer('11010110101') 1717 """ assert (type(b)==str), "Le paramètre entré n'est pas une chaîne de caractères" assert ((i=='0' or i=='1') for i in b), "Le nombre entré n'est pas un chiffre binaire" n=0 for i in range(len(b)): if b[i]=='0': n=n<<1 else: n=(n<<1) | 1 return n #Question 14: def byte_to_binary(o): """ Retourne la valeur binaire sur 8 bits de l'octet entré en paramètre :param o: Octet à convertir :type o: str :return: L'octet o en binaire :rtype: str :CU: o doit être un octet :Exemple: >>> byte_to_binary(10) '00001010' >>> byte_to_binary(126) '01111110' """ assert (type(o)==int), "Le paramètre entré n'est pas un entier (octet)" assert (0<=o<256), "Le paramètre entré n'est pas un octet (valeur comprise entre 0 et 255 inclus)" b=integer_to_binary_str(o) while len(b)!=8: b='0'+b return b #Question 15: def float_to_bin (n): """ Retourne la chaine binaire correspondant au réel n :param n: Réel :type n: int or float :return: Chaine binaire du réel n :rtype: str :CU: n est un réel :Exemple: >>> float_to_bin(3.5) '01000000011000000000000000000000' >>> float_to_bin(1) '00111111100000000000000000000000' """ assert (type(n)==float or type(n)==int), "Le paramètre entré n'est pas un réel" b='' bytes_stored = struct.pack('>f', n) for i in bytes_stored: b=b+byte_to_binary(i) return b #Question 16: def change_a_bit(b,p): """ Retourne la chaine binaire b entré en remplacant le bit à la position p par son bit inverse :param b: Chaine binaire :type b: str :param p: Position du bit à inverser :type p: int :CU: b doit etre une chaine binaire et p un entier (compris entre 0 et len(b)-1) :Exemple: >>> change_a_bit('01011',2) '01111' >>> change_a_bit('010101011',1) '000101011' """ assert (type(b)==str), "Le paramètre b entré n'est pas une chaîne de caractères" assert (type(p)==int), "Le paramètre p entré n'est pas un entier" assert (0<=p<len(b)), "Le paramètre p entré doit être compris entre 0 et la longueur de la chaine b-1" return b[:p]+str(int(b[p])^1)+b[p+1:] #Question 17: def binary_to_bytes(b): """ Retourne la chaine binaire b en une liste d'entiers correspondants à chaque groupe de 8 bits contenus dans b :param b: Chaine binaire :type b: str :return: Liste d'entiers :rtype: list :CU: b est une chaine binaire ayant une taille d'un multiple de 8 :Exemple: >>> binary_to_bytes('0101101001010010') [90, 82] >>> binary_to_bytes('110101101101011111011000') [214, 215, 216] """ assert (type(b)==str), "Le paramètre b entré n'est pas une chaîne de caractères" assert (len(b)%8==0), "La longueur de la chaine b doit être un multiple de 8" l=[] while len(b)>0: bi=b[:8] l.append(binary_str_to_integer(bi)) b=b[8:] return l #Question 18: def change_a_bit_in_float(n,p): """ Retourne la valeur du réel modifié (=prend la représentation binaire de n et change son bit se trouvant à la position p) :param n: Réel à modifier :type n: int or float :param p: Position du bit à inverser :type p: int :return: Valeur du réel n modifié (inversion du bit à la position b dans la représentation binaire de n) :rtype: float :CU: n est un réel et p est un réel positif inférieur strictement à 32 (4 octets) :Exemple: >>> change_a_bit_in_float(3.5,10) 3.0 >>> change_a_bit_in_float(3.5,14) 3.53125 """ assert (type(n)==float or type(n)==int), "Le paramètre entré n'est pas un réel" assert (type(p)==int), "Le paramètre p entré n'est pas un entier" assert (0<=p<32), "p doit être un réel positif inférieur strictement à 32" b=change_a_bit(float_to_bin(n),p) l=binary_to_bytes(b) return (struct.unpack('>f', bytes(l))[0]) #Question 19: #Changement du premier bit (bit à la position 0): change_a_bit_in_float(2,0) #Le changement du premier bit entraîne un changement de signe de l'entier 2. #En effet, on change le premier bit qui désigne le signe de l'entier. #Changement du dernier bit (bit à la position 31): change_a_bit_in_float(2,31) #Le changement du dernier bit fait que le nouveau réel est très proche de 2 (mais supérieur légèrement). #En effet, on change le dernier bit de la mantisse, cela a donc un impact minime sur l'entier. #Changement du neuvième bit (bit à la position 8): change_a_bit_in_float(2,8) #Le changement du neuvième bit fait que le nombre 2 est doublé. (Il devient donc 4) #En effet, on change le dernier bit de l'exposant. Cela entraine donc une multiplication de 2 par 2**1=2. #Question 20: stream_text=open("data","r") stream_bin=open("data","rb") #Question 21: content_text=stream_text.read() content_bin=stream_bin.read() #Pour la lecture en mode texte, la longueur est de 5. #Pour la lecture en mode binaire, la longueur est de 11. #Le fichier en mode binaire est 2 fois plus long que le fichier en mode texte car chaque caractère codé en mode texte correspond à 2 octets en mode binaire (car ce sont des caractères spéciaux). #De plus, il y a un caractère de plus, pour dire que le fichier est en mode binaire. #Question 22: #La variable content_bin est de type 'bytes' (=octet) #Question 23: #content_bin[1] #Question 24: ##with open("data.out","wb") as output: ## output.write(bytes([195, 137])) ## output.close() #Question 25: #Le fichier "data.out" comporte un caractère. Cela s'explique par le fait que le caractère est un caractère accentué, il est donc codé sur 2 octets. #Question 26: #iconv --from-code ISO-8859-1 --to-code UTF-8 --output moncigale-UTF-8.txt cigale-ISO-8859-1.txt #iconv --from-code UTF-8 --to-code ISO-8859-1 --output moncigale-ISO-8859-1.txt cigale-UTF-8.txt #Question 27: #ls -l cigale-ISO-8859-1.txt #ls -l cigale-UTF-8.txt #Le fichier "cigale-ISO-8859-1.txt" a une taille de 624 octets. #Le fichier "cigale-UTF-8.txt" a une taille de 639 octets. #Il y a 15 caractères accentués dans le texte. Il y a 15 octets de différences entre les 2 fichiers. #La différence s'explique de part le fait qu'en UTF-8 chaque caractère accentué est codé sur 2 octets contrairement en ISO-8859-1 où s'est codé sur 1 octet. #Question 28: #Soit O l'octet de valeur comprise entre 160 et 255. #Pour obtenir 2 octets conformes à la consigne, il faut fare: #(((byte>>6)|192),((byte | 192) & 191)) #Le 192 vient du fait qu'en binaire 192 = '0b11000000' et le 191 qu'en binaire 191 = '0b10111111'. #Question 29: def isolatin_to_utf8(stream): """ Lit un caractère ISO-8859-1 du flux 'stream' et retourne un tuple d'un ou deux octet(s) correspondant(s) au caractère UTF-8. Si on est à la fin du fichier, retourne None :param stream: flux :return: Tuple d'un ou deux octet(s) correspondant(s) au caractère UTF-8 (ou None si fin du fichier) :rtype: tuple :CU: None """ try: byte = stream.read(1)[0] if byte<160: return (byte,) else: return (((byte>>6)|192),((byte | 192) & 191)) except IndexError: stream.close() return None #Question 30: def convert_file(source, dest, conversion): ''' Convert `source` file using the `conversion` function and writes the output in the `dest` file. :param source: The name of the source file :type source: str :param dest: The name of the destination file :type dest: str :param conversion: A function which takes in parameter a stream (opened\ in read and binary modes) and which returns a tuple of bytes. :type conversion: function ''' entree = open(source, 'rb') sortie = open(dest, 'wb') octets_sortie = conversion(entree) while octets_sortie != None: sortie.write(bytes(octets_sortie)) octets_sortie = conversion(entree) sortie.close() def convert_file_isolatin_utf8(source, dest): ''' Converts `source` file from ISO-8859-1 encoding to UTF-8. The output is written in the `dest` file. ''' convert_file(source, dest, isolatin_to_utf8) #convert_file_isolatin_utf8('cigale-ISO-8859-1.txt','cigale30-UTF-8.txt') #Question 31: def utf8_to_isolatin(stream): """ Lit un caractère UTF-8 du flux 'stream' et retourne un tuple d'un octet correspondant au caractère ISO-8859-1 Si on est à la fin du fichier, retourne None :param stream: flux :return: Tuple d'un octet correspondant au caractère ISO-8859-1 (ou None si fin du fichier) :rtype: tuple :CU: None """ try: byte = stream.read(1)[0] if (byte==194): byte2=stream.read(1)[0] return (byte2,) elif (byte==195): byte2=stream.read(1)[0] return ((byte2+64),) else: return (byte,) except IndexError: stream.close() return None #Question 32: def conversion_file_utf8_isolatin(source, dest): ''' Converts `source` file from UTF-8 encoding to ISO-8859-1. The output is written in the `dest` file. ''' convert_file(source, dest, utf8_to_isolatin) #conversion_file_utf8_isolatin('cigale-UTF-8.txt','cigale32-ISO-8859-1.txt')
b29641c98a73b2c7a44a4045f95ce2af2d8dcd3b
cgsarfati/CodingChallenges-Insertion-Sort
/insertionsort.py
1,386
4.28125
4
"""Given a list, sort it using insertion sort. For example:: >>> from random import shuffle >>> alist = range(1, 11) >>> shuffle(alist) >>> insertion_sort(alist) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> shuffle(alist) >>> insertion_sort(alist) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> shuffle(alist) >>> insertion_sort(alist) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ def insertion_sort(alist): """Given a list, sort it using insertion sort.""" # INSERTION SORT: # start w/ 2nd item in lst # compare item to items in left, shifting it as long as item < comparison # when comparison > item, stop shift, and move on to next item # this algorithm sorts IN PLACE + best for almost-sorted lst + small lst # start at 2nd item (since 1st item has no left comparison) for idx in range(1, len(alist)): value = alist[idx] # compare value to each item to left of it i = idx - 1 while i >= 0: # shift values if value < alist[i]: alist[i+1] = alist[i] alist[i] = value # move to left i -= 1 else: break return alist if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. NICE SORTING!\n"
76dfab596528e9f7f61031cbd7a917ac001429c0
borko81/python_fundamental_solvess
/examples/10Mach2019_1/HelloFrance.py
1,708
4.25
4
''' Create a program that calculates the profit after buying some items and selling them on a higher price. In order to fulfil that, you are going to need certain data - you will receive a collection of items and budget in the following format: {type->price|type->price|type->price……|type->price} {budget} The prices for each of the types cannot exceed a certain price, which is given bellow: Type Maximum Price Clothes 50.00 Shoes 35.00 Accessories 20.50 If a price for a certain item is higher than the maximum price, don’t buy it. Every time you buy an item, you have to reduce the budget with the value of its price. If you don’t have enough money for it, you can’t buy it. Buy as much items as you can. You have to increase the price of each of the items you have successfully bought with 40%. Print the list with the new prices and the profit you will gain from selling the items. They need exactly 150$ for tickets for the train, so if their budget after selling the products is enough – print – "Hello, France!" and if not – "Time to go." ''' list_item = input().split('|') budjet = float(input()) prices_items = {'Clothes': 50, 'Shoes': 35, 'Accessories': 20.5} buy_items = [] cost_item = [] for l in list_item: name, price = l.split('->') price = float(price) if price <= float(prices_items[name]) and price <= budjet and name in prices_items: cost_item.append(price) buy_items.append(price * 1.4) budjet -= price for item in buy_items: print('%.2f' % item, end=' ') print('') print(f'Profit: {(sum(buy_items) - sum(cost_item)):.2f}') if (sum(buy_items) + budjet) >= 150: print(f'Hello, France!') else: print(f'Time to go.')
4d35185ba390bb1602cbf732c77d31bcf02cd9d7
Cuick/traversing
/shared/utils/random_pick.py
1,878
3.65625
4
# -*- coding:utf-8 -*- """ created by server on 14-7-16上午10:25. """ import random import copy def random_pick_with_weight(items): """ 根据权重获取随机item :param items: {1:50, 2: 50, ...} 1:id 50:权重 :return id list: """ pick_result = None random_max = sum(items.values()) x = random.randint(0, random_max) odds_cur = 0 for item_id, weight in items.items(): odds_cur += weight if x <= odds_cur: pick_result = item_id break return pick_result def random_pick_with_percent(items): """ 根据百分比获取随机item """ pick_result = None random_max = sum(items.values()) x = random.randint(0, 100) odds_cur = 0 for item_id, percent in items.items(): weight = percent*100 odds_cur += weight if x <= odds_cur: pick_result = item_id break return pick_result def random_multi_pick(items, times): """重复掉落多次""" drop_items = [] for i in range(times): picked_item_id = random_pick_with_weight(items) if not picked_item_id: continue drop_items.append(picked_item_id) return drop_items def random_multi_pick_without_repeat(items, times): """重复掉落多次,要去重 """ drop_items = [] items_copy = copy.deepcopy(items) for i in range(times): picked_item_id = random_pick_with_weight(items_copy) if not picked_item_id: continue drop_items.append(picked_item_id) del items_copy[picked_item_id] return drop_items def get_random_items_from_list(num, items=[]): """ items is a list """ res = [] if len(items) < num: return [] for no in random.sample(range(len(items)), num): res.append(items[no]) return res
0cf2a7db2a61af66d5bf0e52b6c287d8216c3cfa
utsav8670/spychat
/main.py
1,375
4.0625
4
print"hello buddy" print"let's get started" spy_name = raw_input(" what is your spy name?? ") if len(spy_name) > 2: print "welcome " + spy_name spy_salutation = raw_input("what should i call you(mr. or ms. )?") if spy_salutation == "mr." or spy_salutation == "ms.": spy_name = spy_salutation + " " + spy_name spy_no = input("enter your mobile no") print "alright" + spy_salutation + " " + spy_name + " i wolud like to know little bit more about u" spy_age = input(" what is your age ") if 16 < 50 > spy_age: print("you are most welcome to spy_chat app") spy_rating = input("what is your spy_rating") if spy_rating > 5.0: print "you are an very good spy" elif 3.5 < spy_rating <= 5.0: print "you are an good spy" elif 2.5 < spy_rating <= 3.5: print "you are an average spy" else: print "you have to learn more" spy_is_online = True print "authentication is complete , welcome: " + spy_name + " age: " + str(spy_age) + " rating: " + str( spy_rating) + " welcome to spy_chat app " else: print("you are no eligible for being spy") else: print"invalid salutation" else: print ("oops , this not a valid name")
b5b66795a67f8336fb8658cc361a0937d86ac112
10Jack2/lucky_unicorn
/11_number_checker.py
828
4.34375
4
# sets the error statement for the if statement to follow error = "please enter a whole number between 1 and 10\n" # keeps the if statement looping until an appropriate answer is entered valid = False while not valid: # This try statment makes it so the program does not crash if a float is entered rather then an interger as the response try: response = int(input("How much would you like to play with ? ")) # An if statement that checks if the response to the previous statement is between 0 and 10 if 0 < response <= 10: print("You have asked to play with ${}".format(response)) # An if statement that outputs the error statement if the response is not between 0 and 10 else: print(error) except ValueError: print(error)
57a341136fa91d90c17748dc237229c3034e12e9
isaquemelo/contests
/Lista 1 - Aquecimento e revisão de ED @ ATAL2020.2/URI 2049.py
276
3.734375
4
instanceCounter = 1 while True: signature = input() if signature == '0': break number = input() if instanceCounter != 1: print() print("Instancia", instanceCounter) if signature in number: print("verdadeira") else: print("falsa") instanceCounter += 1
ea07922666eeaefa247a36580d8ed8c33fcd34d0
rasithasreeraj/python
/abstract class/Multiple Inheritance.py
1,164
4.3125
4
class Water_living: def __init__(self, is_water, name): self.name = name self.is_water = is_water class Land_living: def __init__(self, is_land, name): self.name = name self.is_land = is_land class Amphibian(Water_living, Land_living): def __init__(self, name, is_water, is_land): self.name = name Water_living.__init__(self, is_water, self.name) Land_living.__init__(self, is_land, self.name) def sample(self): if (Mammal1.is_water == "Yes" and Mammal1.is_land =="Yes"): return ("{} is an Amphibian.".format(self.name)) else: return ("{} is not an Amphibian.".format(self.name)) Water_living1 = Water_living("Yes","Fish") Land_living1 = Land_living("Yes","Elephant") Mammal1 = Amphibian("Tortoise","Yes","Yes") Amphibian2 = Amphibian("Frog","Yes","Yes") print(Mammal1.sample()) print(Water_living1.is_water) print(Mammal1.is_water) print(Mammal1.__dict__) print(Water_living1.__dict__) print(Land_living1.__dict__) print(Amphibian.mro()) # Will display Method Resolution Order https://www.python-course.eu/python3_multiple_inheritance.php
4a48189ea702f9b763fd8bf2c7324cbfb0aed022
vendulabezakova/pythonProject1
/main.py
4,396
3.71875
4
"""item = {"title": "Čajová konvička s hrnky", "price": 899, "inStock": True} item["price"] = 929 print("Název položky je " + item["title"] +"." + "Jeho cena je " + str(item["price"]) + " Kč.") print(f"Cena položky je {item['price']} Kč.") item["weight"] = 0.5 if "weight" in item: print(f"Hmotnost je {item['weight']} kg.") else: print(f"Hmotnost není zadána.") sausages = {"jirka": 2, "Natálie": 1, "Bart": 4, "Martin": 3} print(len(sausages)) sausages.pop("Martin") print(len(sausages)) #vysvedceni vysvedceni = {"Matematika": 3, "Český jazyk": 1, "Dějepis": 2} print(vysvedceni) #knihy sales = { "Zkus mě chytit": 4165, "Vrah zavolá v deset": 5681, "Zločinný steh": 2565, } sales = { "Zkus mě chytit": 4165, "Vrah zavolá v deset": 5681, "Zločinný steh": 2565, } sales["Noc, která mě zabila"] = 0 sales["Vrah zavolá v deset"] +=100 print(sales) #tombola tombola = { 7: "Láhev kvalitního vína Château Headache", 15: "Pytel brambor z místního družstva", 23: "Čokoládový dort", 47: "Kniha o historii města", 55: "Šiška salámu", 67: "Vyhlídkový let balónem", 79: "Moderní televizor", 91: "Roční předplatné městského zpravodaje", 93: "Společenská hra Sázky a dostihy", } cislo = int(input("Jaké je číslo tvého lístku? ")) if cislo in tombola: vyhra = tombola.pop(cislo) print(f"Vyhráváš: {vyhra}") else: print("Bohužel jsi nevyhrál.") #večírek passwords = { "Jiří": "tajne-heslo", "Natálie": "jeste-tajnejsi-heslo", "Klára": "nejtajnejsi-heslo" } guest = input("Jaké je tvé jméno? ") if guest in passwords: password = input("Jaké je tvoje heslo? ") if password == passwords[guest]: print("Smíš vstoupit.") else: if password == passwords[guest]: print("Smíš vstoupit.") else: print("Máš smůlu.") else: print("Máš smůlu.") #baliky baliky = { "B541X": True, "B547X": False, "B251X": False, "B501X": True, "B947X": False, } balik = input("Jaké je číslo balíku? ") if balik in baliky: if baliky[balik] == True: print("Balík byl předán kurýrovi.") else: print("Balík nebyl předán kurýrovi.") else: print("Balík neexistuje.") vstup = input("Zadej vstup: ") for i in vstup: print(morseCode[i], end=" ") #detektivky podruhé prodeje2019 = { "Zkus mě chytit": 4165, "Vrah zavolá v deset": 5681, "Zločinný steh": 2565, } prodeje2020 = { "Zkus mě chytit": 3157, "Vrah zavolá v deset": 3541, "Vražda podle knihy": 2510, "Past": 2364, "Zločinný steh": 5412, } kniha = input("Zadej název knihy: ") soucet = 0 if kniha in prodeje2019: soucet = soucet + prodeje2019[kniha] soucet = soucet + prodeje2020[kniha] print(f"Knih se prodalo {soucet} kusů.") #cyklus sales = { "Zkus mě chytit": 4165, "Vrah zavolá v deset": 5681, "Zločinný steh": 2565, } soucet = 0 for nazev, prodano in sales.items(): print(f"Knihy {nazev} bylo prodáno {prodano} kusů.") soucet = soucet + prodano print(f"Bylo prodáno {soucet} kusů knih.") knihy = [ {"nazev": "Zkus mě chytit", "prodano_kusu": 4165,"cena": 347, "rok_vydani": 2018}, {"nazev": "Vrah zavolá v deset", "prodano_kusu": 5681,"cena": 299, "rok_vydani": 2019}, {"nazev": "Zločinný steh", "prodano_kusu": 2565,"cena": 369, "rok_vydani": 2019}, ] celkove_trzby = 0 for kniha in knihy: if kniha["rok_vydani"] == 2019: celkove_trzby += kniha["prodano_kusu"] * kniha["cena"] print(f"Celkové tržby za rok 2019 jsou {celkove_trzby} Kč.") """ #morseovka morseCode = { "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---", "p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-", "u": "..-", "v": "...-", "w": ".--", "x": "-..-", "y": "-.--", "z": "--..", ".": ".-.-.-", ",": "--..--", "?": "..--..", "!": "-.-.--", "-": "-....-", "/": "-..-.", "@": ".--.-.", "(": "-.--.", ")": "-.--.-" }
d5a6842a78c14e29ad58a9ce25d1986f2da1a07c
NTR1407/python
/Clases/Caja.py
526
3.890625
4
class Caja: def __init__(self,largo,alto,ancho): self.largo = largo self.alto = alto self.ancho = ancho def perimetro(self): return self.largo * self.alto * self.ancho print("Hola, a continuacion calcularemos el perimetro de una caja.") largo = float(input("Ingrese el largo de la caja: ")) alto = float(input("Ingrese el alto de la caja: ")) ancho = float(input("Ingrese el ancho de la caja: ")) caja = Caja(largo,alto,ancho) print("El perimetro de la caja es:",caja.perimetro())
024b3e43e7555dda42d85ae322596cd5a674a29f
jerrizzy/auto-messenger
/silly.py
4,372
4.0625
4
import random import words import datetime import time import threading import schedule # section 1 def silly_string(nouns, verbs, names, templates): # Choose a random template. template = random.choice(templates) # We'll append strings into this list for output. output = [] # Keep track of where in the template string we are. index = 0 # Add a while loop here. while index < len(template): if template[index : index + 8] == '{{noun}}': output.append(random.choice(nouns)) index += 8 elif template[index : index + 8] == '{{verb}}': output.append(random.choice(verbs)) index += 8 elif template[index : index + 8] == '{{name}}': output.append(names) index += 8 else: output.append(template[index]) index += 1 return "".join(output) # After the loop has finished, join the output and return it. if __name__ == '__main__': def myFunction(): print(silly_string(words.nouns, words.verbs, words.names, words.templates)) # section 2 # This function is to prompt user to set their timer for when # they want to receive these random messages def clock(): print("Please enter your increment: \n") selection = input("second\n" "minute\n" "hour\n" "day\n").lower() if selection == "second": second() elif selection == "minute": min() elif selection == "hour": hour() else: print("Please enter the correct increment") clock() # this is the function that gets called when user wants to receive messages every seconds def second(): for i in range(60): print(i) # this only prints the seconds the user can enter. Only for user visibilty t = input("Please enter your time in seconds: ") # issue - if user enters wrong iteration, program crashes. Need fixing. schedule.every(int(t)).seconds.do(myFunction) # It's the same issue for the other time options as they are the same set up. while True: schedule.run_pending() time.sleep(1) # this is the function that gets called when user wants to receive messages every minute def min(): for i in range(60): print(i) # this only prints the minutess the user can enter. Only for user visibility t = input("Please enter your time in minute: ") schedule.every(int(t)).minutes.do(myFunction) while True: schedule.run_pending() time.sleep(1) # this is the function that gets called when user wants to receive messages every hour def hour(): for i in range(24): print(i) # this only prints the hours the user can enter. Only for user visibilty t = input("Please enter your time in hours: ") schedule.every(int(t)).hours.do(myFunction) while True: schedule.run_pending() time.sleep(1) # section 3: This is where I try to build the random option, but it's not working yet. def rand_second(): n = 0 t = random.randint(0, 10) schedule.every(int(t)).seconds.do(myFunction) while n < 1: schedule.run_pending() n += 1 if n == 1: break #time.sleep() #schedule.CancelJob def rand_s(): t = random.randint(0, 10) schedule.every(int(t)).seconds.do(rand_second) #while True: schedule.run_pending() #time.sleep(1) def rand_min(): myFunction() return schedule.CancelJob def rand_m(): t = random.randint(0, 30) schedule.every(int(t)).seconds.do(rand_min) while True: schedule.run_pending() time.sleep(1) def rand_day(): t = random.randint(0, 23) schedule.every(int(t)).hours.do(myFunction) while True: schedule.run_pending() time.sleep(1) def rand_inc(): while True: rand_list = [rand_s, rand_m] random.choice(rand_list)() #rand_s() #rand_second() #rand_inc() clock() # todo: # 0- App name for now is SAM(send automatic message)-- # 1- how user stops or cancels an increment job or a cycle. # 2- add a random increment function: whether it chooses a different increment after each job or... # the random func selects an increment randomly and stays on it? I like the former better
b350e74105ae8a3abb05f7109ee28a69e1615b64
AlexeyBazanov/algorithms
/sprint_4/odd_mapping.py
657
3.84375
4
import sys def is_odd_equal(str1, str2): map1 = {} map2 = {} str1_len = len(str1) str2_len = len(str2) if str1_len != str2_len: return False for i in range(str1_len): let1 = str1[i] let2 = str2[i] if let1 in map1 and map1[let1] != let2: return False if let2 in map2 and map2[let2] != let1: return False map1[let1] = let2 map2[let2] = let1 return True def main(): str1 = sys.stdin.readline().strip() str2 = sys.stdin.readline().strip() print('YES' if is_odd_equal(str1, str2) else 'NO') if __name__ == '__main__': main()
8ad32135505e72cc2faf826853e250deda5d6252
finndai/jianzhioffer
/Singleton.py
1,023
3.765625
4
# -*-coding:utf-8-*- # 1.使用__new__方法实现 class Singleton1(object): def __new__(cls,*args,**kwargs): if not hasattr(cls,"_instance"): cls._instance = object.__new__(cls,*args,**kwargs) return cls._instance class TestClass() a = 1 # 使用装饰器 def Singleton2(cls,*args,**kwargs): instances = {} def _singleton(): if cls not in instances: instances[cls] = cls(*args,**kwargs) return instances[cls] return _singleton # 使用Python模板 from ... import ... #共享属性 """ 所谓单例就是所有引用(实例、对象)拥有相同的的状态(属性)和行为(方法) 同一个类的所有实例天然拥有相同的行为(方法) 只需要保证一个类的所有实例具有相同的状态(属性)即可 """ class Singleton3(object): _state = {} def __new__(cls,*args,**kwargs): obj = super(Singleton3,cls).__new__(cls,*args,**kwargs) obj.__dict__ = cls._state return obj
5573525323f85b1f00ece7acfe85376386d9b9a4
bharatanand/B.Tech-CSE-Y2
/applied-statistics/lab/experiment-1/experiment1.py
3,661
3.640625
4
# EXPLANATION: # The dataFrame has the following fields: # Name, Marks, CGPU & Quality of Assignment # The Name field is of Nominal datatype since each record is a nominee of the field. Mode can be found out. # The Marks field is of Ordinal datatype since it can be sorted and comparison operations can be performed. Mode, Median and Mean can be found out. # The CGPA field is of Ratio datatype. Thus, Mode, Median and Mean can be obtained # Quality of Assignment, as the name of the field suggests, is a field of Qualitative type rather than Quantitative type. Since its a textual field and is dependent on conext rather than numeric value. The mode can be obtained from this field. # --------------------------------------------------------------------------------------- # TODO # [X] - Read excel file as dataframe # [X] - Figure our what kind of data it is, eg:. Nominal, Ordinal, etc # [X] - Depending on the type, figure out the mesaure of central tendency that can be found out by ops on the data, eg: if we can find the summation, we cant find the mean, if its not ordinal, we cant sort and we cant find the median, etc. # [X] - Fill in the missing value in the CGPI field # --------------------------------------------------------------------------------------- import pandas as pd # Read the dataset from excel file by passing raw string as argument to read_excel() fn dataFrame = pd.read_excel(r'C:\Users\Volt\code\B.Tech-CSE-Y2\applied-statistics\lab\expt1\Demo.xlsx') # Print the pandas dataFrame obtained from the excel file print('\n-----------ORIGINAL DATA-------------') print(f'\nPrinting the original dataset:\n\n{dataFrame}') # Starting with Name field print('\n-----------NAME-------------') # Calculating mode nameMode = dataFrame['Name'].mode() # Note: Since mode() returns a pandas series, we use indexing to access the name instead of printing the entire record print(f"\nName field is of Nominal datatype\nMode of this data is = {nameMode[0]}") # Marks field print('\n-----------MARKS-------------') # Sorting the marks column sortedMarksCol = dataFrame['Marks'].sort_values(ascending=False) # Printing the marks column print(f'\nMarks field is of Ordinal datatype\nPrinting the sorted marks column:\n{sortedMarksCol.to_string(index=False)}') # Calculating mode, median, mean marksMode = sortedMarksCol.mode() # We use indexing only for mode since the return type is a pandas series marksMedian = sortedMarksCol.median() marksMean = sortedMarksCol.mean() # Printing results print(f"Results of statistical calculations on Marks:\nMean = {marksMean}\nMedian = {marksMedian}\nMode = {marksMode[0]}") # CGPA field print('\n-----------CGPA-------------') # Sorting the CGPA column sortedCGPACol = dataFrame['CGPI'].sort_values(ascending=False) # Print the CGPA column print(f'\nCGPA field is of Ratio datatype\nPrinting the sorted CGPA column:\n{sortedCGPACol.to_string(index=False)}') # Calculating mode, median, mean CGPAMode = sortedCGPACol.mode() CGPAMedian = sortedCGPACol.median() CGPAMean = sortedCGPACol.mean() # Printing results print("Results of statistical calculations on CGPA:\nMean = {:.2}\nMedian = {}\nMode = {}".format(CGPAMean, CGPAMedian, CGPAMode[0])) # QoA field print('\n-----------Quality of Assignment-------------') QoAMode = dataFrame['Quality of Assignment'].mode() print(f"\nQuality of Assignment field is of Qualitative datatype\nMode of this data is = {QoAMode[0]}") # Filling the missing value print('\n-----------UPDATED DATA-------------') dataFrame['CGPI'].fillna(value=CGPAMean, inplace=True) print(f'\nUpdated data frame with filled missing value for CGPA:\n{dataFrame}')
ccfda18329956ae35ec92e3d4a938569ac6884c9
jshk1205/pythonPractice
/10987.py
192
3.65625
4
text = list(str(input())) count = 0 for i in range(0, len(text)): if text[i] == 'a' or text[i] == 'e' or text[i] == 'i' or text[i] == 'o' or text[i] == 'u': count += 1 print(count)
208ac09d36f8cccdadbc24fa57826c80c8232a6d
charlysl/MIT-6.009-Python-Self-Learning
/tutorials/tutorial_3/lab.py
2,027
4.09375
4
""" Data structures: ---------------- music := list of "genomes", each of which is a list of integers in [0,1] music is therefore a list of lists of integers likes := list of song_id integers corresponding to songs (genomes) in music dislikes := same as above """ def next_song(likes, dislikes, music): # play the next unplayed song with the highest "goodness" played = likes + dislikes # undefined behavior when all songs have played. Here, we return 0. best_song_id, best_goodness = 0, -999999999999 # a very "bad" goodness # consider all songs in music for song_id in range(len(music)): # disregard songs that have played already if song_id in played: continue # what is the goodness of the song we're considering? g = goodness(likes, dislikes, song_id, music) # if song is better than best_so_far, update best_so_far if g > best_goodness: best_song_id = song_id best_goodness = g # at this point, considered all unplayed song, and must've seen the best return best_song_id def goodness(likes, dislikes, song_id, music): # "goodness" function, as defined in the lab assignment # favor songs far away from disliked songs, but close to liked songs return average_distance(dislikes, song_id, music) - average_distance(likes, song_id, music) def average_distance(song_id_list, song_id, music): # average distance is the sum of distances # divided by the number of distances considered d = 0 for other_song_id in song_id_list: d += distance(music[song_id], music[other_song_id]) return d/max(1, len(song_id_list)) # compute average; distance to empty playlist is 0 def distance(song_1, song_2): # Distance is defined to be the "manhattan distance" of genomes: # the number of genes differing between songs d = 0 for gene in range(len(song_1)): # assume songs have equal numbers of genes d += abs(song_1[gene]-song_2[gene]) return d
d75765cdd06ad98b09bc91a4299152e5f067059c
prathammehta/interview-prep
/MaximumSumIncreasingSubSequence.py
570
3.9375
4
# https://www.geeksforgeeks.org/printing-maximum-sum-increasing-subsequence/ def get_subsequence(arr): l = len(arr) max_sum = [arr[i] for i in range(l)] max_sum_seq = [[arr[i]] for i in range(l)] for i in range(1,l): max_value = 0 max_index = 0 for j in range(0,i): if arr[j] < arr[i] and max_value < max_sum[j]: max_value = max_sum[j] max_index = j max_sum[i] = max_value + arr[i] max_sum_seq[i] = max_sum_seq[max_index] + max_sum_seq[i] return max_sum_seq[max_sum.index(max(max_sum))] print(get_subsequence([1, 101, 2, 3, 100, 4, 5]))
9d47e4d07855501b08d524d9db2c15d3921318a7
artodeschini/First-steps-in-Python
/variables.py
73
3.65625
4
a = 5 b = 6 c = 7 print(' {0} + {1} + {2} = {3} '.format(a,b,c, a+b+c) )
bc0f0f9629f5fa2c482b60e69fca49f59e97998f
febinv/DS_ALGO
/checkstringpermutation.py
217
3.984375
4
def checkpermutation(str1,str2): if len(str1)!=len(str2): return False else: return sorted(str1)==sorted(str2) print(checkpermutation('febin','nibef')) print(checkpermutation('febi','ibef'))
ed5ec78e4280558316d359219c4a759e635837b0
CowFu/GoatHouse_Bot
/cards.py
1,451
3.859375
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 26 18:10:21 2018 @author: spaeh """ import random class Cards: def __init__(self): self.newDeck() self.hands = [] self.players = [] def newDeck(self): values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] suites = [':hearts:', ':spades:', ':clubs:', ':diamonds:'] self.deck = [j + i for j in values for i in suites] random.shuffle(self.deck) self.hands = [] self.players = [] def shuffle(self): random.shuffle(self.deck) self.round = 1 def newGame(): c.newDeck() def deal(user, number = 1): cards = "" if user not in c.players: c.players.append(user) c.hands.append([]) playernum = c.players.index(user) if(len(c.deck) >= number): for a in range(0,number): card = "__**" + c.deck.pop(0) + "**__" cards += card + ", " c.hands[playernum].append(card) return cards[:-2] return "Not enough cards to draw" def count(): return(str(len(c.deck)) + ' cards remaining in the deck') def hand(user): if user not in c.players: return("sorry, you don't have any cards") results = user + "'s hand: " for card in c.hands[c.players.index(user)]: results += card + " " return results #global variable to keep persistant deck c = Cards()
38a54b3d4f9dfe5a301c6a2260da5399593fd26b
Emerson53na/exercicios-python-3
/035 Análise Triângulo.py
547
3.75
4
n = 's' while n == 's': print('=-'*20) print(' \033[33m Analiser de triângulo\033[m') print('=-'*20) s1 = float(input(' Primeiro segmento: ')) s2 = float(input(' Segundo segmento: ')) s3 = float(input(' Terceiro segmento: ')) if s1 < s2+s3 and s2 < s3+s1 and s3 < s1+s2: print('\n É possível formar um triângulo.') else: print('\n Não é possível formar um triângulo.') n = str(input('\n Desejar reiniciar? [s/n]\n >>')) if n == 'n': exit()
675d199a35673fd590a8582f5f2960c8ffbb32a1
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/prime-factors/e2d8b0ef712b435e887d846f6b67b5e2.py
267
3.671875
4
def prime_factors(number): result = [] factor_test = 2 while number > 1: if number % factor_test == 0: result.append(factor_test) number /= factor_test else: factor_test += 1 return result
2332a18e0c9d5e800fd1c346a680164bb0ed53c2
TrejoCode/python
/03-loops/loops.py
478
3.65625
4
""" Bucle FOR continue: Salta el valor break: Rompe el ciclo, finaliza """ def run(): fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) for letra in "palabra": print(letra) for x in range(6): print(x) else: print("Finally finished!") fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break if __name__ == '__main__': run()
7e27684984b844b9295cdf260a2e9226f4986131
LPetrova/Python
/Saturday_task/sum_of_evens.py
227
4
4
n = input('Enter n: ') n = int(n) start_number = 1 sum = 0 while start_number <= n: if start_number % 2 == 0: print(str(start_number) + ' is even' ) sum = sum + start_number start_number += 1 print(sum)
01b10ad3d3f4b181a2c6dc8d8b9c5314aee8d9aa
kimsungbo/Algorithms
/백준/유니온파인드/1976_여행가자.py
732
3.609375
4
# 1976 여행 가자 # 유니온 파인드로 두 정점이 연결되어 있는지 확인 cities = int(input()) travel = int(input()) parents = [i for i in range(cities+1)] def Find(x): if x == parents[x]: return x else: y = Find(parents[x]) parents[x] = y return y def Union(x, y): x = Find(x) y = Find(y) if x != y : parents[y] = x for y in range(1, cities+ 1): maps = list(map(int, input().split())) for x in range(1, len(maps) + 1): if maps[x-1] == 1: Union(y, x) tour = list(map(int, input().split())) result = set([Find(i) for i in tour]) if len(result ) != 1: print("NO") else: print("YES")
f6ee0d2cb5369fe65fa505fdc8186465492273d1
luizfmgarcia/uctp_ufabc
/uctp_ufabc/src/uctp.py
51,584
3.59375
4
# UCTP Main Methods import objects import ioData import random # Set '1' to allow, during the run, the print on terminal of some steps printSteps = 0 #============================================================================================================== # Create the first generation of solutions def start(solutionsNoPop, subjList, profList, init): if(printSteps == 1): print("Creating first generation...", end='') for _ in range(init): solutionsNoPop.addCand(newCandRand(subjList, profList)) if(printSteps == 1): print("Created first generation!") #------------------------------------------------------- # Create new Candidate Full-Random def newCandRand(subjList, profList): candidate = objects.Candidate() # Follow the subjects in 'subjList', in order, and for each one, choose a professor randomly for sub in subjList: candidate.addRelation(sub, profList[random.randrange(len(profList))]) return candidate #============================================================================================================== # Extracts info about what Subj appears in which Prof PrefList def extractSubjIsPref(subjList, profList): # Lists for each Prof, where it is '1' if Subj in respective index is on Prof List of Pref but not same Quadri # '2' if same quadri subjIsPrefList = [[0 for _ in range(len(subjList))] for _ in range(len(profList))] # Counting the occurrences, filling the vectors for pIndex in range(len(profList)): # Getting data of current Prof prefSubjLists = [i for i in profList[pIndex].getPrefSubjLists()] # All Relations of one Prof for sIndex in range(len(subjList)): # Getting data of current Subj sName = subjList[sIndex].getName() sQuadri = subjList[sIndex].getQuadri() # For each quadri for i in range(3): # Finding the Subject 'sName' in "pPrefSubjQXList+pPrefSubjLimList" list sumList = prefSubjLists[i] + prefSubjLists[3] # Checking if the List is not empty if(len(sumList) > 0): try: index_value = sumList.index(sName) except ValueError: index_value = -1 # If the Subj name appears in the list if(index_value != -1): # If current Subject in analysis is on current Quadri if(str(i+1) in sQuadri): # Informing that the Subj appears on respective Prof-QuadriPrefList subjIsPrefList[pIndex][sIndex] = 2 # Informing that the Subj appears on other Prof-QuadriPrefList that is not same Quadri else: # Granting that do not decrease a value 2 already set if(subjIsPrefList[pIndex][sIndex] == 0): subjIsPrefList[pIndex][sIndex] = 1 return subjIsPrefList #============================================================================================================== # Separation of solutions into 2 populations def twoPop(solutionsNoPop, infPool, feaPool, profList, subjList, weightsList, numInfWeights): # Granting that the Lists will be empty to receive new Solutions infPool.resetCandList() feaPool.resetCandList() for cand in solutionsNoPop.getCandList(): # Classification by checking feasibility pop = checkFeasibility(cand, profList, subjList, weightsList, numInfWeights) if(pop == "feasible"): feaPool.addCand(cand) elif(pop == "infeasible"): infPool.addCand(cand) # Granting that the List will be empty to next operations solutionsNoPop.resetCandList() if(printSteps == 1): print("Checked Feasibility (new Candidates)/", end='') #============================================================================================================== # Detect the violation of a Restriction into a candidate def checkFeasibility(candidate, profList, subjList, weightsList, numInfWeights): # As part of the Candidate's Prof-Subj relations (with both Feasible and the Infeasible) will be traversed to check they Feasibility here, # instead of re-pass an entire Infeasible Candidate again in the 'calc_fitInfeas', the calculation of its Fitness will already be done # only one time here. Only the Feasible ones will have to pass through 'calc_fitFeas' later. fit = -1 fit = calc_fitInfeas(candidate, profList, subjList, weightsList[:numInfWeights]) if(fit < 0): candidate.setFitness(fit) return "infeasible" return "feasible" #============================================================================================================== # Calculate the Fitness of the candidate def calcFit(infeasibles, feasibles, profList, subjList, weightsList, numInfWeights, subjIsPrefList): # All Infeasible Candidates - is here this code only for the representation of the default/original algorithm`s work # The Inf. Fitness calc was already done in 'checkFeasibility()' method # Check if the Infeasible pop. is empty if(len(infeasibles.getCandList()) != 0): for cand in infeasibles.getCandList(): if(cand.getFitness() == 0.0): # Setting the Fitness with the return of calc_fitInfeas() method cand.setFitness(calc_fitInfeas(cand, profList, subjList, weightsList[:numInfWeights])) if(printSteps == 1): print("Fitness of all Inf./", end='') # All Feasible Candidates # Check if the Feasible pop. is empty if(len(feasibles.getCandList()) != 0): for cand in feasibles.getCandList(): if(cand.getFitness() == 0.0): # Setting the Fitness with the return of calc_fitFeas() method cand.setFitness(calc_fitFeas(cand, profList, subjList, weightsList[numInfWeights:], subjIsPrefList)) if(printSteps == 1): print("Fitness of all Feas./", end='') #============================================================================================================== # Calculate Fitness of Infeasible Candidates def calc_fitInfeas(candidate, profList, subjList, weightsList): # Getting information about the Candidate prof_relationsList = calc_i1(candidate, profList, subjList) i2_conflictsList, i3_conflictsList = calc_i2_i3(prof_relationsList, subjList) # Setting found variables candidate.setInfVariables(prof_relationsList, i2_conflictsList, i3_conflictsList) # Checking if occurred violations of restrictions on the Candidate # If there are violated restrictions, this Candidate is Infeasible and then will calculate and return a negative Fitness, # if not, is Feasible, will return 1.0 as Fitness if(prof_relationsList.count([]) != 0 or i2_conflictsList.count([]) != len(i2_conflictsList) or i3_conflictsList.count([]) != len(i3_conflictsList)): # Calculating main variables i1 = float(prof_relationsList.count([]) / (len(profList) - 1.0)) i2 = float(sum([len(i) for i in i2_conflictsList]) / len(subjList)) i3 = float(sum([len(i) for i in i3_conflictsList]) / len(subjList)) i = [i1, i2, i3] # Final Infeasible Function Fitness Calc Fi = -1.0 * sum([i[j] * weightsList[j] for j in range(len(i))]) / sum([w for w in weightsList]) # Returning the calculated result return Fi # If all Relations Prof-Subj in this Candidate passed through the restrictions) return 1.0 #------------------------------------------------------- # i1: penalty to how many Professors does not have at least one relation with a Subject def calc_i1(candidate, profList, subjList): # List of lists of Subjects that are related to the same Professor, where the position in this list is the same of the same professor in 'profList' list # Empty list in this list means that some Professor (p) does not exists on the Candidate prof_relationsList = [[] for _ in range(len(profList))] # Filling the list according to the candidate for s, p in candidate.getRelationsList(): indexp = profList.index(p) indexs = subjList.index(s) prof_relationsList[indexp].append(indexs) return prof_relationsList #------------------------------------------------------- # i2: penalty to how many Subjects, related to the same Professor, are teach in the same day, hour and quadri # i3: penalty to how many Subjects, related to the same Professor, are teach in the same day and quadri but in different campus def calc_i2_i3(prof_relationsList, subjList): # List of the subjects that have a conflict between them - always the two conflicts are added, that is, # there can be repetitions of subjects i2_conflictsList, i3_conflictsList = [[] for _ in range(len(prof_relationsList))], [[] for _ in range(len(prof_relationsList))] # Searching, in each professor (one at a time), conflicts of schedules between subjects related to it for list_subj in prof_relationsList: # Current Prof in analysis profIndex = prof_relationsList.index(list_subj) # Check if the professor has more than 1 relation Prof-Subj to analyze if(len(list_subj) > 1): # Getting the data of all Subjects related to current Professor in analysis timetableList_List = [subjList[i].getTimeTableList() for i in list_subj] quadri_List = [subjList[i].getQuadri() for i in list_subj] campus_List = [subjList[i].getCampus() for i in list_subj] period_List = [subjList[i].getPeriod() for i in list_subj] # Comparing the data of one Subject (i) with all next subjects listed, and do the same with next ones i = 0 for timeTable in timetableList_List: # all [day/hour/frequency] of the Timetable of the Subject (i) in 'timetableList_List' i_day = [j[0] for j in timeTable] i_hour = [j[1] for j in timeTable] i_frequency = [j[2] for j in timeTable] # Now, comparing current (i) subject data with next ones (k), one at a time k = i + 1 rest = timetableList_List[k:] # repeat this 'len(rest)' times for nextK in rest: # Already check if both Subj (i, k) is on same Quadri if(quadri_List[i] == quadri_List[k]): # Variables that flags if a conflict was already detected (do not count 2 or more times same 2 subjects in conflict) verified_i2, verified_i3 = False, False # all [day/hour/frequency] of the Timetable of the Subject (k) in 'timetableList_List' inext_day = [j[0] for j in nextK] inext_hour = [j[1] for j in nextK] inext_frequency = [j[2] for j in nextK] # Finally comparing one-to-one timetables - between i and k subjects for a in i_day: for b in inext_day: if(a == b): # There is, at least, two subjects teach in the same day and quadri, but in different campus if(campus_List[i] != campus_List[k]): if(verified_i3 == False): i3_conflictsList[profIndex].append(list_subj[i]) i3_conflictsList[profIndex].append(list_subj[k]) verified_i3 = True # There is, at least, two subjects teach in the same day, hour and quadri # First check if they have the same Period if(period_List[i] == period_List[k] and i_hour[i_day.index(a)] == inext_hour[inext_day.index(b)]): # if one 'frequency' is "QUINZENAL I" and the other is "QUINZENAL II" then DO NOT count if('SEMANAL' in i_frequency[i_day.index(a)] or 'SEMANAL' in inext_frequency[inext_day.index(b)]): if(verified_i2 == False): i2_conflictsList[profIndex].append(list_subj[i]) i2_conflictsList[profIndex].append(list_subj[k]) #print(subjList[list_subj[i]].get(), subjList[list_subj[k]].get(), '\n') verified_i2 = True elif('QUINZENAL I' in i_frequency[i_day.index(a)] and 'QUINZENAL I' in inext_frequency[inext_day.index(b)]): if(verified_i2 == False): i2_conflictsList[profIndex].append(list_subj[i]) i2_conflictsList[profIndex].append(list_subj[k]) #print(subjList[list_subj[i]].get(), subjList[list_subj[k]].get(), '\n') verified_i2 = True elif('QUINZENAL II' in i_frequency[i_day.index(a)] and 'QUINZENAL II' in inext_frequency[inext_day.index(b)]): if(verified_i2 == False): i2_conflictsList[profIndex].append(list_subj[i]) i2_conflictsList[profIndex].append(list_subj[k]) #print(subjList[list_subj[i]].get(), subjList[list_subj[k]].get(), '\n') verified_i2 = True # Going to the next Subject (k+1) to compare with the same, current, main, Subject (i) k = k + 1 # Going to the next Subject (i+1) related to the same Professor i = i + 1 # Removing from 'i2_conflictsList' and 'i3_conflictsList' duplicates final_i2 = [[] for _ in range(len(prof_relationsList))] final_i3 = [[] for _ in range(len(prof_relationsList))] for i in range(len(prof_relationsList)): for j in i2_conflictsList[i]: if(final_i2[i].count(j) == 0): final_i2[i].append(j) for j in i3_conflictsList[i]: if(final_i3.count(j) == 0): final_i3[i].append(j) return final_i2, final_i3 #============================================================================================================== # Calculate Fitness of Feasible Candidates def calc_fitFeas(candidate, profList, subjList, weightsList, subjIsPrefList): prof_relationsList, _, _, _, _, _ = candidate.getFeaVariables() # Looking for good Relations into the Candidate using "Quality Amplifiers" # Getting information about the Candidate sum_chargesRelative, difChargeList = calc_f1(subjList, profList, prof_relationsList) sum_Satisfaction, numSubjPrefList = calc_f2(subjList, profList, prof_relationsList, subjIsPrefList) sum_quadSabbNotPref, quadSabbNotPrefList = calc_f3(subjList, profList, prof_relationsList) sum_periodPref, periodPrefList = calc_f4(subjList, profList, prof_relationsList) sum_campusPref, campPrefList = calc_f5(subjList, profList, prof_relationsList) sum_relationsRelative, _ = calc_f6(subjList, profList, prof_relationsList) sum_qualityRelative, _ = calc_f7(subjList, profList, prof_relationsList, subjIsPrefList) # Setting found variables candidate.setFeaVariables(prof_relationsList, numSubjPrefList, periodPrefList, quadSabbNotPrefList, campPrefList, difChargeList) # Calculating main variables f1 = 1.0 - float(sum_chargesRelative / len(profList)) f2 = float(sum_Satisfaction / len(profList)) f3 = float(sum_quadSabbNotPref / len(subjList)) f4 = float(sum_periodPref / len(subjList)) f5 = float(sum_campusPref / len(subjList)) f6 = 1.0 - float(sum_relationsRelative / len(profList)) f7 = float(sum_qualityRelative / len(profList)) f = [f1, f2, f3, f4, f5, f6, f7] # Final Feasible Function Fitness Calc Ff = sum([f[j] * weightsList[j] for j in range(len(f))]) / sum([w for w in weightsList]) # Returning the result calculated return Ff #------------------------------------------------------- # f1: how balanced is the distribution of Subjects, considering the "Charge" of each Professor and its Subj related def calc_f1(subjList, profList, prof_relationsList): # List of all 'Effective Charges', that is, the sum of the charges of all the subjects related to the professor charges_eachProfRelations = [0 for _ in range(len(profList))] # List of requested charges of each professor charges_EachProf = [profList[i].getCharge() for i in range(len(profList))] # Counting the occurrences, filling the vectors for i in range(len(prof_relationsList)): # Summing all chargers of all relations of this Prof charges_eachProfRelations[i] = sum([subjList[sIndex].getCharge() for sIndex in prof_relationsList[i]]) # Difference of Prof Charge and the sum of all of its Subj-Relations difChargeList = [charges_EachProf[i] - charges_eachProfRelations[i] for i in range(len(profList))] # Relative weigh of excess or missing charge for each Prof - based on the absolute credit difference # between the credits requested by the Prof and the sum off all Subj related to it charges_relative = [float(abs(difChargeList[i]) / charges_EachProf[i]) for i in range(len(profList))] # Making a simple adjust on the value charges_relativeFinal = [charge if charge < 1.0 else 1.0 for charge in charges_relative] # The sum of charge discrepancies of all professors sum_chargesRelative = sum([charge for charge in charges_relativeFinal]) return sum_chargesRelative, difChargeList #------------------------------------------------------- # f2: how many and which Subjects are the professors preference, considering "prefSubj..." Lists def calc_f2(subjList, profList, prof_relationsList, subjIsPrefList): # These are Lists (each quadri - 3) of Lists (each professor) of Lists (each PrefList+LimList) # In each List (inside the List inside the List) we have 1 if the same index Subject (from same Quadri X Pref List + Lim Pref List) is related to Same Prof # or we have 0 if it is not related qX_relations = [[[] for _ in range(len(profList))] for _ in range(3)] # List with the number of subjects that are on respective Prof's List of Preferences numSubjPrefList = [0 for _ in range(len(profList))] # Counting the occurrences, filling the vectors for relations in prof_relationsList: # Setting Index of current Prof pIndex = prof_relationsList.index(relations) # Getting data of current Prof prefSubjLists = [i for i in profList[pIndex].getPrefSubjLists()] # For each Quadri - Filling QX Lists of current Prof # in each one appends "pPrefSubjQXList" with "pPrefSubjLimList" to have the length of the subList for i in range(3): qX_relations[i][pIndex] = [0 for _ in range(len(prefSubjLists[i]) + len(prefSubjLists[3]))] # All Relations of one Prof for sIndex in relations: # Getting data of current Subj sName = subjList[sIndex].getName() sQuadri = subjList[sIndex].getQuadri() # For each quadri for i in range(3): # Looking for only in the list of respective quadri of current Subject in analysis if(str(i+1) in sQuadri): # Finding the Subject 'sName' in "pPrefSubjQXList+pPrefSubjLimList" list sumList = prefSubjLists[i] + prefSubjLists[3] # Checking if the List is not empty if(len(sumList) > 0): try: index_value = sumList.index(sName) except ValueError: index_value = -1 # If the Subj name appears in the list if(index_value != -1): # Putting '1' in same position found 'index_value' in the subList (which this one, is in same position of profList) qX_relations[i][pIndex][index_value] = 1 # Adding the Subj that is on Prof Pref List numSubjPrefList[pIndex] = numSubjPrefList[pIndex] + 1 # Calculating intermediate variables # Lists of the calculation of "satisfaction" based on the order of Subjects choose by a Professor (index = 0 has more weight) finalQX = [[0.0 for _ in range(len(profList))] for _ in range(3)] # For each Qaudri for i in range(3): # Calculating the Satisfaction from QX relations for each Professor for list_choice_relation in qX_relations[i]: # Setting current Prof Index and current List Relations-Preference prof_index = qX_relations[i].index(list_choice_relation) len_current_list = len(list_choice_relation) # Initializing current position and total weight that will be calculated next total_weight = 0 # Checking if the Relations-Preference List is empty if(len_current_list == 0): finalQX[i][prof_index] = 1.0 # If is needed to be calculated (is not empty) else: # QX Relations of each Professor for h in list_choice_relation: # Setting current Subject Preference Position pref_index = list_choice_relation.index(h) # Summing the Total Weight of this list of preferences to normalize later (+1 because first index is 0) total_weight = total_weight + pref_index + 1 # If the current Subj, in this specific position on the Preference List of current Prof, is related to it if(h == 1): # Summing the respective weight the Subj has in the Prof List of Preferences finalQX[i][prof_index] = finalQX[i][prof_index] + (len_current_list - pref_index + 1) # Calculate the final value of "Satisfaction" normalized, after obtained and summed all weights from Subjects related to current professor finalQX[i][prof_index] = float(finalQX[i][prof_index] / total_weight) # Calculate the final value of a Prof "satisfaction" summing all 3 values (from finalQ1, finalQ2 and finalQ3 lists) and normalizing it final_Satisf = [float((finalQX[0][i] + finalQX[1][i] + finalQX[2][i]) / 3.0) for i in range(len(finalQX[0]))] # Finally, calculating all Professors Satisfaction summing all final values sum_Satisfaction = sum([value for value in final_Satisf]) return sum_Satisfaction, numSubjPrefList #------------------------------------------------------- # f3: how many Subjects are teach in a "Quadri" that is not the same of Professors 'quadriSabbath' def calc_f3(subjList, profList, prof_relationsList): # List of Subjs related to a Prof that is on different Quadri of prof's QuadSabb quadSabbNotPrefList = [[] for _ in range(len(profList))] # Getting the occurrences, filling the vector for i in range(len(prof_relationsList)): # Getting data of current Prof pQuadriSabbath = profList[i].getQuadriSabbath() # All Relations of one Prof for sIndex in prof_relationsList[i]: # Getting data of current Subj sQuadri = subjList[sIndex].getQuadri() # Adding to count if the Subj is not in the same 'pQuadriSabbath' (if Prof choose 'nenhum' he does not have a 'pQuadriSabbath') if('NENHUM' in pQuadriSabbath or sQuadri != pQuadriSabbath): quadSabbNotPrefList[i].append(sIndex) # Calculating intermediate variable sum_quadSabbNotPref = sum([len(listSubj) for listSubj in quadSabbNotPrefList]) return sum_quadSabbNotPref, quadSabbNotPrefList #------------------------------------------------------- # f4: how many Subjects are teach in the same "Period" of the Professor preference "pPeriod" def calc_f4(subjList, profList, prof_relationsList): # List of Subjs related to a Prof that is on same Period of prof's Period periodPrefList = [[] for _ in range(len(profList))] # Getting the occurrences, filling the vector for i in range(len(prof_relationsList)): # Getting data of current Prof pPeriod = profList[i].getPeriod() # All Relations of one Prof for sIndex in prof_relationsList[i]: # Getting data of current Subj sPeriod = subjList[sIndex].getPeriod() # Adding to count if the Subj is in the same 'pPeriod' or if Prof do not care about 'pPeriod' equal to 'NEGOCIAVEL' if('NEGOCI' in pPeriod or sPeriod == pPeriod): periodPrefList[i].append(sIndex) # Calculating intermediate variable sum_periodPref = sum([len(listSubj) for listSubj in periodPrefList]) return sum_periodPref, periodPrefList #------------------------------------------------------- # f5: how many Subjects are teach in the same "Campus" of the Professor preference "prefCampus" def calc_f5(subjList, profList, prof_relationsList): # List of Subjs related to a Prof that is on same Campus of prof's Campus campPrefList = [[] for _ in range(len(profList))] # Getting the occurrences, filling the vector for i in range(len(prof_relationsList)): # Getting data of current Prof pPrefCampus = profList[i].getPrefCampus() # All Relations of one Prof for sIndex in prof_relationsList[i]: # Getting data of current Subj sCampus = subjList[sIndex].getCampus() # Adding to count if the Subj is in the same 'pPrefCampus' if(sCampus == pPrefCampus): campPrefList[i].append(sIndex) # Calculating intermediate variable sum_campusPref = sum([len(listSubj) for listSubj in campPrefList]) return sum_campusPref, campPrefList #------------------------------------------------------- # f6: average of relations between profs def calc_f6(subjList, profList, prof_relationsList): # Number of Subjs ideal for each professor avgSubjperProf = float(len(subjList)/len(profList)) # Difference between num of relations of each prof and the average difNumRel = [len(relations) - avgSubjperProf for relations in prof_relationsList] # Relative weigh of excess or missing relations for each Prof - based on the absolute relations difference relations_relative = [float(abs(difNumRel[i]) / avgSubjperProf) for i in range(len(prof_relationsList))] # Making a simple adjust on the values relations_relativeFinal = [value if value < 1.0 else 1.0 for value in relations_relative] # The sum of relations discrepancies of all professors sum_relationsRelative = sum([charge for charge in relations_relativeFinal]) return sum_relationsRelative, difNumRel #------------------------------------------------------- # f7: quality of relations (subj appears in some list of pref or/and same quadri) def calc_f7(subjList, profList, prof_relationsList, subjIsPrefList): # Summing, for each professor, its relations qualities sumRelationsQuality = [sum([subjIsPrefList[i][pos] for pos in prof_relationsList[i]]) for i in range(len(prof_relationsList))] # Relative value of quality of all relations for each Prof (2 is the max value of quality - same quadri of pref list) qualityRelative = [float(sumRelationsQuality[i] / (2 * len(prof_relationsList[i]))) for i in range(len(prof_relationsList))] # The sum of relative qualities of all professors sum_qualityRelative = sum([value for value in qualityRelative]) return sum_qualityRelative, qualityRelative #============================================================================================================== # Generate new solutions from the current Infeasible population def offspringI(solutionsNoPop, solutionsI, profList, subjList, subjIsPrefList, mutWithRand): # Check if the Infeasible pop. is empty if(len(solutionsI.getCandList()) != 0): # Make a Mutation for each candidate, trying to repair a restriction problem maker for cand in solutionsI.getCandList(): newCand = mutationI(cand, profList, subjList, subjIsPrefList, mutWithRand) # Adding the new Candidate generated by Mutation to 'solutionsNoPop' solutionsNoPop.addCand(newCand) if(printSteps == 1): print("Inf. Offspring/", end='') #============================================================================================================== # Generate new solutions from the current Feasible population def offspringF(solutionsNoPop, solutionsF, profList, subjList, subjIsPrefList, maxNumCand_perPop, pctParentsCross, reposCross, twoPointsCross, mutWithRand): # Check if the Feasible pop. is empty if(len(solutionsF.getCandList()) != 0): # 'objectiveNum': number of solutions to become parents - based on 'pctParentsCross' objectiveNum = int(pctParentsCross * len(solutionsF.getCandList()) / 100) # Turning 'objectiveNum' to Even if it is Odd -> summing +1 to it only if the new 'objectiveNum' is not bigger then len(solutionsF) if(objectiveNum % 2 != 0): if((objectiveNum + 1) <= len(solutionsF.getCandList())): objectiveNum = objectiveNum + 1 else: objectiveNum = objectiveNum - 1 # Granting that are solutions enough to became fathers (more than or equal 2) if(objectiveNum < 2): # If have at most 1 solution (insufficient to make any crossover) - then all solutions will generate a child through a mutation for cand in solutionsF.getCandList(): solutionsNoPop.addCand(mutationF(cand, profList, subjList, subjIsPrefList,mutWithRand)) # If we have at least 2 solutions else: # Roulette Wheel to choose solutions to become Parents fitnessList = [cand.getFitness() for cand in solutionsF.getCandList()] parentsSolFeas, notParents_objectsList, _ = rouletteWheel(solutionsF.getCandList(), fitnessList, objectiveNum, reposCross) # Solutions 'children' created by crossover childSolFeas = [] # Make a Crossover (create two new candidates) for each pair of parents candidates randomly choose # Granting the number of children is equal of parents while(len(childSolFeas) != objectiveNum): # If there are only 2 parents, make a crossover between them if(len(parentsSolFeas) <= 2): parent1, parent2 = 0, 1 # If there are more then 2, choosing the parents Randomly else: parent1, parent2 = random.randrange(len(parentsSolFeas)), random.randrange(len(parentsSolFeas)) # Granting the second parent is not the same of first one while(parent1 == parent2): parent2 = random.randrange(len(parentsSolFeas)) # Making the Crossover with the selected parents newCand1, newCand2 = crossover(parentsSolFeas[parent1], parentsSolFeas[parent2], twoPointsCross) # Removing used parents to make a new selection of Parents parent2 = parentsSolFeas[parent2] parentsSolFeas.remove(parentsSolFeas[parent1]) parentsSolFeas.remove(parent2) # adding the new candidates generated to childSolFeas childSolFeas.append(newCand1) childSolFeas.append(newCand2) # Adding the child generated by crossover to 'solutionsNoPop' for cand in childSolFeas: solutionsNoPop.addCand(cand) # Make Mutation with all the candidates that were not chosen to be Parents right before for cand in notParents_objectsList: # Making a not random mutation newCand = mutationF(cand, profList, subjList, subjIsPrefList,mutWithRand) # Adding the child not generated by crossover to 'solutionsNoPop' solutionsNoPop.addCand(newCand) if(printSteps == 1): print("Feas. Offspring/", end='') #============================================================================================================== # Make a mutation into a infeasible candidate def mutationI(candidate, profList, subjList, subjIsPrefList, mutWithRand=1): # Getting data to work with relations = candidate.getRelationsList()[:] prof_relationsList, i2_conflictsList, i3_conflictsList = candidate.getInfVariables() # This While ensures that 'problemType' will choose Randomly one 'restriction repair' flag_work_done = False while(flag_work_done == False): # Choosing one type of restriction to repair if(mutWithRand == 0): problemType = random.randrange(1,4) if(mutWithRand == 1): problemType = random.randrange(0,4) if(mutWithRand == 2): problemType = 0 # (0) No repair -> Random Change if(problemType == 0): flag_work_done, newCand = mutationRand(candidate, profList) # (1) Prof without relations (with no Subjects) in 'prof_relationsList' elif(problemType == 1): # Granting that the 'problemType' do not change good relations without restrictions to repair if(prof_relationsList.count([]) != 0): flag_work_done, newCand = mutationDeterm(profList, prof_relationsList, relations, subjIsPrefList, prof_relationsList) else: # (2) 2 or more Subjects (related to the same Prof) with same 'quadri', 'day' and 'hour' in 'i2_conflictsList' if(problemType == 2): iX_conflictsList = i2_conflictsList # (3) 2 or more Subjects (related to the same Prof) with same 'day' and 'quadri' but different 'campus' in 'i3_conflictsList' if(problemType == 3): iX_conflictsList = i3_conflictsList # Granting that the 'problemType' do not change good relations without restrictions to repair if(len(iX_conflictsList) != 0 and iX_conflictsList.count([]) != len(iX_conflictsList)): flag_work_done, newCand = mutationDeterm(profList, prof_relationsList, relations, subjIsPrefList, iX_conflictsList) return newCand #============================================================================================================== # Make a mutation into a feasible candidate def mutationF(candidate, profList, subjList, subjIsPrefList, mutWithRand=1): # Getting data to work with relations = candidate.getRelationsList()[:] prof_relationsList, _, periodPrefList, quadSabbNotPrefList, campPrefList, _ = candidate.getFeaVariables() # This While ensures that 'adjustType' will choose Randomly one 'Improvement work' flag_work_done = False while(flag_work_done == False): # Choosing one type of 'Improvement work' if(mutWithRand == 0): adjustType = random.randrange(1,6) if(mutWithRand == 1): adjustType = random.randrange(0,6) if(mutWithRand == 2): adjustType = 0 # (0) No 'Improvement work' -> Random Change if(adjustType == 0): flag_work_done, newCand = mutationRand(candidate, profList) # (1) Improving number of Relations elif(adjustType == 1): flag_work_done, newCand = mutationDeterm(profList, prof_relationsList, relations, subjIsPrefList, prof_relationsList) # (2) Improving number of Subj Preferences elif(adjustType == 2): # Building a list with relations that is NOT Pref notPrefList = [[subjIndex for subjIndex in prof_relationsList[i] if subjIsPrefList[i][subjIndex] == 0] for i in range(len(prof_relationsList))] # Granting that the 'adjustType' do not change good relations without Problems to improve if(notPrefList.count([]) != len(notPrefList)): flag_work_done, newCand = mutationDeterm(profList, prof_relationsList, relations, subjIsPrefList, prof_relationsList) else: # (3) Improving number of Periods if(adjustType == 3): XPref = periodPrefList # (4) Improving number of QuadSabb if(adjustType == 4): XPref = quadSabbNotPrefList # (5) Improving number of Campus if(adjustType == 5): XPref = campPrefList if(len(XPref) != 0): # Building a list with relations that is NOT Pref notPrefList = [[subjIndex for subjIndex in prof_relationsList[i] if [i].count(subjIndex) == 0] for i in range(len(prof_relationsList))] # Granting that the 'adjustType' do not change good relations without Problems to improve if(notPrefList.count([]) != len(notPrefList)): flag_work_done, newCand = mutationDeterm(profList, prof_relationsList, relations, subjIsPrefList, notPrefList) return newCand #============================================================================================================== # Make a selection of the solutions from all Infeasible Pop.('infPool' and 'solutionsI') def selectionI(infPool, solutionsI, maxNumCand_perPop, reposSelInf): # Check if the Infeasible pop. is empty if(len(solutionsI.getCandList()) != 0 or len(infPool.getCandList()) != 0): # Gathering both lists (infPool and solutionsI) infeasibles_List = solutionsI.getCandList() + infPool.getCandList() # Check if is needed to make a selection process if(len(infeasibles_List) > maxNumCand_perPop): # Roulette Wheel Selection # Since the value of Fitness is in the range of '-1' and '0' it is needed to be modified to a range of '0' and '1' fitnessList = [1.0 + cand.getFitness() for cand in infeasibles_List] infeasibles_List, _, _ = rouletteWheel(infeasibles_List, fitnessList, maxNumCand_perPop, reposSelInf) # Updating the (new) 'solutionsI' list to the next generation solutionsI.setCandList(infeasibles_List) if(printSteps == 1): print("Inf. Selection/", end='') #============================================================================================================== # Make a Selection of the best solutions from Feasible Pop. def selectionF(feaPool, solutionsF, maxNumCand_perPop, pctElitism, reposSelFea): # Check if the Feasible pop. is empty if(len(solutionsF.getCandList()) != 0 or len(feaPool.getCandList()) != 0): # Gathering both lists (feaPool and solutions) feasibles_List = solutionsF.getCandList() + feaPool.getCandList() # Check if is needed to make a selection process if(len(feasibles_List) > maxNumCand_perPop): # Defining the division of number of candidates between selections process elitismNum = maxNumCand_perPop * pctElitism / 100.0 if(elitismNum > 0.0 and elitismNum < 1.0): elitismNum = 1 else: elitismNum = int(elitismNum) roulNum = maxNumCand_perPop - elitismNum # Elitism and Roulette Selection listFit = [cand.getFitness() for cand in feasibles_List] maxFeasibles_List, rest_objectsList, rest_valuesList = elitismSelection(feasibles_List, listFit, elitismNum) selectedObj, _, _ = rouletteWheel(rest_objectsList, rest_valuesList, roulNum, reposSelFea) feasibles_List = maxFeasibles_List + selectedObj # Updating the (new) 'solutionsF' list to the next generation solutionsF.setCandList(feasibles_List) if(printSteps == 1): print("Feas. Selection/", end='') #============================================================================================================== # Make a rand mutation into a solution def mutationRand(candidate, profList): # Getting all relations from Candidate relations = candidate.getRelationsList()[:] # Choosing randomly a relation to be modified original = random.randrange(len(relations)) # Recording the Original Relation subj, oldProf = relations[original] # Granting that the 'newProf' is different from the 'oldProf' newProf = oldProf while(oldProf == newProf): # Finding randomly a new Prof change = random.randrange(len(profList)) newProf = profList[change] # Setting the new Relation modified, creating and setting a new Candidate relations[original]=[subj,newProf] newCand = objects.Candidate() newCand.setRelationsList(relations) # Setting the flag to finish the while flag_work_done = True # Returning the new Candidate generated return flag_work_done, newCand #============================================================================================================== # Make some deterministic type of adjustment changing some 'bad' relation def mutationDeterm(profList, prof_relationsList, relations, subjIsPrefList, problemList): # Choosing a professor to lose a relation # Roulette Wheel - more 'bad' relations -> more weight weightList = [len(i) for i in problemList] problemSubList_selected, _, _ = rouletteWheel(problemList, weightList, objectiveNum=1, repos=0) profLost_Index = problemList.index(problemSubList_selected[0]) # Choosing the relation to be modified # Roulette Wheel - less preference -> more weight lessPrefValue = [2 - subjIsPrefList[profLost_Index][subjIndex] for subjIndex in problemList[profLost_Index]] will_change_index, _, _ = rouletteWheel(problemSubList_selected[0], lessPrefValue, objectiveNum=1, repos=0) relation_will_change_index = will_change_index[0] # Recording original relation that will be modified subjList, oldProf = relations[relation_will_change_index] # Choosing new Prof to be in the selected relation # Granting that the new Prof is different from the old one newProf = oldProf while(oldProf == newProf): # Roulette Wheel - more preference AND less relations -> more weight SubjPrefValuesList = [subjIsPref_subList[relation_will_change_index] for subjIsPref_subList in subjIsPrefList] # Removing possible Zeros to make the division prof_relations_final = [len(i) if len(i) != 0 else 0.5 for i in prof_relationsList] # Getting the weights values morePrefValueList = [float(SubjPrefValuesList[i] / prof_relations_final[i]) for i in range(len(profList))] # If there is only one Prof with value != 0.0 if(morePrefValueList.count(0.0) == len(morePrefValueList) - 1): indexNotZero = [i for i in range(len(profList)) if morePrefValueList[i] != 0.0] # If is the same of the old one - random choice if(oldProf == profList[indexNotZero[0]]): newProf = profList[random.randrange(len(profList))] # If not else: newProf = profList[indexNotZero[0]] # If there are more then 1 Prof to chose else: newProf, _, _ = rouletteWheel(profList, morePrefValueList, objectiveNum=1, repos=0) newProf = newProf[0] # Setting the new relation, creating new Candidate and returning it relations[relation_will_change_index]=[subjList, newProf] # Setting the flag to finish the while flag_work_done = True # Generating a new candidate newCand = objects.Candidate() newCand.setRelationsList(relations) return flag_work_done, newCand #============================================================================================================== # Make a crossover between two solutions def crossover(cand1, cand2, twoPointsCross=-1): # The number of changes between parents will always be equal (same crossover segment size), never same size of Num of Parents Relations # twoPointsCross = False -> its chosen only one point, will have changes from the 0 relation till the chosed point # What is equal '-1' will be a random choice if(twoPointsCross == -1): twoPointsCross = random.choice([True, False]) # Getting all relations from Candidates to work with relations1 = cand1.getRelationsList()[:] relations2 = cand2.getRelationsList()[:] # OnePoint type: if(not twoPointsCross): point1 = 0 # Default initial point ('first-half') - if we make changes on 'second-half' the result woud be the same point2 = random.randrange(len(relations1)) # Randomly choosing other point that can be equal to 'point1' # Granting that not occur only a copy of parents - the chosen point is not the last relation while(point2 == len(relations1)-1): point2 = random.randrange(len(relations1)) # twoPointsCross Type else: # Generating, randomly two numbers to create a patch - can be a single modification (when p1=p2) point1, point2 = random.randrange(len(relations1)), random.randrange(len(relations1)) # Granting that 'point2' is bigger than 'point1' if(point2 < point1): p = point1 point1 = point2 point2 = p # Granting that the crossover do not only copy all relations of one Cand to the another while(point2 - point1 == len(relations1) - 1): # Generating, randomly two numbers to create a patch - can be a single modification (when p1==p2) point1, point2 = random.randrange(len(relations1)), random.randrange(len(relations1)) # Granting that 'point2' is bigger than 'point1' if(point2 < point1): p = point1 point1 = point2 point2 = p # Passing through the relations between Parents making all changes while (point1 <= point2): # Recording the original relations s1, p1 = relations1[point1] s2, p2 = relations2[point1] # Making the exchange of relations (changing only professors) relations1[point1] = s1, p2 relations2[point1] = s2, p1 # Next relation point1 = point1 + 1 # Creating and setting the two new Candidates newCand1, newCand2 = objects.Candidate(), objects.Candidate() newCand1.setRelationsList(relations1) newCand2.setRelationsList(relations2) # Returning the new Candidates return newCand1, newCand2 #============================================================================================================== # Selection by elitism def elitismSelection(objectsList, valuesList, objectiveNum): selectedObj = [] # List with the selected Objects objectsList = objectsList[:] valuesList = valuesList[:] # Getting the maximal Value Solutions while(len(selectedObj) < objectiveNum): # Finding the maximal value in the list and its respective index maxValue = max(valuesList) maxIndex = valuesList.index(maxValue) # Adding selected object to list selectedObj.append(objectsList[maxIndex]) # Removing maximal Value/Object to next selection valuesList.pop(maxIndex) objectsList.pop(maxIndex) return selectedObj, objectsList, valuesList #============================================================================================================== # Make selection of objects by Roulette Wheel def rouletteWheel(objectsList, valuesList, objectiveNum, repos=0): # objectiveNum: Num of objects will be selected # repos: Type of wheel (with reposition) # Making a copy of the original lists to work with objectsList = objectsList[:] valuesList = valuesList[:] # List with the selected Objects selectedObj = [] # Flag that allows to make all important calcs at least one time when the Roulette is configured to have Reposition reCalc = True while(len(selectedObj) < objectiveNum): # Allow the Updating of the data for the next Roulette Round without the object that was recent selected on past round if(reCalc): # When the Roulette process does have reposition of objects if(repos): reCalc = False # Find the total Value of the Objects totalValue = sum([value for value in valuesList]) # If all values are Zero if(totalValue == 0.0): valuesList = [1.0 for _ in valuesList] totalValue = len(valuesList) # Calculate the prob. of a selection for each object probObj = [float(value / totalValue) for value in valuesList] # Calculate a cumulative prob. for each object cumulative = 0.0 cumulativeProbObj = [] for q in probObj: qNew = q + cumulative cumulativeProbObj.append(qNew) cumulative = qNew # MAIN Roulette Wheel Selection process (one round) probPrev = 0.0 r = float(random.randrange(101) / 100.0) #r = float(random.randrange(0, 1, 0.001)) for i in range(len(cumulativeProbObj)): if(probPrev < r and r <= cumulativeProbObj[i]): # Adding the selected Object to 'selectedObj' selectedObj.append(objectsList[i]) if(not repos): # Removing the selected object/value from 'valuesList' to do next roulette process valuesList.pop(i) objectsList.pop(i) break probPrev = cumulativeProbObj[i] # Removing from 'objectsList' the selected objects (not removed before because of the reposition) # If there are repeated objects, (objectsList + selectedObj) will be larger then original objectsList size if(repos): for i in selectedObj: try: index = objectsList.index(i) objectsList.pop(index) valuesList.pop(index) except ValueError: index = -1 return selectedObj, objectsList, valuesList #============================================================================================================== # Detect the stop condition def stop(asks, curr_Iter, maxNum_Iter, lastMaxFit_Iter, convergDetect, maxFitFea): if(curr_Iter == maxNum_Iter): return (True if asks == 0 else ioData.askStop()) # Reached max num of iterations if(convergDetect != 0 and curr_Iter - lastMaxFit_Iter == convergDetect): return (True if asks == 0 else ioData.askStop()) # Reached convergence num of iterations return False # Continues the run with same num of iterations #==============================================================================================================
a2aa369bfa01c7d624e218b27557229d1b06ae31
myf-algorithm/Leetcode
/Huawei/99.自守数.py
202
3.640625
4
while True: try: a, res = int(input()), 0 for i in range(0, a + 1): if str(i ** 2).endswith(str(i)): res += 1 print(res) except: break
1bfb82d2f12f93926611a622d08054d9cbac9d3c
brayanjav28/brayanjav28.github.com
/Escritorio/Manipulación de imagenes - Python/codigo05.py
306
3.75
4
from time import time valor = input ('valor:') palindromo = 'Es palindromo' tiempo_inicial = time() for pos in range(0, len(valor)//2): if valor[pos] != valor[-(pos + 1)]: palindromo = 'No es palindromo' break tiempo_final = time() print(palindromo) print('tiempo:', tiempo_final - tiempo_inicial)
491fe172789ea0017ebce97c780c992feeb4dca2
RobertNguyen125/PY4E
/ex_06_string/1_Banana.py
411
3.96875
4
# fruit = 'banana' # letter = fruit[1] # the result is a because python starts counting from 0 # print(letter) '''fruit = 'banana' length = len(fruit) last = fruit[length] print(last)''' # this is wrong as there is no banana with index 6 because Python #start counting from 0 - 5 fruit = 'banana' length = len(fruit) print(length) last = fruit[length - 1] print (last) # # for char in fruit: # print(char)
aa8fbe17326e9aa3bb5b96b2da6edc64f8e6d457
Aasthaengg/IBMdataset
/Python_codes/p02392/s854074606.py
118
3.71875
4
a = raw_input().split() x = int(a[0]) y = int(a[1]) z = int(a[2]) if x < y and y < z: print "Yes" else : print "No"
a0dde5a2669101289dfff1943acec326a42a16d5
kklove0502/JDTempRepository
/JD_FactorFactory01/tools/compute.py
576
3.53125
4
import numpy as np def computeCorrelation(x,y): """ 计算功能函数,计算简单线性回归相关系数的函数 :param x,y: series,计算相关系数的两个序列 :return: r:float,相关系数 """ import math xBar = np.mean(x) yBar = np.mean(y) SSR = 0.0 varX = 0.0 varY = 0.0 for i in range(0,len(x)): diffXXbar = x[i] - xBar difYYbar = y[i] - yBar SSR += (diffXXbar * difYYbar) varX += diffXXbar**2 varY += difYYbar**2 SST = math.sqrt(varX * varY) return SSR/SST
2363bf98712cf942e28ebbac29509c3a210bd432
gabriel-tavares/python-exercicios
/lista I/exercicio-02.py
523
3.9375
4
#Escreva um programa que leia um valor em metros e o exiba convertido em milmetros print 'Exerccio-02' print '' print 'Converso de Metros em Milmetros' metros = raw_input('Metro(s): ') if not metros: print 'Campo em branco, por favo digite de novo' elif ',' in metros: print 'Use o . (ponto) como separador decimal.' else: try: metros = float(metros) mm = metros * 1000 print 'O valor da converso em milmetro :%s mm' %mm except: print 'Valor incorreto'
470c14c98ce7578a4c47539a2266f7e1e7c16b1b
jainsiddharth99/Basic-Coding-Problems
/reversestring2.py
787
4.15625
4
def reverse(s): str = "" for i in s: # here str=i+str means all elements in s are added in way # where we add elements in the beginning # so first g is inserted, than e, then e, thek k ....... #if it was str +i then elemnt is added in back str =i+str return str s = "Geeksforgeeks" print ("The original string is : ",end="") print (s) print ("The reversed string(using loops) is : ",end="") print (reverse(s)) def recursive_reverse(s): if len(s)==0: return s else: return recursive_reverse(s[1:])+s[0] s = "Geeksforgeeks" print ("The original string is : ",end="") print (s) print ("The reversed string(using loops) is : ",end="") print (recursive_reverse(s))
d8425d37ca8aa56303b185ea9dc66b40abc79877
jeff-diz/coregistration_project
/count_files.py
494
3.5625
4
import argparse import os def count_subdir_files(src_dir): pairs = os.listdir(src_dir) for p in pairs: files = os.listdir(os.path.join(src_dir, p)) if len(files) > 1: print('{}: {}'.format(p, len(files))) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('src_dir', type=os.path.abspath, help='Path to directory holding pair directories') args = parser.parse_args() src_dir = args.src_dir count_subdir_files(src_dir)
d8eb83c84a0a87d48fc66ae8da57159664871e60
ogerasymenko/sample
/My_Py_Code/triangle.2.py
288
3.96875
4
print() s = '' for i in range(1, 6): s += str(i) s += ' ' print (s) print() j = '' for i in range(1, 6): j += str(i) j += ' ' print (j) print() n = int(input('Введите n: ')) num = '' for i in range(1, n+1): num += str(i) num += ' ' print(num)
5da622d01c0f231eed76301ef9cb559dbdc3149d
HegnerCarvalho/algoritmos
/Algoritmos/zzz.py
347
3.921875
4
idade=input("Digite sua idade:") idade=int(idade) if idade>=18: print("Você é maior.") print("Entrada permitida...") else: print("Menor detectado...") print("Entrada negada!") print('Fim') if "Rafael"=="rafael": print("Letras maiúsculas não importam") else: print("Letras maiúsculas são diferentes de minúsculas")
5aea98f3fb31f9f9beb8bf9b6b42548096742c09
lfteixeira996/Coding-Bat
/Python/String-1/make_abba.py
695
4.125
4
import unittest ''' Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi". make_abba('Hi', 'Bye') -> 'HiByeByeHi' make_abba('Yo', 'Alice') -> 'YoAliceAliceYo' make_abba('What', 'Up') -> 'WhatUpUpWhat' ''' def make_abba(a, b): return a+b+b+a class Test_make_abba(unittest.TestCase): def test_1(self): self.assertEqual(make_abba('Hi', 'Bye'), 'HiByeByeHi') def test_2(self): self.assertEqual(make_abba('Yo', 'Alice'), 'YoAliceAliceYo') def test_3(self): self.assertEqual(make_abba('What', 'Up'), 'WhatUpUpWhat') if __name__ == '__main__': unittest.main()
13a391ec62029ac52ed2f19110ef60114210fd1b
jedzej/tietopythontraining-basic
/students/barecki_andrzej/lesson_02_flow_control/L3_Knight_move.py
801
3.640625
4
# Chess knight moves like the letter L. It can move two cells horizontally and one cell vertically, # or two cells vertically and one cells horizontally. Given two different cells of the chessboard, # determine whether a knight can go from the first cell to the second in one move. # The program receives the input of four numbers from 1 to 8, each specifying the column and row number, first two - # for the first cell, and then the last two - for the second cell. The program should output YES if a knight can go # from the first cell to the second in one move, or NO otherwise. ax = int(input()) ay = int(input()) bx = int(input()) by = int(input()) if abs(ax - bx) == 1 and abs(ay - by) == 2 or abs(ax - bx) == 2 and abs(ay - by) == 1: result = 'YES' else: result = 'NO' print(result)
8250eadeaffdb192f60877616fae8948f96fcf81
KIMJINMINININN/Python
/Pandas/source/Basic/test15.py
571
3.578125
4
import pandas as pd exam_data = {'이름' : ['서준', '우현', '인아'], '수학': [90, 80, 70], '영어' : [98, 89, 95], '음악' : [85, 95, 100], '체육' : [100, 90, 90]} # df.set_index('이름', inplace=True) df = pd.DataFrame(exam_data) print(df) print('\n') # 특정 열을 index로 만들어주기 ndf = df.set_index(['이름']) print(ndf) print('\n') ndf2 = ndf.set_index('음악') print(ndf2) print('\n') ndf3 = ndf.set_index(['수학', '음악']) print(ndf3) print(ndf3.loc[90,85]) print(ndf3.columns)
c1a052769236ebcfbc2daf1b3d41be47e1bdf57d
marikaSvensson/Knightec
/pythonProgs/code170515/mainSubsets_Permutations_Combinations.py
208
3.75
4
# prime def is_prime(n): for i in range(2,n): if n % i == 0: return False else: return True n = 21 a = [] for i in range(2,n): if (is_prime(i)): a.append(i) print a
d5ef95a411e9c7463712fe8ae5d5150b3b540652
maxstrano/jpmorgan-simplestocks
/main.py
13,225
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Massimo Strano, PhD # NOTES: # - Requires python 3 # - There were ambiguities in the provided formulae. # - I made a number of assumptions in order to provide code that can be run as is. # Please refer to the comments in the code for more information. import sys from datetime import datetime, timedelta import math from random import seed, randint, uniform, random class Trade: """ This class implements a trade operation for a stock. """ def __init__(self, symbol, t, quantity, buyVsSell, price): """ Instantiate a new Trade object. Arguments: symbol (str): stock symbol t (datetime.datetime): timestamp for the trade quantity (int): number of stocks traded buyVsSell (Boolean): a flag to indicate if the trade is a purchase (True), or a sale (False) price (int): the initial ticker price, in pennies """ self.symbol = symbol self.timestamp = t self.quantity = quantity self._buyVsSell = buyVsSell self.price = price def isSale(self): """ Return True if this Trade was a sale """ return not self._buyVsSell def isPurchase(self): """ Return true if this trade was a purchase. """ return self._buyVsSell def __str__(self): """ Return a string representation of this Trade object. """ s = 'Trade (' if self._buyVsSell: s = s + 'Purchase) ' else: s = s + 'Sale) ' s = s + 'Quantity: ' + str(self.quantity) + ', Price: ' + str(self.price) \ + ' - Timestamp: ' + str(self.timestamp) return s class Stock: """ This class implements a stock. This also includes a history of the trades for that stock, and provides methods that rely on this history - to calculate the dividend yield and the P/E ratio. """ def __init__(self, symbol, initial_price, preferredVsCommon, par_value, last_dividend, fixed_dividend=0): """ Instantiate a new Stock object. Arguments: symbol (str): the stock symbol initial_price (int): the initial price of the stock, in pennies preferredVsCommon (Boolean): a flag to indicate if this is a preferred stock (True) or a common one (False) par_value (int): the par value of this stock, in pennies last_dividend (int): the last dividend of this stock, in pennies fixed_dividend (float): the fixed dividend of this stock - default value is 0. """ self.symbol = symbol self.trades = [] self.price = initial_price self.preferred = preferredVsCommon self.par_value = par_value self.last_dividend = last_dividend self.fixed_dividend = fixed_dividend def record_trade(self, trade): """ Record a new trade on this stock and recalculate the new ticker price. """ self.trades.append(trade) # Automatically recalculate the ticker price self.recalculate_price() def recalculate_price(self): """ Recalculate the new ticker price and return it, using the trades from the last 15 minutes. IMPORTANT NOTE: In the formula, there is a division by zero if there were no trades in the time interval considered. In this case I assumed the price would remain the same. """ current_time = datetime.now() fifteen_minutes = timedelta(minutes=15) # Loop over the past trades, from the latest to the oldest, # checking the ones that happened in the last 15 minutes, and # accumulating en passant the values used to calculate the stock price # and stopping at the first trade older than the 15 minutes threshold # since all the others will be older than that. total_qty = 0 total_traded_value = 0 for t in self.trades: time_diff = current_time - t.timestamp if (time_diff <= fifteen_minutes): total_qty = total_qty + t.quantity total_traded_value = total_traded_value + (t.price * t.quantity) else: # If we found a trade older than 15 minutes, all of the following ones will also be older. break # If some trades have been made in the last 15 minutes, the total quantity will # be greater than zero; in this case recalculate the price. Otherwise, the price will # be taken to remain the same, to avoid divisions by zero. if total_qty > 0: self.price = total_traded_value / total_qty return self.price def get_dividend_yield(self): """ Calculate and return the dividend yield for this stock. IMPORTANT NOTE: The formula for the preferred stock was ambiguous and unclear. Searching online provided very different formulae, because of course they do not need to simplify. I had to make an assumption, and I decided that, as it says only "dividend", I was going to use the last dividend value. It should probably be a completely different value involving the fixed dividend, as well as the last dividend, but this goes beyond my financial knowledge. This can be easily fixed if I am given the right formula. """ if self.preferred: return ((self.par_value * self.last_dividend) / self.price) else: return (self.last_dividend / self.price) def get_price_earnings_ratio(self): """ Calculate and return the P/E ratio for this stock. This class can raise an exception if the last dividend is zero, as the formula can't be applied in this case. """ if self.last_dividend > 0: return self.price / self.last_dividend else: raise ZeroDivisionError('Last dividend is zero, P/E ratio cannot be calculated') def __str__(self): """ Return a string representation of this Stock object, including the trades for it. """ s = '** Stock (' if self.preferred: s = s + 'Preferred) ' else: s = s + 'Common) ' s = s + '- Symbol: ' + self.symbol + ', Current price: ' + str(self.price) \ + ', Last dividend: ' + str(self.last_dividend) + ', Par value: ' + str(self.par_value) \ + ', Number of trades: ' + str(len(self.trades)) for trade in self.trades: s = s + '\n* ' + str(trade) return s class StockExchangeEngine: """ This class implements a simplified version of a subset of the tasks of a stock exchange. It keeps a set of stocks and of their trades, and provides methods to record trades and to calculate the GBCE All Share Index using the provided formulae. """ def __init__(self): """ Instantiate a new stock exchange, with an empty initial list of stocks. """ self.all_stocks = dict() def add_stock(self, symbol, initial_price, preferredVsCommon, par_value, last_dividend, fixed_dividend=0): """ Add a new stock to the stock exchange, if it doesn't already exist. This operation is idempotent. Arguments: symbol (str): the stock symbol initial_price (int): the initial price of the stock, in pennies preferredVsCommon (Boolean): a flag to indicate if this is a preferred stock (True) or a common one (False) par_value (int): the par value of this stock, in pennies last_dividend (int): the last dividend of this stock, in pennies fixed_dividend (float): the fixed dividend of this stock. """ if not (symbol in self.all_stocks): self.all_stocks[symbol] = Stock(symbol, initial_price, preferredVsCommon, par_value, last_dividend, fixed_dividend) def record_trade(self, symbol, trade): """ Record a trade for a stock, if its symbol is present. Otherwise, ignore the request. Arguments: symbol (str): the symbol of the traded stock. trade (Trade): the trade to record for the given stock. """ if symbol in self.all_stocks: self.all_stocks[symbol].record_trade(trade) def get_all_share_index(self): """ Calculate the GBCE All Share Index, using the provided formula. """ prices_product = 1 for stock in self.all_stocks.values(): prices_product = prices_product * stock.price # Nth root of the sum of the prices! return math.pow(prices_product, 1/len(self.all_stocks)) def get_symbols(self): """ Return a list of the symbols of all available stocks. """ return self.all_stocks.keys() def get_stock(self, symbol): """ Return the stock associated with a given symbol. If the symbol does not exist, return None. Argument: symbol (str): the wanted symbol """ if symbol in self.all_stocks: return self.all_stocks[symbol] else: return None def generate_random_time_deltas(min_trades, max_trades, min_td, max_td): """ Generate a list of integers, each representing the time differential in minutes for a Trade from the current time. The length of the list is randomly determined, and it represents the number of trades to generate. Arguments: min_trades (int): The minimum length of the list max_trades (int): The maximum length of the list min_td (int): The minimum time differential max_td (int): The maximum time differential """ time_deltas = [] no_of_trades = randint(min_trades, max_trades) for t_i in range(no_of_trades): time_deltas.append(randint(min_td, max_td)) return sorted(time_deltas) def generate_random_trade(symbol, time_delta, price_variation, current_price, min_qty, max_qty): """ Generate a Trade object, with a time stamp generated from a time differential in minutes. The trade price and quantity are randomly generated; the price is generated from the current price by adding or subtracting a random quantity controlled by the price variation, and the quantity is a random number between the provided max and min quantities provided. Arguments: symbol (str): The stock symbol time_delta (int): The value in minutes of the time differential price_variation (float): The percentage of variation from the initial price, used to randomly determine this trade's price. current_price (int): The ticker price of the stock, in pennies min_qty (int): The minimum quantity for the trade max_qty (int): The maximum quantity for the trade """ # Generate a timestamp time_delta minutes in the past now = datetime.now() a_time_delta = timedelta(minutes=time_delta) timestamp = now - a_time_delta # Generate a trade price, adding a factor to the current price obtained # multiplying the current price by a random factor. # Uniform distribution. trade_price = current_price + int(current_price * uniform(-price_variation, price_variation)) qty = randint(min_qty, max_qty) # Determine randomly whether this was a purchase or a sale. # Chances are 50-50, with uniform distribution. buyVsSell = True if random() >= 0.5: buyVsSell = False return Trade(symbol, timestamp, qty, buyVsSell, trade_price) def main(args): print ('*** Simple stocks ***') # Simulation data min_trades = 6 # Min number of trades max_trades = 12 # Max number of trades min_time_delta = 1 # Min time differential for a trade - one minute ago max_time_delta = 45 # Max time differential for a trade - 45 minute ago price_variation = 0.5 # Variation for randomly generated trade prices min_quantity = 20 # Min quantity of traded stocks max_quantity = 120 # Max quantity of traded stocks # Sample data, taken from the Super Simple Stocks document # # NOTE: I am also adding an initial ticker price for the stocks. # dataset = [ dict(symbol='TEA', initial_price=120, preferred=False, par_value=100, last_dividend=0, fixed_dividend=0), dict(symbol='POP', initial_price=150, preferred=False, par_value=100, last_dividend=8, fixed_dividend=0), dict(symbol='ALE', initial_price=170, preferred=False, par_value=60, last_dividend=23, fixed_dividend=0), dict(symbol='GIN', initial_price=190, preferred=True, par_value=100, last_dividend=8, fixed_dividend=0.02), dict(symbol='JOE', initial_price=200, preferred=False, par_value=250, last_dividend=13, fixed_dividend=0) ] # Instantiate stock engine and add the stocks se_engine = StockExchangeEngine() for s in dataset: se_engine.add_stock(s['symbol'], s['initial_price'], s['preferred'], \ s['par_value'], s['last_dividend'], s['fixed_dividend']) print ('** Created stocks: ', se_engine.get_symbols()) print() # Create a trade history for the stocks. The idea: generate a random list of time differentials, # that represent the time distance in minutes from now when a random trade occurred. now = datetime.now() for s in se_engine.get_symbols(): current_price = se_engine.get_stock(s).price # Generate a list of time differential for the trades for the current stock time_deltas = generate_random_time_deltas(min_trades, max_trades, min_time_delta, max_time_delta) # For each time differential, generate a random trade operation # with randomly determined price and quantity for td in time_deltas: current_trade = generate_random_trade(s, td, price_variation, current_price, min_quantity, max_quantity) se_engine.record_trade(s, current_trade) stock = se_engine.get_stock(s) print (str(stock)) print () print ('** Created trade history\n') print ('** GBCE All Share Index:', se_engine.get_all_share_index()) # Conclusion! return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
1796c20dcac3c1adb0a8d8508531a6dc2e19e7ac
Donggeun-Lim3/ICS3U-Unit3-06-Python
/try.py
793
4.25
4
#!/usr/bin/env python3 # Created by Donggeun Lim # Created on December 2020 # This program is number guessing game import random def main(): # this function checks if number is not 5 # input integer_as_string = input("Enter your number ") print("") # process random_number = random.randint(1, 9) # a number between 1 and 9 try: integer_as_number = int(integer_as_string) if random_number == integer_as_number: # output print("You are right!") print("random number is {}".format(random_number)) else: print("you are wrong") print("random number is {}".format(random_number)) except Exception: print("This was not an integer") if __name__ == "__main__": main()
0eaf8d9d3fe88dadceafc87fe97f9e923d70dd2b
RedRem95/AoC2019
/Day04/task.py
723
3.515625
4
from typing import List from Day04 import INPUT from helper import partner_check, only_increase, int_to_iter, atleast_one_pair_check from main import custom_print def create_passwords(min_pw=min(*INPUT), max_pw=max(*INPUT)) -> List: return [i for i in range(min_pw, max_pw + 1, 1) if partner_check(int_to_iter(i)) and only_increase(int_to_iter(i))] def create_passwords_2(min_pw=min(*INPUT), max_pw=max(*INPUT)) -> List: return [i for i in range(min_pw, max_pw + 1, 1) if atleast_one_pair_check(int_to_iter(i)) and only_increase(int_to_iter(i))] def main(): custom_print("Found %s passwords A1" % len(create_passwords())) custom_print("Found %s passwords A2" % len(create_passwords_2()))
726ea99dad70b9b1bafe2ca5baa550fcd45bbfbb
MyCatWantsToKillYou/TimusTasks
/Volume 11/src/Grant.py
276
3.90625
4
# task #2056 # Difficulty 58 grades = [] for i in range(int(input())): grades.append(int(input())) if 3 in grades: print('None') elif sum(grades)/len(grades) == 5: print('Named') elif sum(grades)/len(grades) >= 4.5: print('High') else: print('Common')
ac890b226b69fbc626a4b27975eb1f58d359cb1e
lliei/learn-python
/twl/c5.py
331
3.765625
4
# reduce from functools import reduce list_x = [1,2,3] list_y = [1,2,3,4,5,6,7,8] list_xy = [(0,0),(1,2),(2,2),(-1,-2)] # def func(x): # return x * x r = reduce(lambda x,y:x*y,list_x) # 集合列表与参数要相同 # print(r) print(r) # 扩展 # 大数据 # map/reduce 模型 函数式编程 映射 归约 并行计算
6cc664cc5105cd3ea20f7eadcaec25ef063d09af
leninesprj/Python_Sketches
/CollatzHypothesis.py
764
4.03125
4
# Writing Collatz's hypothesis # In 1937, a German mathematician named Lothar Collatz formulated an # intriguing hypothesis (it still remains unproven) which can be described # in the following way: # take any non-negative and non-zero integer number and name it c0; # if it's even, evaluate a new c0 as c0 ÷ 2; # otherwise, if it's odd, evaluate a new c0 as 3 × c0 + 1; # if c0 ≠ 1, skip to point 2. # The hypothesis says that regardless of the initial value of c0, it will # always go to 1. #----------------------- c0 = int(input("enter a number greather than 0: ")) steps = 0 while c0 != 1: if c0 == 1: break steps +=1 if c0%2 == 0: c0 = c0/2 else: c0 = 3*c0+1 print(int(c0)) print("steps:", steps)
8ae4f2edd42f227efc7cf0f753e68a4f649e2212
Yumingyuan/algorithm_lab
/minmax.py
1,383
3.8125
4
# -*- coding: utf-8 -*- import random import time def min_max_method1(search_data):#穷举搜索 length=len(search_data) temp_max=search_data[1] temp_min=search_data[1] for i in range(2,length):#从第二个元素进行对比 if search_data[i]>temp_max: temp_max=search_data[i] if search_data[i]<temp_min: temp_min=search_data[i] return temp_max,temp_min def min_max_method2(search_data,low,high):#分治法进行搜索函数 #the situation of only two number if high-low<=1:#当只有1个或2个元素时 if search_data[low]<search_data[high]: return (search_data[high],search_data[low]) else: return (search_data[low],search_data[high]) #the situation of more number than 2 mid_num=int((low+high)/2) x1,y1=min_max_method2(search_data,low,mid_num) x2,y2=min_max_method2(search_data,mid_num+1,high) #比较大小 if x1<x2: x=x2 else: x=x1 #比较大小 if y1<y2: y=y1 else: y=y2 return x,y if __name__=="__main__": range_upper=200 length=15 list_search=random.sample(range(range_upper),length) print('Before search:',list_search) starttime=time.time() print(min_max_method1(list_search)) endtime=time.time() print("function1 time consuming:",(endtime-starttime),"s") starttime=time.time() print(min_max_method2(list_search,0,len(list_search)-1)) endtime=time.time() print("function2 time consuming:",(endtime-starttime),"s")
0f93d8803a87e9cbae3dc98bcfe7566f6f7a52ee
fanyichen/assignment6
/mz775/assignment6/assignment6.py
7,406
4.34375
4
from interval import * import sys def no_space(interval_string): ''' use this function to get rid of white space in intervals from users ''' no_space_str = str() for element in interval_string: if element != ' ': no_space_str += element return no_space_str def mergeIntervals(int1,int2): ''' Question 2. This is a function to merge two overlapping intervals, and would throw an value error if two intervals do not overlap. ''' int1 = no_space(int1) int2 = no_space(int2) int1 = interval(int1) int2 = interval(int2) if int1.upper_real >= int2.lower_real or int1.lower_real >= int2.upper_real: # see if there is overlapping integers = [int1.lower_input,int1.upper_input,int2.lower_input,int2.upper_input] integers.sort() #sort 4 integers from user merged_lower_integer = str(integers[0]) merged_upper_integer = str(integers[-1]) #get the biggest and smallest integers that can be integer bounds for merged interval int1_convert_list = [int1.left,str(int1.lower_input),str(int1.upper_input),int1.right] int2_convert_list = [int2.left,str(int2.lower_input),str(int2.upper_input),int2.right] #use multiple if statement to rearrange integer bounds and interval bounds to get merged interval if merged_lower_integer in int1_convert_list: if merged_lower_integer in int2_convert_list: if int1_convert_list [0] == int2_convert_list [0]: merged_left = int1_convert_list [0] else: merged_left = '[' else: merged_left = int1_convert_list [0] else: merged_left = int2_convert_list [0] if merged_upper_integer in int1_convert_list: if merged_upper_integer in int2_convert_list: if int1_convert_list [-1] == int2_convert_list [-1]: merged_right = int1_convert_list [-1] else: merged_right = ']' else: merged_right = int1_convert_list [-1] else: merged_right = int2_convert_list [-1] merged_interval_list = [merged_left,merged_lower_integer,',',merged_upper_integer,merged_right] merged_interval = ''.join(merged_interval_list) else: raise ValueError return merged_interval def interval_list(interval_list_input): ''' this is a function that converts a string consisting of multiple intervals such as '(1,3),(2,5),[9,10]' into a string list containing many interval elements, such as ['(1,3)','(2,5)','[9,10]'] ''' interval_list_input = no_space(interval_list_input) interval_list_split1 = interval_list_input.split('],') interval_list=[] for element in interval_list_split1: if element[-1] != ']' and element[-1] != ')': element = element + ']' interval_list.append(element) interval_list_1=[] for element in interval_list: element = element.split('),') interval_list_1.append(element) interval_list_2=[] interval_list_3=[] for i in range(0,len(interval_list_1)): for j in range(0,len(interval_list_1[i])): if interval_list_1[i][j][-1] != ')' and interval_list_1[i][j][-1] != ']': interval_list_1[i][j] = interval_list_1[i][j] + ')' interval_list_2.append(interval_list_1[i][j]) else: interval_list_3.append(interval_list_1[i][j]) interval_list_final = interval_list_2+interval_list_3 new = [] for element in interval_list_final: try: element=interval(element) new.append(element) except validationError: new=[] if len(new) == len(interval_list_final): return interval_list_final else: raise validationError def sorting(int1,int2): ''' this is a function that sorts intervals by the smallest number in the interval ''' int1=no_space(int1) int2=no_space(int2) int1 = interval(int1) int2 = interval(int2) if int1.lower_real < int2.lower_real: return -1 if int1.lower_real > int2.lower_real: return 1 else: return 0 def mergeOverlapping(intervals): ''' Question 3. This is a function that merges a list of intervals. ''' intervals = interval_list(intervals) #convert the input into a list of many interval strings intervals.sort(sorting) #sort the intervals by their smallest number intervals_list=[] # an empty list used to store merged and unmerged intervals for i in range(0,len(intervals)): if len(intervals_list) == 0: intervals_list.append(intervals[i]) else: try: merged = mergeIntervals(intervals_list[-1],intervals[i]) intervals_list.pop() intervals_list.append(merged) except ValueError: intervals_list.append(intervals[i]) return intervals_list def insert(intervals,newint): ''' Question 4. This is a function that inserts a new interval into a list of intervals and returns merged results ''' intervals = intervals + ','+newint return mergeOverlapping(intervals) def main(): ''' Question 5. This function takes input from users and return merged results. ''' user_input = raw_input('List of intervals?') while len(user_input) == 0: print 'please enter intervals' user_input = raw_input('List of intervals?') if user_input == 'quit': sys.exit() else: try: user_input_convert = interval_list(user_input) user_input_valid = user_input except validationError: raise validationError('there is invalid interval(s) in your list, please re-enter in the correct format') if len(user_input_convert) > 0: user_input_single_interval = raw_input('Interval?') while len(user_input_single_interval) == 0: print 'please enter interval or quit' user_input_single_interval = raw_input('Interval?') while len(user_input_single_interval) != 0: if user_input_single_interval == 'quit': sys.exit() else: user_input_single_interval_check = interval(user_input_single_interval) while user_input_single_interval_check.validation() == False: print 'invalid interval' user_input_single_interval = raw_input('Interval?') new_int_list = insert(user_input_valid,user_input_single_interval) user_input_valid = user_input_valid+','+user_input_single_interval print new_int_list user_input_single_interval = raw_input('Interval?') if __name__ == '__main__': main()
1822c620f7bb4a3f9fd1c43410144d0a335055d0
Fake45mar/Python
/convertIntToRom.py
3,931
3.5
4
varNum = int(input("Enter number")) arrayList = ['I', 'V', 'X', 'L', 'C'] def lessThanTen(number): if number >= 1 and number < 4: print(arrayList[0] * number) elif number == 4: print(arrayList[0] + arrayList[1]) elif number == 5: print(arrayList[1]) elif number > 5 and number < 9: print(arrayList[1] + arrayList[0] * (number - 5)) elif number == 9: print(arrayList[0] + arrayList[2]) elif number == 10: print(arrayList[2]) def biggerThanTenAndLessThanFourty(number): varAmount = number // 10 stringTens = arrayList[2] * varAmount number = number % 10 if number == 0: print(stringTens) elif number >= 1 and number < 4: print(stringTens + arrayList[0] * number) elif number == 4: print(stringTens + arrayList[0] + arrayList[1]) elif number == 5: print(stringTens + arrayList[1]) elif number > 5 and number < 9: print(stringTens + arrayList[1] + arrayList[0] * (number - 5)) elif number == 9: print(stringTens + arrayList[0] + arrayList[2]) elif number == 10: print(stringTens + arrayList[2]) def biggerThanFourtyAndLessThanFifty(number): varAmount = number // 10 stringTens = arrayList[2] + arrayList[3] number = number % 10 if number == 0: print(stringTens) elif number >= 1 and number < 4: print(stringTens + arrayList[0] * number) elif number == 4: print(stringTens + arrayList[0] + arrayList[1]) elif number == 5: print(stringTens + arrayList[1]) elif number > 5 and number < 9: print(stringTens + arrayList[1] + arrayList[0] * (number - 5)) elif number == 9: print(stringTens + arrayList[0] + arrayList[2]) elif number == 10: print(stringTens + arrayList[2]) def biggerThanFourtyAndLessThanFifty(number): varAmount = number // 10 stringTens = arrayList[2] + arrayList[3] number = number % 10 if number == 0: print(stringTens) elif number >= 1 and number < 4: print(stringTens + arrayList[0] * number) elif number == 4: print(stringTens + arrayList[0] + arrayList[1]) elif number == 5: print(stringTens + arrayList[1]) elif number > 5 and number < 9: print(stringTens + arrayList[1] + arrayList[0] * (number - 5)) elif number == 9: print(stringTens + arrayList[0] + arrayList[2]) elif number == 10: print(stringTens + arrayList[2]) #print(varAmount,stringTens,number) def biggerThanFiftyAndLessThanNinety(number): varAmount = number // 10 stringTens = arrayList[3] + arrayList[2] * ((number - 50)//10) number = number % 10 print(varAmount,stringTens,number) if number == 0: print(stringTens) elif number >= 1 and number < 4: print(stringTens + arrayList[0] * number) elif number == 4: print(stringTens + arrayList[0] + arrayList[1]) elif number == 5: print(stringTens + arrayList[1]) elif number > 5 and number < 9: print(stringTens + arrayList[1] + arrayList[0] * (number - 5)) elif number == 9: print(stringTens + arrayList[0] + arrayList[2]) elif number == 10: print(stringTens + arrayList[2]) def biggerThanNinetyAndLessThanOneHundred(number): varAmount = number // 10 stringTens = arrayList[2] + arrayList[4] number = number % 10 #print(varAmount,stringTens,number) if number == 0: print(stringTens) elif number >= 1 and number < 4: print(stringTens + arrayList[0] * number) elif number == 4: print(stringTens + arrayList[0] + arrayList[1]) elif number == 5: print(stringTens + arrayList[1]) elif number > 5 and number < 9: print(stringTens + arrayList[1] + arrayList[0] * (number - 5)) elif number == 9: print(stringTens + arrayList[0] + arrayList[2]) elif number == 10: print(stringTens + arrayList[2]) if varNum > 0 and varNum <= 100: if varNum <= 10: lessThanTen(varNum) elif varNum > 10 and varNum < 40: biggerThanTenAndLessThanFourty(varNum) elif varNum >= 40 and varNum < 50: biggerThanFourtyAndLessThanFifty(varNum) elif varNum >= 50 and varNum < 90: biggerThanFiftyAndLessThanNinety(varNum) elif varNum >= 90: biggerThanNinetyAndLessThanOneHundred(varNum)
7d56bac8179de5144b155e8bb80eb8d11e8f46e3
Graph-Algorithms-Visualizations/graph-algorithms
/NPAlgorithms.py
7,185
4
4
from modify import Graph def intToBinary(number, size): """ Converts a decimal number to binary form Parameters: ========== number: Integer The Number to be converted into binary form size: Integer The maximum length of the returning binary list Returns: ======= list: Returns a list of length size consisting of 0's and 1's representing binary form of number """ binary = [0 for i in range(size)] i = 0 while number > 0: binary[i] = number%2 number = number // 2 i += 1 return binary def setBits(binary): """ Calculates the number of ones in the binary Parameters: ========== binary: List The binary list of a decimal number Returns: ======= Integer: Returns number of 1's in the binary representation """ counter = 0 for i in binary: if i == 1: counter += 1 return counter def visitAllNeighborClique(visited, binary): """ Checks wether all considered nodes in binary are visited or not. This function is used as a utility function for the clique subroutine Parameters: ========== visited: list The information of visited and unvisited node binary: list The nodes which are under consideration Returns: ======= bool: If all considered nodes are visited then True otherwise False """ n = len(binary) for i in range(n): if binary[i] == 1 and visited[i] == False: return False return True class AlgorithmManager: def __init__(self, graph): self.graph = graph def runAlgorithm(self, id): """ Runs the corresponding algorithm Parameters: ========== id: Integer represents the algorithm id """ if id == 1: return self.minimumDominantSet() elif id == 2: return self.maximumIndependentSet() elif id == 3: return self.maximumClique() def minimumDominantSetUtil(self, binary): """ Checks wether the binary consideration of nodes is a valid Dominant Set or not Parameters: ========== binary: list The nodes which are under consideration Returns: ======= bool: If all considered nodes form a Dominant Set then True otherwise False """ n = len(self.graph.adjacencyList) visited = [False for i in range(n)] for i in range(n): if binary[i] == 1: visited[i] = True for j in self.graph.adjacencyList[i]: visited[j.toNode.key] = True for i in range(n): if visited[i] == False: return False return True def minimumDominantSet(self): """ Calculates the dominant set of minimum size Returns: ======= list: A list comprising of 0's and 1's of length equal to number of nodes in graph. 0: Represents the node was not considered 1: Represents the node was considered """ # ID:1 n = len(self.graph.adjacencyList) minimumSet = [] minimum = n rangeToCover = 2**n for i in range(rangeToCover): binary = intToBinary(i,n) involvedNodes = setBits(binary) if self.minimumDominantSetUtil(binary) == True: if minimum > involvedNodes: minimum = involvedNodes minimumSet = binary return minimumSet def maximumIndependentSetUtil(self,binary): """ Checks wether the binary consideration of nodes is a valid independent set or not Parameters: ========== binary: list The nodes which are under consideration Returns: ======= bool: If all considered nodes form an Independent Set then True otherwise False """ n = len(self.graph.adjacencyList) visited = [False for i in range(n)] for i in range(n): if binary[i] == 1: visited[i] = True for i in range(n): if visited[i] == True: for j in self.graph.adjacencyList[i]: if visited[j.toNode.key] == True: return False return True def maximumIndependentSet(self): """ Calculates the independent set of maximimum size Returns: ======= list: A list comprising of 0's and 1's of length equal to number of nodes in graph. 0: Represents the node was not considered 1: Represents the node was considered """ #ID:2 n = len(self.graph.adjacencyList) maximumSet = [] maximum = 0 rangeToCover = 2**n for i in range(rangeToCover): binary = intToBinary(i,n) involvedNodes = setBits(binary) if self.maximumIndependentSetUtil(binary) == True: if maximum < involvedNodes: maximum = involvedNodes maximumSet = binary return maximumSet def maximumCliqueUtil(self, binary): """ Checks wether the binary consideration of nodes is a valid clique or not Parameters: ========== binary: list The nodes which are under consideration Returns: ======= bool: If all considered nodes forms a clique then True otherwise False """ n = len(self.graph.adjacencyList) for i in range(n): if binary[i] == 1: visited = [False for j in range(n)] visited[i] = True for j in self.graph.adjacencyList[i]: visited[j.toNode.key] = True if not visitAllNeighborClique(visited, binary): return False return True def maximumClique(self): """ Calculates the clique of maximimum size Returns: ======= list: A list comprising of 0's and 1's of length equal to number of nodes in graph. 0: Represents the node was not considered 1: Represents the node was considered """ #ID:3 n = len(self.graph.adjacencyList) maximumSet = [0 for i in range(n)] maximum = 0 rangeToCover = 2**n for i in range(rangeToCover): binary = intToBinary(i,n) involvedNodes = setBits(binary) if self.maximumCliqueUtil(binary) == True: if maximum < involvedNodes: maximum = involvedNodes maximumSet = binary return maximumSet
6efa4ac39ed59d0464e9addecac3784bd3e7f071
surendragalwa11/data-structures
/sorts/insertion-sort.py
714
4
4
def insertionSort(fullList): listLen = len(fullList) for i in range(1, listLen): keyVal = fullList[i] j = i-1 while j >= 0 and keyVal < fullList[j]: fullList[j+1] = fullList[j] fullList[j] = keyVal j -= 1 return fullList if __name__ == '__main__': fullList = [] elementsCount = int(input('Enter number of elements: ')) print('Enter elements: ') for i in range(elementsCount): element = int(input()) fullList.append(element) # fullList = [12, 7, 19, 3, 15, 17] # fullList = [14,46,43,27,57,41,45,21,70] fullList = insertionSort(fullList) print('Sorted list is', fullList)