text
stringlengths
37
1.41M
maior = menor = 0 for x in range(5): peso = float(input('Informe o peso da {} pessoa'.format(x+1))) if menor == 0: menor = peso maior = peso elif peso > maior: maior = peso elif peso < menor: menor = peso print('O maior peso foi {}KG e o menor peso foi {}KG'.format(maior, menor))
""" A decorator for caching properties in classes. Examples: >>> class Foo(object): ... @cached_property ... def bar(self): ... print("This message only print once") ... return None >>> foo = Foo() >>> foo.bar This message only print once >>> foo.bar """ import functools def cached_property(func): attr = '_cached_' + func.__name__ @property @functools.wraps(func) def decorator(self, *args, **kwargs): if not hasattr(self, attr): setattr(self, attr, func(self, *args, **kwargs)) return getattr(self, attr) return decorator
#!/usr/bin/env python """ This is my implementation of Application #4 from the Algorithmic thinking course. created by RinSer """ import random from matplotlib import pyplot as plot import math import project4 # File names HUMAN_EYELESS_PROTEIN = 'HumanEyelessProtein.txt' FRUITFLY_EYELESS_PROTEIN = 'FruitflyEyelessProtein.txt' CONSENSUS_PAX_DOMAIN = 'ConsensusPAXDomain.txt' SCORING_MATRIX = 'PAM50.txt' def read_protein(file_name): """ Helper function to read protein sequence from a file. Returns the sequence as a string. """ protein_file = open(file_name, 'r') protein_sequence = protein_file.read().rstrip() protein_file.close() return protein_sequence def read_scoring_matrix(file_name): """ Helper function to read a scoring matrix from a file. Returns the scoring matrix as a dictionary. """ matrix_file = open(file_name, 'r') scoring_matrix = dict() # Read the first line and create a list column_values = matrix_file.readline().split() # Read the other lines for line in matrix_file.readlines(): scores = line.split() row_value = scores.pop(0) scoring_matrix[row_value] = dict() for column_value, score in zip(column_values, scores): scoring_matrix[row_value][column_value] = int(score) matrix_file.close() return scoring_matrix def remove_dashes(string): """ Helper function to remove dashes from a given string. Returns the string without dashes. """ dashless = '' for character in string: if character != '-': dashless += character return dashless def compare_strings(string1, string2): """ Helper function to compare the characters in two strings of equal size. Returns the percentage number of equal characters as a floating point number. """ number_of_equals = 0 if len(string1) == len(string2): for idx_c in range(len(string1)): if string1[idx_c] == string2[idx_c]: number_of_equals += 1 return number_of_equals/float(len(string1))*100 def generate_null_distribution(seq_x, seq_y, scoring_matrix, num_trials): """ Takes as input two sequences seq_x and seq_y, a scoring matrix scoring_matrix, and a number of trials num_trials. Returns a dictionary that represents an un-normalized distribution. """ # Initialize the distribution dictionary scoring_distribution = dict() for dummy in range(num_trials): # Generate a random permutation of the second sequence list_y = list(seq_y) random.shuffle(list_y) rand_y = ''.join(list_y) # Compute the maximum value score for the local alignment of seq_x and seq_y using the score matrix current_alignment_matrix = project4.compute_alignment_matrix(seq_x, rand_y, scoring_matrix, False) score = project4.compute_local_alignment(seq_x, rand_y, scoring_matrix, current_alignment_matrix)[0] # Add the score to the distribution dictionary if score in scoring_distribution: scoring_distribution[score] += 1 else: scoring_distribution[score] = 1 return scoring_distribution def read_words_list(file_name): """ Helper function to extract the word list from a file. Returns the list. """ words_file = open(file_name, 'r') words_list = list() for word in words_file.readlines(): words_list.append(word.rstrip()) words_file.close() return words_list def check_spelling(checked_word, dist, word_list): """ Iterates through word_list and returns the set of all words that are within edit distance dist of the string checked_word. """ scoring_matrix = project4.build_scoring_matrix('abcdefghijklmnopqrstuvwxyz', 2, 1, 0) within_dist = set() for word in word_list: alignment_matrix = project4.compute_alignment_matrix(checked_word, word, scoring_matrix, True) score = project4.compute_local_alignment(checked_word, word, scoring_matrix, alignment_matrix)[0] edit_distance = len(checked_word)+len(word)-score if edit_distance <= dist: within_dist.add(word) return within_dist # Scoring matrix dictionary ScoringMatrix = read_scoring_matrix(SCORING_MATRIX) # Extract the proteins' data HumanEyeless = read_protein(HUMAN_EYELESS_PROTEIN) FruitflyEyeless = read_protein(FRUITFLY_EYELESS_PROTEIN) def Question1(): """ Function to compute the answer for Question #1. """ # Compute alignment scores alignment_matrix = project4.compute_alignment_matrix(HumanEyeless, FruitflyEyeless, ScoringMatrix, False) # Compute the alignment eyeless_alignment = project4.compute_local_alignment(HumanEyeless, FruitflyEyeless, ScoringMatrix, alignment_matrix) print '### Question 1 ###' print 'Score: ' + str(eyeless_alignment[0]) print eyeless_alignment[1] print eyeless_alignment[2] return eyeless_alignment def Question2(): """ Function to compute the answer for Question #2. """ # Extract the consensus data consensus_pax = read_protein(CONSENSUS_PAX_DOMAIN) # Find the local alignments from Question 1 local_alignments = Question1() human_pax = remove_dashes(local_alignments[1]) fruitfly_pax = remove_dashes(local_alignments[2]) # Compute the global alignments # For human humcon_alignment = project4.compute_alignment_matrix(human_pax, consensus_pax, ScoringMatrix, True) human_global = project4.compute_global_alignment(human_pax, consensus_pax, ScoringMatrix, humcon_alignment) human_percentage = compare_strings(human_global[1], human_global[2]) # For fruitfly flycon_alignment = project4.compute_alignment_matrix(fruitfly_pax, consensus_pax, ScoringMatrix, True) fruitfly_global = project4.compute_global_alignment(fruitfly_pax, consensus_pax, ScoringMatrix, flycon_alignment) fruitfly_percentage = compare_strings(fruitfly_global[1], fruitfly_global[2]) print '### Question 2 ###' print 'Human percentage of agreed elements: ' + str(human_percentage) + '%' print 'Fruit fly percentage of agreed elements: ' + str(fruitfly_percentage) + '%' def Question4(): """ Function to draw the answer for Question #4. """ scoring_distribution = generate_null_distribution(HumanEyeless, FruitflyEyeless, ScoringMatrix, 1000) # Generate the distribution bar plot scores = list() fractions = list() for score, fraction in scoring_distribution.iteritems(): scores.append(score) fractions.append(fraction/1000.0) plot.bar(scores, fractions, color='r') plot.title('Null distribution of randomly generated scores.') plot.xlabel('Score') plot.ylabel('Fraction of trials total') plot.savefig('q4.png') plot.close() print '### Question 4 ###' print 'Null distribution bar plot has been saved as the file q4.png' return scoring_distribution def Question5(): """ Function to compute the answer for Question #5. """ scoring_distribution = Question4() # Compute the mean scores_sum = 0 scores_number = 0 for score, value in scoring_distribution.iteritems(): for dummy in range(value): scores_sum += score scores_number += 1 mean = scores_sum/float(scores_number) print scores_number # Compute the standard deviation sum_of_squared_deviations = 0 for score, value in scoring_distribution.iteritems(): for dummy in range(value): sum_of_squared_deviations += (score - mean)**2 standard_deviation = math.sqrt(sum_of_squared_deviations/float(scores_number)) # Compute the z-value z_value = (875 - mean)/standard_deviation # Print the results print '### Question 5 ###' print 'Mean = ' + str(mean) print 'Standard deviation = ' + str(standard_deviation) print 'Z-value = ' + str(z_value) return (mean, standard_deviation, z_value) def Question8(): """ Function to find the answer for Question #8. """ words_list = read_words_list('assets_scrabble_words3.txt') print '### Question 8 ###' print check_spelling('humble', 1, words_list) print check_spelling('firefly', 2, words_list) # Execution #Question2() #Question5() Question8()
""" Function to draw the graph in_degree distribution plot. created by RinSer """ import matplotlib.pyplot as plot def draw(graph, plot_file, title, xlabel, ylabel, log=True): """ Draws the plot of a given graph. Returns nothing. """ plot.plot(graph.keys(), graph.values(), 'ro') plot.title(title) plot.xlabel(xlabel) plot.ylabel(ylabel) if log: plot.xscale('log') plot.yscale('log') plot.grid(True) plot.savefig(plot_file) plot.close()
# -*- coding: utf-8 -*- from modules import * def main(): clear() recipes = get_recipes() print "RESEPTIT" while True: switch = read_input("Kirjoita '1' jos haluat nähdä listan julkaisun mukaan. Kirjoita '2' niin reseptit listataan kategorian mukaan. Kirjoittamalla 'exit' poistuu päävalikkoon.") if switch == '1' or switch == '2' or switch == 'exit': break else: print "Väärä komento. Yritä uudelleen" if switch == 'exit': return elif switch == '1': if len(recipes) > 0: list_sort_by_created(recipes) else: print "Yhtään reseptiä ei löytynyt" elif switch == '2': if len(recipes) > 0: list_sort_by_category(recipes) else: print "Yhtään reseptiä ei löytynyt" press_to_continue("Palaa takaisin valikkoon painamalla ENTER") def list_sort_by_created(recipes): print "Luetellaan luomisjärjestyksessä" i = 1 for recipe in recipes: print "%s. %s [%s]" %(i, recipe["name"].encode('utf-8'), recipe["category"].encode('utf-8')) i += 1 print "" def list_sort_by_category(recipes): sortedRecipes = {} for recipe in recipes: if recipe["category"] not in sortedRecipes: sortedRecipes[recipe["category"]] = [] sortedRecipes[recipe["category"]].append(recipe) for category in sorted(sortedRecipes): i = 1 print "---%s---" %(category.encode('utf-8')) for recipe in sortedRecipes[category]: print "%s. %s" %(i, recipe["name"].encode('utf-8')) i += 1 print ""
from pprint import pprint from var_dump import var_dump import string class WordNode: characters = 0 def __init__(self): self.character = None self.is_word = False self.count = 0 self.children = {} WordNode.characters += 1 def addWord(self, this_tree, word_list): if type(word_list) is str: word_list = list(word_list) if type(word_list) is list: pass else: return "Word list isn't a list or string" if type(this_tree) is not dict: return "first argument must be a dictionary" word_list = list(word_list) if len(word_list): first_char = word_list.pop(0) else: return this_tree # Is it already at this level? if first_char not in this_tree: # Nope, then this object can grab it this_tree[first_char] = WordNode() this_tree[first_char].character = first_char # Is this the end of the word (list) passed in ? if len(word_list) == 0: this_tree[first_char].is_word = True this_tree[first_char].count += 1 return this_tree else: next_char = word_list[0] if first_char in this_tree: # Pass word list to the node below that matched this_tree[first_char].addWord(this_tree[first_char].children, word_list) else: # Adding the new node new_node = WordNode() this_tree[first_char].children[next_char] = new_node.addWord(this_tree[first_char].children, word_list) return this_tree @staticmethod def isWord(node_tree, word=''): if word: word = list(word) if len(word) == 1: # Word is now one char, we've arrived, but is it a word node? if (word[0] in node_tree) and (node_tree[word[0]].is_word): return node_tree[word[0]] return False if word[0] in node_tree: return WordNode.isWord(node_tree[word[0]].children, word[1:]) return False @staticmethod def cleanString(word = ''): response = '' for c in word: # TODO move excpetions to config # TODO can this be done with a map ? if (c in ["'", '-']) or (c.lower() in string.ascii_lowercase): response += c return response
"""Solution to problem 8 of IEEEXtreme 10.0.""" def safe_divide(a, b): """Do a safe integer division.""" if a % b != 0: return -1 else: return a / b def main(): """Main application logic.""" line = raw_input().split() atoms = [int(line[0]), int(line[1]), int(line[2])] glucose = safe_divide(4 * atoms[0] + atoms[1] - 2 * atoms[2], 24) dioxide = safe_divide(2 * atoms[2] - atoms[1], 4) water = safe_divide(atoms[1] + 2 * atoms[2] - 4 * atoms[0], 4) if glucose < 0 or dioxide < 0 or water < 0: print "Error" else: print "%d %d %d" % (water, dioxide, glucose) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Created on Thu Jan 3 15:02:29 2019 @author: f556085 """ from functools import reduce buzz_fizz = lambda x: "Fizz" * ( x % 3 == 0) + "Buzz" *( x % 2 == 0) or str(x) string_newline_from_list = lambda x,y: x + "\n" + y resultado = reduce(string_newline_from_list, map(buzz_fizz, range(101))) print(resultado)
import math import time import itertools from src.Surface import Surface from shapely import geometry from src.Bucket import Bucket class Road(Surface): """ One of the essential building blocks of the traffic environment. A road has a number of lanes and connects to an intersection on each of its ends. Road supports the tick-tock simulation methods, requesting next locations from vehicles driving on it and handling moving them to their next locations. Road handles transferring vehicles to and from adjacent intersections. """ lane_width = 10 def __init__(self, anchor_corner, length, inbound_lanes, outbound_lanes, orientation, speed_limit): """ :param anchor_corner: [double, double] :param length: double :param inbound_lanes: int :param outbound_lanes: int :param orientatino: double (IN RADIANS!) :param speed_limit: int """ self.anchor = anchor_corner self.length = length self.inbound_lanes = inbound_lanes self.outbound_lanes = outbound_lanes self.lanes = inbound_lanes + outbound_lanes self.width = self.lanes * self.lane_width self.orientation = orientation self.speed_limit = speed_limit self.bucket_length = 0.2778 * self.speed_limit * 10 self.initial_intersection = None self.terminal_intersection = None self.vehicles = [] self.bucket_list = self.initialize_buckets(road_length = self.length, road_width = self.width, bucket_length = self.bucket_length, inbound_lanes = self.inbound_lanes, outbound_lanes = self.outbound_lanes) self.surface = self.generate_surface() self.next_locations = [] # Prevents conflicts with cars being moved onto roads between tick and tock. self.name = None self.reporter = None def tick(self, ticktime_ms): """ Performs the vehicle next location getting tick :param ticktime_ms: :return: """ self.next_locations = self.request_next_locations(ticktime_ms) return def tock_positions(self): """ Performs the vehicle position updating tock :return: """ self.update_positions() return def tock_crashes(self): """ Performs the crash detecting and handling tock, files the timestep report with the reporter :return: """ crashes = self.process_collisions() if self.reporter is not None: number_of_vehicles = len(self.vehicles) if len(self.vehicles) > 0: avg_speed = sum([math.sqrt(v.vx ** 2 + v.vy ** 2) for v in self.vehicles]) / len(self.vehicles) else: avg_speed = "NAN" self.reporter.add_info_road(self.name, number_of_vehicles, avg_speed, crashes) return def initialize_buckets(self, road_length, road_width, bucket_length, inbound_lanes, outbound_lanes): """ Creates a list of buckets of length equal to 10 seconds of travel at the speed limit to populate the length of the road. :param road_length: :param road_width: :param bucket_length: :param inbound_lanes: :param outbound_lanes: :return: """ number_of_buckets = math.ceil(road_length / bucket_length) bucket_list = [] for i in range(number_of_buckets): if i == 0: head = Bucket(initial_x = i * self.bucket_length, length=bucket_length, inbound_lanes=inbound_lanes, outbound_lanes=outbound_lanes) tail = head bucket_list.append(head) else: next = Bucket(initial_x = i * self.bucket_length, length=bucket_length, inbound_lanes=inbound_lanes, outbound_lanes=outbound_lanes) next.set_previous_bucket(tail) tail.set_next_bucket(next) tail = next bucket_list.append(tail) return bucket_list def generate_surface(self): """ Generates the shapely Polygon storing the surface of the road. :return: """ # Points proceed clockwise around the rectangle from the anchor point # [x, y] formatting first = self.anchor second = [first[0] + self.length * math.cos(self.orientation), first[1] + self.length * math.sin(self.orientation)] third = [second[0] + self.width * math.cos(self.orientation + math.pi / 2), second[1] + self.width * math.sin(self.orientation + math.pi / 2)] fourth = [first[0] + self.width * math.cos(self.orientation + math.pi / 2), first[1] + self.width * math.sin(self.orientation + math.pi / 2)] # Reference : https://toblerity.org/shapely/manual.html#polygons return geometry.Polygon([first, second, third, fourth]) def request_next_locations(self, ticktime_ms): """ Produces the next intended location of each car. :param ticktime_ms: :return: """ current_time = time.time()*1000 next_locations = [[vehicle.compute_next_location(ticktime_ms), vehicle] for vehicle in self.vehicles] return next_locations def update_positions(self): # Update the location of each vehicle by updating it directly or transferring it to a neighboring intersection for intended_location, vehicle in self.next_locations: if self.is_local_on_road(intended_location): vehicle.update_location(intended_location[0], intended_location[1]) self.appropriately_bucket(vehicle, intended_location) else: global_location = self.local_to_global_location_conversion(intended_location) self.transfer(vehicle, global_location) # Reset the list of cars intending to move self.next_locations = [] return def is_local_on_road(self, location): """ Takes a local coordinate and returns whether or not it is on the road :param location: :return: """ location = self.local_to_global_location_conversion(location) return self.surface.contains(geometry.Point(location[0], location[1])) def is_global_on_road(self, location): """ Takes a global coordinate and returns whether or not it is on the road :param location: :return: """ return self.surface.contains(geometry.Point(location[0], location[1])) def local_to_global_location_conversion(self, location): """ Turn a local coordinate into its corresponding global coordinate :param location: :return: """ x = self.anchor[0] + location[0] * math.cos(self.orientation) + location[1] * math.cos(self.orientation + math.pi / 2) y = self.anchor[1] + location[0] * math.sin(self.orientation) + location[1] * math.sin(self.orientation + math.pi / 2) return (x, y) def global_to_local_location_conversion(self, location): """ Turn a global coordinate into its corresponding local coordinate :param location: :return: """ # Recenter so that the anchor is the origin relative_x = location[0] - self.anchor[0] relative_y = location[1] - self.anchor[1] # Rotate counterclockwise by the orientation local_x = relative_x * math.cos(-self.orientation) - relative_y * math.sin(-self.orientation) local_y = relative_y * math.cos(-self.orientation) + relative_x * math.sin(-self.orientation) return (local_x, local_y) def which_neighbor(self, location): """ Takes a global coordinate and returns which, if any of the neighboring intersections contain that coordinate :param location: :return: """ if self.initial_intersection.is_global_in_intersection(location): return self.initial_intersection, "initial" elif self.terminal_intersection.is_global_in_intersection(location): return self.terminal_intersection, "terminal" else: raise ValueError("No neighbor contains that location.") return def transfer(self, vehicle, location): """ Takes a vehicle and a global location and attempts to relocate the vehicle to that location :param vehicle: :param location: :return: """ try: # Side is "initial" / "terminal" neighbor, side = self.which_neighbor(location) vehicle.last_road = self vehicle.navlist = vehicle.navlist[1:] if len(vehicle.navlist) > 0: neighbor.accept_transfer(vehicle, location, self, side) self.vehicles.remove(vehicle) except ValueError: print("A vehicle couldn't be transferred because it requested an invalid destination.") self.vehicles.remove(vehicle) return def accept_transfer(self, vehicle, location): """ Takes a vehicle and a global coordinate and places the vehicle onto the road at the local coordinate corresponding to the global coordinate :param vehicle: :param location: :return: """ local_location = self.global_to_local_location_conversion(location) vehicle.transfer_to_road(self, local_location) self.appropriately_bucket(vehicle, local_location) self.vehicles.append(vehicle) return def appropriately_bucket(self, vehicle, location): """ Takes a vehicle and a local location and ensures that the vehicle is in the bucket corresponding to the location :param vehicle: :param location: :return: """ # Remove the vehicle from its current bucket if it exists if vehicle.get_bucket() is not None: vehicle.get_bucket().remove(vehicle) # And place it into the new bucket in which it belongs bucket = self.bucket_list[math.floor(location[0] / self.bucket_length)] bucket.add(vehicle) # And inform the vehicle which bucket it is now in vehicle.set_bucket(bucket) return def process_collisions(self): """ Locates those vehicles which have been in a collision and informs them of that fact. :return: """ count = 0 for bucket in self.bucket_list: preceding = [] if bucket.get_previous_bucket() == None else bucket.get_previous_bucket().get_vehicles() following = [] if bucket.get_next_bucket() == None else bucket.get_next_bucket().get_vehicles() current = bucket.get_vehicles() vehicle_list = preceding + current + following vehicle_pairs = list(itertools.combinations(vehicle_list, 2)) for (v1, v2) in vehicle_pairs: if self.have_collided(v1, v2): count += 1 # I am assuming that vehicles will want to know which vehicle they collided with. v1.collided(v2) v2.collided(v1) # Collided vehicles are simply removed from the road (tow trucks are fast in this universe) if v1 in self.vehicles: self.vehicles.remove(v1) if v2 in self.vehicles: self.vehicles.remove(v2) if v1 in preceding: bucket.get_previous_bucket().remove(v1) elif v1 in following: bucket.get_next_bucket().remove(v1) else: bucket.remove(v1) if v2 in preceding: bucket.get_previous_bucket().remove(v2) elif v2 in following: bucket.get_next_bucket().remove(v2) else: bucket.remove(v2) return count def add_neighboring_intersection(self, intersection, end): """ Takes an intersection and an associated end of the road and adds that intersection at that road. :param intersection: :param end: :return: """ if end == "initial": self.initial_intersection = intersection elif end == "terminal": self.terminal_intersection = intersection else: raise ValueError("Intersection added to an end other than 'initial' or 'terminal'") return def set_name(self, name): self.name = name def get_name(self): return self.name def set_reporter(self, reporter): self.reporter = reporter
def val(n): if (len(n)>=10 and len(n)<32): return True if(n.isupper()): d=True if(n.isdigit()): f=True p=input("enter password:") c=val(p) if(c==True): print("Valid") else: print("Invalid")
lst=[] n=int(input("number of element:")) for i in range(n): i=int(input()) lst.append(i) print(lst) j=int(input("search:")) for i in lst: if(i==j): print("element at",i)
#! usr/bin/env python3 def shuttleSort(array): """ Shuttle sort algorithm Bit like a reverse bubble sort Higher numbers sink to the bottom """ for i in range(1, len(array)): for j in range(i, 0, -1): if array[j-1] > array[j]: temp = array[j-1] array[j-1] = array[j] array[j] = temp return array unsorted = list(range(11)) unsorted.sort(reverse=True) print(unsorted) print(shuttleSort(unsorted))
#! usr/bin/env python3 def bubbleSort(array): """ Bubble sort algorithm: Sum of n-1 where n = list. Max number of swaps per pass == n-1 """ for i in range(0, len(array)-1): for j in range(0, len(array)-i): if array[j+1] > array[j]: temp = array[j+1] array[j+1] = array[j] array[j+1] = temp return array unsorted = list(range(11)) unsorted.sort(reverse=True) print(unsorted) print(bubbleSort(unsorted))
#!/usr/bin/env python # -*- coding: utf-8 -*- # punkcja zachowujaca sie jak print w python3.x from __future__ import print_function from sys import maxsize from Graph import Graph # rysowanie minimalnego drzewa rozpinającego import networkx as nx import matplotlib.pyplot as plt # algorytm dijkstry, jako argument przyjmuje graf oraz nr wierzchołka stanowiącego źródło # zwraca słownik, w którym kluczem są wierzchołḱi a wartościami ich odległości od źródła # wypisuje ścieżki pomiędzy danym wierzchołkiem a źródłem def dijkstra(graph, source): prevs={i:None for i in range(graph.vertex)} dist = {i:maxsize for i in range(graph.vertex)} dist[source] = 0 S=[] Q=[i for i in range(graph.vertex)] while bool(Q): u = extractMin(Q,dist) S.append(u) for v in graph.AL[u]: if dist[v]>(dist[u]+graph.EV[u][v]): dist[v] = dist[u]+graph.EV[u][v] prevs[v] = u print("\nScieżki pomiędzy poszczególnymi wierzchołkami dla źródła",source,":") for i in range(graph.vertex): if(i==source): continue w=i print("from",i , "to", source, end=":\n") print(i, end=" ") while prevs[w]!=None: w=prevs[w] print("->", w, end=" ") print() return dist def extractMin(Q, dist): i=Q[0] for v in Q: if dist[v]<dist[i]: i=v Q.remove(i) return i # algorytm konstruujący macierz odległości między wierzchołakami def distMatrix(graph): dijkstraLists = [dijkstra(graph, i) for i in range(graph.vertex)] matrix = [[dijkstraLists[i][j] for j in range(graph.vertex)] for i in range(graph.vertex)] return matrix # algorytm wypisujący centrum grafu def centrum(matrix): l=sum(matrix[0]) m=0 for i in range(len(matrix)-1): s=sum(matrix[i+1]) if s<l: l=s m=i+1 print("Centrum tego grafu to wierzchołek ", m) # algorytm wypisujący centrum mini-max grafu def minimax(matrix): l=max(matrix[0]) m=0 for i in range(len(matrix)-1): s=max(matrix[i+1]) if s<l: l=s m=i+1 print("Centrum mini-max tego grafu to wierzchołek ", m) # algorytm prima class PriorityQueue: def __init__(self, vertex): self.d = {i:20 for i in range(vertex)} def pop(self): minimum = min(self.d.values()) u=0 for i in self.d: if self.d[i]==minimum: u=i break self.d.pop(u) return u def empty(self): return self.d class Prim: def __init__(self, graph, r): self.r = r self.graph = graph q = PriorityQueue(graph.vertex) q.d[r] = 0 self.pre = [None for i in range(graph.vertex)] while q.empty(): u = q.pop() for v in graph.AL[u]: if v in q.d and graph.EV[u][v] < q.d[v]: self.pre[v] = u q.d[v] = graph.EV[u][v] def draw(self): g = nx.Graph() for i in range(1, len(self.pre)): j = self.pre[i] g.add_edge(i, j, w=self.graph.EV[i][j]) pos = nx.shell_layout(g) nx.draw_networkx_nodes(g, pos, node_size=300) nx.draw_networkx_edges(g, pos) nx.draw_networkx_labels(g, pos) nx.draw_networkx_edge_labels(g, pos) plt.axis('off') plt.savefig("Prim.png") plt.close()
#Describe how you could use a single array to implement three stacks #first stack would be from 0 to n/3-1 #second stack would be from n/3 to 2*n/3-1 #third stack would be from 2*n/3 to n-1 #0 1 2 3 4 5 6 class Node(): data = 0 next = None def __init__(self,data): self.data = data self.next = None class Stack(): top = Node(0) def __init__(self,top): self.top.data = top self.top.next = None def push(self,top): t = Node(top) t.next = self.top self.top = t def pop(self): if self.top != None : #delete the top the_data = self.top.data self.top = self.top.next #return the top data return the_data else : return None array = [4,5,6,7,21,231,43,6] n = len(array) i = 1 s1 = Stack(array[0]) #first stack while i <= n//3: s1.push(array[i]) i+=1 s2 = Stack(array[i]) while i <= 2*n//3: s2.push(array[i]) i+=1 s3 = Stack(array[i]) while i < n: s3.push(array[i]) i+=1
#fresher class Fresher(): canHandleCall = True #technical lead class TL(): canHandleCall = True #project manager class PM(): canHandleCall = True class Employees(): freshers = [] def __init__(self,fresher,tl,pm): self.freshers.append(fresher) self.tl = tl self.pm = pm def addFresher(self,fresh): self.freshers.append(fresh) def getCallHandler(self): i = 0 for fresher in self.freshers: if fresher.canHandleCall == True: print("The call was handled by fresher #"+str(i)) fresher.canHandleCall = False return i+=1 if self.tl.canHandleCall == True: print("The call was handled by techlead ") self.tl.canHandleCall = False return if self.pm.canHandleCall == True: print("The call was handled by project manager ") self.pm.canHandleCall = False return
class Pawn(): line = 0 column = 0 team = "" def __init__(self , line , column , team): self.line = line self.column = column self.team = team #white or black #return a list of possible points where the pawn can move #on the given board def GetPossibleMoves(self , board): possible_moves = [] piece = board[self.line][self.column]
#P = float(input(P) #n = 1 #r = .0821 #T = float(input(T) from scipy.constants import convert_temperature from pint import UnitRegistry ureg = UnitRegistry() print("Unit Converter") print() # pressure = [] # volume = [] # n = 1 # T = [] def CalculateVolume(P, n, T): R = 0.0821 n = 1 V = (n*R*T)/P return V temp = str(input('Enter Temperature with a space and unit (C,F,K): ').upper()) if temp[-1] == 'F': temp = int(temp[:-1]) T = convert_temperature(temp, 'Fahrenheit', 'Kelvin') # print(T) elif temp[-1] == 'C': temp = int(temp[:-1]) T = convert_temperature(temp, 'Celsius', 'Kelvin') # print(T) elif (temp[-1] == 'K' or len(temp.split(' ')) == 1): if len(temp.split(' ')) == 1: T = int(temp) # print(T) else: T = int(temp[:-1]) # print(T) pressure = str(input('Enter Pressure with a space and unit (ATM, inHG, PSI): ').upper()) if pressure.split()[1] == 'PSI': pressure = int(pressure[:-3]) P = pressure * ureg.psi # print(P.to(ureg.atm)) P.to(ureg.atm) elif pressure.split()[1] == 'INHG': pressure = int(pressure[:-4]) #split removes unit by designating position in input -4 indicates position P = pressure * ureg.inHg #print(P.to(ureg.atm)) P.to(ureg.atm) elif pressure.split()[1] == 'ATM': pressure = int(pressure[:-3]) P = pressure else: print('Enter a valid temperature and unit!') V = (1*0.0821*T)/P # print() print(f'Volume is {V:.2f} in Liters')
# https://courses.edx.org/courses/course-v1:MITx+6.00.1x_6+2T2015/courseware/sp13_Week_3/videosequence:Lecture_5/ def recurPowerNew(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float; base^exp ''' if exp == 0: return 1 elif exp % 2 ==0: return recurPowerNew((base*base),(exp/2)) else: return base * recurPowerNew(base, exp-1)
# Assume s is a string of lower case characters. # Write a program that prints the longest substring of s in which the letters occur in alphabetical order. # For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh # In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print # Longest substring in alphabetical order is: abc # For problems such as these, do not include raw_input statements or define the variable s in any way. # Our automated testing will provide a value of s for you - so the code you submit in the following box # should assume s is already defined. If you are confused by this instruction, please review L4 Problems 10 and 11 # before you begin this problem set. alpha = 'abcdefghijklmnopqrstuvwxyz' ## track the length of the longest alphabetic order substring ## starting from each letter in s ind = [] for i in range(len(s)): length = 1 while True: if i == len(s) - 1: break elif alpha.find(s[i]) <= alpha.find(s[i+1]): length += 1 i += 1 else: break ind.append(length) t=[] ## t is an empty list, it will contain all the substrings in alphabetic order for start, length in enumerate(ind): t.append(s[start:start + length]) print max(t, key = len)
方法一:递归 我们可以对这两棵树同时进行前序遍历,并将对应的节点进行合并。在遍历时,如果两棵树的当前节点均不为空,我们就将它们的值进行相加,并对它们的左孩子和右孩子进行递归合并;如果其中有一棵树为空,那么我们返回另一颗树作为结果;如果两棵树均为空,此时返回任意一棵树均可(因为都是空)。 class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if t2==None: return t1 if t1==None: return t2 t1.val += t2.val t1.left = self.mergeTrees(t1.left,t2.left) t1.right = self.mergeTrees(t1.right,t2.right) return t1 时间复杂度:O(N),其中 N 是两棵树中节点个数的较小值。 空间复杂度:O(N),在最坏情况下,会递归 N 层,需要 O(N) 的栈空间。 方法二:迭代 我们首先把两棵树的根节点入栈,栈中的每个元素都会存放两个根节点,并且栈顶的元素表示当前需要处理的节点。在迭代的每一步中,我们取出栈顶的元素并把它移出栈,并将它们的值相加。随后我们分别考虑这两个节点的左孩子和右孩子,如果两个节点都有左孩子,那么就将左孩子入栈;如果只有一个节点有左孩子,那么将其作为第一个节点的左孩子;如果都没有左孩子,那么不用做任何事情。对于右孩子同理。 class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if t2==None: return t1 if t1==None: return t2 stack = [(t1,t2)] while stack: t = stack.pop(0) if t[1]==None: continue t[0].val += t[1].val if(t[0].left==None): t[0].left = t[1].left else: stack.append((t[0].left,t[1].left)) if(t[0].right==None): t[0].right = t[1].right else: stack.append((t[0].right,t[1].right)) return t1 时间复杂度:O(N),其中 N 是两棵树中节点个数的较小值。 空间复杂度:O(N),在最坏情况下,栈中会存放 N 个节点。
class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: max_ = 0 for trip in trips: max_ = max(trip[2],max_) line = [0]*max_ for trip in trips: for i in range(trip[1],trip[2]): line[i] += trip[0] for l in line: if l>capacity: return False return True 方法二:(更快) class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: travel = [] for i in trips: travel.append([i[1], i[0]]) travel.append([i[2], -i[0]]) travel.sort(key = lambda x:(x[0], x[1])) #注意先下后上 people_in_car = 0 for i in travel: people_in_car += i[1] if people_in_car > capacity: return False return True
"""gffpandas depends on the following libraries: pandas (pd), itertools and defaultdict from collections.""" import pandas as pd import itertools from collections import defaultdict def read_gff3(input_file): return Gff3DataFrame(input_file) class Gff3DataFrame(object): """Creating 'Gff3DataFrame' class for bundling data and functionalities together.""" def __init__(self, input_gff_file=None, input_df=None, input_header=None): """Create an instance.""" if input_gff_file is not None: self._gff_file = input_gff_file self._read_gff3_to_df() self._read_gff_header() else: self._df = input_df self._header = input_header def _read_gff3_to_df(self): """ Create a pd dataframe. By the pandas library the gff3 file is read and a pd dataframe with the given column-names is returned """ self._df = pd.read_table(self._gff_file, comment='#', names=["seq_id", "source", "type", "start", "end", "score", "strand", "phase", "attributes"]) return self._df def _read_gff_header(self): """ Create a header. The header of the gff file is read, means all lines, which start with '#'. """ self._header = '' for line in open(self._gff_file): if line.startswith('#'): self._header += line else: break return self._header def write_csv(self, csv_file): """ Create a csv_file. The pd dataframe is safed as a csv_file. """ self._df.to_csv(csv_file, sep=',', index=False, header=["seq_id", "source", "type", "start", "end", "score", "strand", "phase", "attributes"]) def write_tsv(self, tsv_file): """ Create a tsv_file. The pd dataframe is safed as a tsv_file. """ self._df.to_csv(tsv_file, sep='\t', index=False, header=["seq_id", "source", "type", "start", "end", "score", "strand", "phase", "attributes"]) def filter_feature_of_type(self, feature_type): """ Filtering the pd dataframe by a feature_type. For this method a feature-type has to be given, as e.x. 'CDS'. """ feature_df = self._df feature_df = feature_df[feature_df.type == feature_type] return Gff3DataFrame(input_df=feature_df, input_header=self._header) def filter_by_length(self, min_length: int, max_length: int): """ Filtering the pd dataframe by the gene_length. For this method the desired minimal and maximal bp length have to be given. """ filtered_length = self._df gene_length = pd.Series(filtered_length.apply(lambda row: row.end - row.start, axis=1)) filtered_length = filtered_length[(gene_length >= min_length) & (gene_length <= max_length)] return Gff3DataFrame(input_df=filtered_length, input_header=self._header) def get_feature_by_attribute(self, attr_tag, attr_value): """ Filtering the pd dataframe by a attribute. The 9th column of a gff3-file contains the list of feature attributes in a tag=value format. For this mmethod the desired attribute tag as well as the corresponding value have to be given. If the value is not available an empty dataframe would be returned.""" attribute_df = self._df.copy() attribute_df['at_dic'] = attribute_df.attributes.apply( lambda attributes: dict([key_value_pair.split('=') for key_value_pair in attributes.split(';')])) attribute_df['at_dic_keys'] = attribute_df['at_dic'].apply( lambda at_dic: list(at_dic.keys())) merged_attribute_list = list(itertools.chain. from_iterable(attribute_df ['at_dic_keys'])) nonredundant_list = sorted(list(set(merged_attribute_list))) for atr in nonredundant_list: attribute_df[atr] = attribute_df['at_dic'].apply(lambda at_dic: at_dic.get(atr)) filtered_by_attr_df = self._df[(attribute_df[attr_tag] == attr_value)] return Gff3DataFrame(input_df=filtered_by_attr_df, input_header=self._header) def attributes_to_columns(self): """ Safing each attribute-tag to a single column. Attribute column will be split to 14 single columns.""" attribute_df = self._df df_attributes = attribute_df.loc[:, 'seq_id':'attributes'] attribute_df['at_dic'] = attribute_df.attributes.apply( lambda attributes: dict([key_value_pair.split('=') for key_value_pair in attributes.split(';')])) attribute_df['at_dic_keys'] = attribute_df['at_dic'].apply( lambda at_dic: list(at_dic.keys())) merged_attribute_list = list(itertools.chain. from_iterable(attribute_df ['at_dic_keys'])) nonredundant_list = sorted(list(set(merged_attribute_list))) for atr in nonredundant_list: df_attributes[atr] = attribute_df['at_dic'].apply(lambda at_dic: at_dic.get(atr)) return Gff3DataFrame(input_df=df_attributes, input_header=self._header) def stats_dic(self) -> dict: """ Gives the following statistics for the data: The maximal bp-length, minimal bp-length, the count of sense (+) and antisense (-) strands as well as the count of each available feature. """ input_df = self._df df_w_region = input_df[input_df.type != 'region'] gene_length = pd.Series(df_w_region.apply(lambda row: row.end - row.start, axis=1)) strand_counts = defaultdict(int) for key in input_df['strand']: strand_counts[key] += 1 feature_type_counts = defaultdict(int) for key in input_df['type']: feature_type_counts[key] += 1 stats_dic = { 'Maximal_bp_length': gene_length.max(), 'Minimal_bp_length': gene_length.min(), 'Counted_strands': strand_counts, 'Counted_feature_types': feature_type_counts } return Gff3DataFrame(input_df=stats_dic, input_header=self._header) def overlaps_with(self, seq_id=None, start=None, end=None, type=None, strand=None, complement=False): """ To see which entries overlap with a to comparable feature. For this method the chromosom accession number has to be given. The start and end bp position for the to comparable feature have to be given, as well as optional the feature-type of it and if it is on the sense (+) or antisense (-) strand. By selecting 'complement=True', all the feature, which do not overlap with the to comparable feature will be returned. This is usefull for finding features which are outside of the given genome region. Therefore, the bp position of the genome region have to be given. """ overlap_df = self._df overlap_df = overlap_df[overlap_df.seq_id == seq_id] if type is not None: overlap_df = overlap_df[overlap_df.type == type] if strand is not None: overlap_df = overlap_df[overlap_df.strand == strand] if not complement: overlap_df = overlap_df[((overlap_df.start > start) & (overlap_df.start < end)) | ((overlap_df.end > start) & (overlap_df.end < end)) | ((overlap_df.start < start) & (overlap_df.end > start)) | ((overlap_df.start == start) & (overlap_df.end == end)) | ((overlap_df.start == start) & (overlap_df.end > end)) | ((overlap_df.start < start) & (overlap_df.end == end))] else: overlap_df = overlap_df[~(((overlap_df.start > start) & (overlap_df.start < end)) | ((overlap_df.end > start) & (overlap_df.end < end)) | ((overlap_df.start < start) & (overlap_df.end > start)) | ((overlap_df.start == start) & (overlap_df.end == end)) | ((overlap_df.start == start) & (overlap_df.end > end)) | ((overlap_df.start < start) & (overlap_df.end == end)))] return Gff3DataFrame(input_df=overlap_df, input_header=self._header) def find_redundant_entries(self, seq_id=None, type=None): """ Find entries which are redundant. For this method the chromosom accession number (seq_id) as well as the feature-type have to be given. Then all entries which are redundant according to start- and end-position as well as strand-type will be found.""" input_df = self._df input_df = input_df[input_df.seq_id == seq_id] df_gene = input_df[input_df.type == type] if (df_gene[['end', 'start', 'strand']].duplicated().sum() == 0): print('No redundant entries found') else: duplicate = df_gene.loc[df_gene[['end', 'start', 'strand']].duplicated()] return Gff3DataFrame(input_df=duplicate, input_header=self._header) # test_object = read_gff3('NC_016810B.gff') # data_frame_new = test_object.attributes_to_columns() # print(data_frame_new._df) # print(__doc__) # print(Gff3DataFrame.__doc__) # print(Gff3DataFrame._read_gff_header.__doc__)
from employees import * import os class EmployeesManager: def __init__(self): self.employees_list = [] def run(self): self.load_employees() # 1ԱϢ while True: # 2ʾܲ˵ self.show_menu() # 3û빦 try: menu_num = int(input('ҪĹţ')) except: print('1-7ţ') continue # 4ûĹִвͬĹ if menu_num == 1: self.add_employees() # û1Ա elif menu_num == 2: self.del_employees() # û2ɾԱ elif menu_num == 3: self.modify_employees() # û3޸Ա elif menu_num == 4: self.search_employees() # û4ѯԱ elif menu_num == 5: self.show_employees() # û5ʾԱϢ elif menu_num == 6: self.save_employees() # û6ԱϢעǰɾIJDzлļ elif menu_num == 7: break # û7˳ else: print('1-7ţ') @staticmethod def show_menu(): print('ѡ¹ܶӦ-------------') print('1:Ա') print('2:ɾԱ') print('3:޸ԱϢ') print('4:ѯԱϢ') print('5:ʾԱϢ') print('6:ԱϢ') print('7:˳ϵͳ') def add_employees(self): name = input('Name:') gender = input('Gender: ') tel = input('Tel: ') self.employees_list.append(Employees(name, gender, tel)) print(Employees(name, gender, tel)) def del_employees(self): flag = False del_name = input('Name:') for i in range(len(self.employees_list)): if self.employees_list[i].name == del_name: del self.employees_list[i] print("ɾɹ") flag = True break if not flag: print("޴") def modify_employees(self): flag = False modify_name = input('Name: ') for i in range(len(self.employees_list)): if self.employees_list[i].name == modify_name: new_gender = input('Gender: ') new_tel = input('Tel: ') del self.employees_list[i] self.employees_list.append(Employees(modify_name, new_gender, new_tel)) print("{}Ա{}绰{}".format(modify_name, new_gender, new_tel)) flag = True if not flag: print("޴") def search_employees(self): flag = False search_name = input('Name: ') for i in range(len(self.employees_list)): if self.employees_list[i].name == search_name: print(self.employees_list[i]) flag = True if not flag: print("޴") def show_employees(self): for i in range(len(self.employees_list)): print(self.employees_list[i]) def save_employees(self): new_list = [] for i in range(len(self.employees_list)): new_list.append(self.employees_list[i].name) new_list.append(self.employees_list[i].gender) new_list.append(self.employees_list[i].tel) with open(r'employees.data', 'w', encoding='utf8') as write: write.write('{}'.format(','.join(new_list))) print('ɹ') def load_employees(self): new_list = [] if os.path.exists('employees.data'): with open(r'employees.data', 'r+', encoding='utf8') as read: data = read.read() for i in data.split(','): new_list.append(i) if len(new_list) > 1: for i in range(len(new_list)): if i % 3 == 0: self.employees_list.append(Employees(new_list[i], new_list[i + 1], new_list[i + 2])) else: with open(r'employees.data', 'w', encoding='utf8') as W: pass
if 5 > 4: print("helloworld!") else: print("no Hello :(") my_array = ["vamsi", "sai", "rama", "krishna"] if "vamsi" in my_array: print("vamsi listed in array!") for name in my_array: print("my name is {0}").format(name) start = 10 end = 20 inc = 2 for index in range(start, end, inc): print("my index is {0}".format(index))
'''some helpful tools for processing the natural languages''' import nltk def avg_word_length(corpus, punctuation=True): '''Calculate the average word length in a corpus or corpus subset. Used to answer question 1 and 2 particularly''' try: #First try treating the corpus as a word list word_lengths = [ len(word) for word in set(v.lower() for v in corpus if punctuation or v.isalnum()) ] except TypeError: try: #We need a third level of recursion if we're actually #passed a corpus word_lengths = [ len(word) for word in set(v.lower() for file in corpus.fileids() for v in corpus.words(file) if punctuation or v.isalnum()) ] except TypeError: print 'Please use a corpus or a list of words' raise return sum(word_lengths) * 1.0 / len(word_lengths) #Question 4, 5, 7 solution def word_freq(corpus, punctuation=True): #If the corpus is a list of words, access it directly. Otherwise try to #treat it like an nltk corpus. try: freq_dist = nltk.FreqDist(word.lower() for word in corpus if punctuation or word.isalnum()) except TypeError: freq_dist = nltk.FreqDist(word.lower() for file in corpus.fileids() for word in corpus.words(file) if punctuation or word.isalnum()) return freq_dist #Used for question 8 def avg_token_length(corpus, punctuation=True): #If the corpus is a list of words, access it directly. Otherwise #try to treat it like an nltk corpus. try: word_lengths = [len(word) for word in corpus if punctuation or word.isalnum()] except TypeError: #Might be a corpus. Let's give that a shot try: word_lengths = [ len(word.lower()) for file in corpus.fileids() for word in corpus.words(file) if punctuation or word.isalnum() ] except TypeError: print 'corpus needs to be an nltk corpus or a list of words' raise return sum(word_lengths) * 1.0 / len(word_lengths) #Used in question 9 def num_word_types_for_speech(speech_name, punctuation=True): word_types = set(v.lower() for v in inaugural.words(speech_name) if (punctuation or v.isalnum()) and v not in stops) return len(word_types) #Used in question 10 and 11 def rank(fd, sample): ''' Given a sample and a nltk FreqDist, compute the sample's ranking in the FreqDist based on the number of times that sample occurs :param fd: nltk.FreqDist used to rank the sample :type fd: nltk.FreqDist :param sample: The sample whose rank is to be determined :type sample: token occuring in fd (string) ''' #Get the number of times our sample appears in the FreqDist c = fd[sample] #Sum over counts of all samples that occured more than c times #(If our sample were the only sample that occured c times, our rank #would be p + 1) p = sum(fd.Nr(r) for r in range(c+1, fd[fd.max()] + 1)) #Calculate the average number of samples that occur #c times((n + 1) / 2) #Then calculate the shared rank by adding that to p return p + ((fd.Nr(c) + 1) / 2.0)
print(4*5) print(5*4.2) print(20.1/4) # float divided by int gives a float print(20/3) # int divided by int can result in a float print(2**2/4-3) # multiple mathetimatical operators appears to follow PEDMAS print('hello'*2) #produces hello twice print('hey'+'dude')
# 第12章のチャレンジ # http://tinyurl.com/gpqe62e # 'りんご'から思い浮かぶ4つの属性を考え,インスタンス変数に持たせて,Appleクラスを定義するプログラム # 名前,重さ,色,腐る性質をインスタンス変数に持たせる class Apple: def __init__(self, n, w, c): self.name = n self.weight = w self.color = c self.mold = 0 def rot(self, days, temp): self.mold = days * temp def sweetness(self): return 100 / self.weight # どうやら,変数の型はこの処理で決まるようだ ap1 = Apple("Orin", 50, "red") print(ap1.name) print(ap1.weight) print(ap1.color) # 関数的な使い方だね ap1.rot(14, 3) print(ap1.mold) print(ap1.sweetness()) # 円を表すクラスに,面積を計算して返すメソッドを持たせ,結果を出力するプログラム import math class Circle: def __init__(self, r): self.radius = r def area(self): return math.pi * self.radius * self.radius circle = Circle(5) print(circle.area()) # 三角形の面積を返すプログラム class Triangle: def __init__(self, b, h): self.bottom = b self.height = h def area(self): return self.bottom * self.height / 2 def change_size(self, b, h): self.bottom = b self.height = h triangle = Triangle(7, 4) print(triangle.area()) triangle.change_size(10, 5) print(triangle.area()) # 六角形を表すクラスを定義し,外周の長さを計算して返すメソッドを呼び出し,結果を出力するプログラム class Hexagon: def __init__(self, s1, s2, s3, s4, s5, s6): self.side1 = s1 self.side2 = s2 self.side3 = s3 self.side4 = s4 self.side5 = s5 self.side6 = s6 def calculate_perimeter(self): return self.side1 + self.side2 + self.side3 + self.side4 + self.side5 + self.side6 hexagon = Hexagon(1, 2, 3, 4, 5, 6) print(hexagon.calculate_perimeter())
# 第3章のチャレンジ # http://tinyurl.com/zx7o2v9 print('ジオブレイク70S', 'ジオブレイク80S', 'Fレーザー7S') x = 7 if x < 10: print('伸びしろですね') elif 10 <= x <= 25: print('もっとできるはずさ') else: print('慢心ではなく自信を持て!') print(2020 % 825) print(2020 // 825) barth_year = 2000 age = 2020 - barth_year if age >= 20: print('もうお酒が飲めるのだ') else: print('まだおこちゃまでしょ?')
#!/usr/bin/env python class Animal(object): pass class Dog(Animal): def talk(self): return "whoof whoof" class Cat(Animal): def talk(self): return "miao" class Pig(Animal): def talk(self): return "oink oink" def all_animals(): return Animal.__subclasses__() if __name__ == "__main__": for animal in all_animals(): print "%s says: %s" % (animal.__name__, animal().talk())
#!/usr/bin/env python # encoding: utf-8 '''Calculate distance of path in .kmz file in Km''' from collections import namedtuple from math import sqrt, sin, cos, atan2, radians from zipfile import ZipFile, BadZipfile import xml.etree.ElementTree as et namespaces = {'gx': 'http://www.google.com/kml/ext/2.2'} Coord = namedtuple('Coord', ['lat', 'lng']) R = 6371 # Earth radius in km def elem2coord(elem): # '35.014666 32.519769 144.1999969482422' -> (35.014666, 32.519769) lat, lng, _ = [float(v) for v in elem.text.split()] return Coord(lat, lng) def sin2(x): '''sin²(x/2)''' v = sin(x/2.) return v * v def dist(coord1, coord2): '''Distance between two coordinates This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is, the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points (ignoring any hills they fly over, of course!). Haversine formula: a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2) c = 2 ⋅ atan2( √a, √(1−a) ) d = R ⋅ c where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km); via http://www.movable-type.co.uk/scripts/latlong.html ''' lat1, lng1 = radians(coord1.lat), radians(coord1.lng) lat2, lng2 = radians(coord2.lat), radians(coord2.lng) a = sin2(abs(lat2 - lat1)) + cos(lat1) * cos(lat2) * sin2(abs(lng2 - lng1)) c = 2 * atan2(sqrt(a), sqrt(1-a)) return R * c def kmz_dist(file): '''Calculate distance of all points in .kmz file in Km file can be either a file name or an open file object. ''' zfo = ZipFile(file) fo = zfo.open(zfo.filelist[0].filename) root = et.parse(fo).getroot() elems = root.iterfind('.//gx:coord', namespaces=namespaces) coords = [elem2coord(elem) for elem in elems] # Shift the coords list and then zip with itself, we'll get a list of # tuples like [(coord1, coord2), (coord2, coord3) ...] return sum(dist(c1, c2) for c1, c2 in zip(coords, coords[1:])) if __name__ == '__main__': from argparse import ArgumentParser from sys import stdin parser = ArgumentParser(description=__doc__) parser.add_argument('kmz', help='kmz file name', default='-', nargs='?') args = parser.parse_args() file = stdin if args.kmz == '-' else args.kmz try: print('{:.3f}km'.format(kmz_dist(file))) except (IOError, BadZipfile) as err: raise SystemExit('error: {}'.format(err))
#!/usr/bin/env python ''' Solving http://projecteuler.net/index.php?section=problems&id=24 Note that Python's 2.6 itertools.permutations return the permutation in order so we can just write: from itertools import islice, permutations print islice(permutations(range(10)), 999999, None).next() And it'll work much faster :) ''' from itertools import islice, ifilter def is_last_permutation(n): return n == sorted(n, reverse=1) def next_head(n): '''Find next number to be 'head'. It is smallest number if the tail that is bigger than the head. In the case of (2 4 3 1) it will pick 3 to get the next permutation of (3 1 2 4) ''' return sorted(filter(lambda i: i > n[0], n[1:]))[0] def remove(element, items): return filter(lambda i: i != element, items) def next_permutation(n): if is_last_permutation(n): return None sub = next_permutation(n[1:]) if sub: return [n[0]] + sub head = next_head(n) return [head] + sorted([n[0]] + remove(head, n[1:])) def nth(it, n): '''Return the n'th element of an iterator''' return islice(it, n, None).next() def iterate(func, n): '''iterate(func, n) -> n, func(n), func(func(n)) ...''' while 1: yield n n = func(n) def permutations(n): return ifilter(None, iterate(next_permutation, n)) if __name__ == "__main__": n = range(10) m = 1000000 print "Calculateing the %d permutation of %s" % (m, n) print nth(permutations(n), m-1)
#!/usr/bin/env python3 ''' 字段:学生姓名 班级 Linux PHP Python stu1 = {'id':1,'sname':'tom','bj':'1','Linux':100,} ''' stu_info = [] id = 0 def menu(): print(''' | ----------学生成绩系统--------| | | | ==========主功能菜单==========| | | | | | 1.录入学生成绩 | | 2.查询学生成绩 | | 3.删除学生的成绩 | | 4.修改学生的成绩 | | 5.展示所有学生成绩 | | 0.退出系统 | | | |-------------------------------| ''') #录入学生成绩 def add_info(): while True: sname = input('输入学生的姓名:') if not sname: print('学生姓名不能为空') continue bj = input('输入学生的班级:') Linux = input('输入Linux成绩:') PHP = input('输入PHP成绩:') Python = input('输入Python成绩:') global id id += 1 stu = {'id':id,'sname':sname,'bj':bj,'Linux':Linux,'PHP':PHP,'Python':Python} stu_info.append(stu) print(stu_info) key = input('是否继续录入y/n?') if key == 'y': continue else: break #显示所有学生的成绩 def show(): ''' 遍历列表,获取到每个学生的信息 ''' format_title = '{:^6}{:^12}\t{:^12}{:^12}{:^12}{:^12}' format_data = '{:^6}{:^13}\t{:^15}{:^13}{:^15}{:^14}' print(format_title.format('ID','姓名','班级','Linux成绩','PHP成绩','Python成绩')) for i in stu_info: id = i.get('id') sname = i.get('sname') bj = i.get('bj') Linux = i.get('Linux') PHP = i.get('PHP') Python = i.get('Python') print(format_data.format(id,sname,bj,Linux,PHP,Python)) def search(): ''' 根据名字查询学生的成绩 ''' format_title = '{:^6}{:^12}\t{:^12}{:^12}{:^12}{:^12}' format_data = '{:^6}{:^13}\t{:^15}{:^13}{:^15}{:^14}' sname = input('输入要查询学生的姓名:') print(format_title.format('ID','姓名','班级','Linux成绩','PHP成绩','Python成绩')) #提取到所有学生的名字 name_list = [stu_info[i].get('sname') for i in range(len(stu_info))] if sname in name_list: for i in stu_info: if sname == i.get('sname'): id = i.get('id') sname = i.get('sanme') bj = i.get('bj') Linux = i.get('Linux') PHP = i.get('PHP') Python = i.get('Python') print(id,sname,bj,Linux,PHP,Python) else: print('学生名字不存在') def delete(): global id sname = input('请输入要删除学生得名字:') if stu_info: for i in stu_info: if i['sname'] == sname: stu_info.remove(i) #删除该字段 print('删除成功') #修改剩下学生的id id - 1 #for i,v in enumerate(stu_info): for i in range(len(stu_info)): id = i + 1 stu_info[i]['id'] = id if not stu_info: id = 0 show() #修改学生信息,只修改学生的成绩 def modify(): sname = input('请输入学生名字:') global stu_info for i in stu_info: if i['sname'] == sname: id = i.get('id') stuid = id - 1 sname = i.get('sname') bj = i.get('bj') stuNum = i.get('stuNum') newLinux = input('请输入学生linux成绩:') newPHP = input('请输入学生php成绩:') newPython = input('请输入学生python成绩:') # 将获取到的用户输入的新成绩全部赋值到新的字典 newStudent = {"id":id,"sname":sname,"bj":bj,'stuNum':stuNum,'Linux':newLinux,'PHP':newPHP,'Python':newPython} stu_info[stuid].update(newStudent) # 将新字典更新到列表同位置下标下 else: print('学生不存在') def main(): while True: menu() key = input('请选择功能:') if key == '1': add_info() if key == '2': search() if key == '3': delete() if key == '4': modify() if key == '5': show() if key == '0': break main()
""" RNA Alignment Assignment Implement each of the functions below using the algorithms covered in class. You can construct additional functions and data structures but you should not change the functions' APIs. You will be graded on the helper function implementations as well as the RNA alignment, although you do not have to use your helper function. *** Make sure to comment out any print statement so as not to interfere with the grading script """ import sys # DO NOT EDIT THIS from shared import * from itertools import product from math import log ALPHABET = [TERMINATOR] + BASES RADIX = 100 def get_suffix_array(s): """ Naive implementation of suffix array generation (0-indexed). You do not have to implement the KS Algorithm. Make this code fast enough so you have enough time in Aligner.__init__ (see bottom). Input: s: a string of the alphabet ['A', 'C', 'G', 'T'] already terminated by a unique delimiter '$' Output: list of indices representing the suffix array >>> get_suffix_array('GATAGACA$') [8, 7, 5, 3, 1, 6, 4, 0, 2] """ sorted_suffixes = sort_suffixes(s, [(s[i:i+RADIX], i) for i in range(len(s))]) sa = [pair[1] for pair in sorted_suffixes] return sa def sort_suffixes(s, suffixes, ranks=None): if ranks is None: ranks = {} sorted_suffixes = sorted(suffixes, key=lambda x: x[0]) else: sorted_suffixes = sorted(suffixes, key=lambda x: ranks[x]) conflicts = {} bucket = [] rank = 0 curr_su = None for i in range(len(sorted_suffixes)): su, idx = sorted_suffixes[i] if su != curr_su: if len(bucket) > 1: conflicts[rank-1] = bucket bucket = [] rank = i + 1 curr_su = su ranks[(su, idx)] = rank bucket.append((su, idx)) if len(bucket) > 1: conflicts[rank - 1] = bucket resolve_conflicts(s, sorted_suffixes, conflicts, ranks) return sorted_suffixes def resolve_conflicts(s, sorted_suffixes, conflicts, ranks): for i, c in conflicts.items(): resolved = [(s[idx-RADIX:idx], idx-RADIX) for su, idx in sort_suffixes(s, [(s[idx+RADIX:idx+RADIX+RADIX], idx+RADIX) for su, idx in c], ranks)] for k in range(len(resolved)): r = resolved[k] ranks[r] += k sorted_suffixes[i:i+len(resolved)] = resolved def get_bwt(s, sa): """ Input: s: a string terminated by a unique delimiter '$' sa: the suffix array of s Output: L: BWT of s as a string """ L = '' for i in sa: L += s[i - 1] return L def get_F(L): """ Input: L = get_bwt(s) Output: F, first column in Pi_sorted """ return ''.join(sorted(L)) def get_M(F): """ Returns the helper data structure M (using the notation from class). M is a dictionary that maps character strings to start indices. i.e. M[c] is the first occurrence of "c" in F. If a character "c" does not exist in F, you may set M[c] = -1 """ M = {c: -1 for c in ALPHABET} prev_c = None for i in range(len(F)): c = F[i] if c != prev_c: M[c] = i prev_c = c return M def get_occ(L): """ Returns the helper data structure OCC (using the notation from class). OCC should be a dictionary that maps string character to a list of integers. If c is a string character and i is an integer, then OCC[c][i] gives the number of occurrences of character "c" in the bwt string up to and including index i """ occ = {c: [0 for _ in range(len(L))] for c in ALPHABET} for i in range(len(L)): for char in ALPHABET: if char == L[i]: occ[char][i] = occ[char][i - 1] + 1 else: occ[char][i] = occ[char][i - 1] return occ def set_ep(c, M, occ): indices = sorted(M.values()) try: return indices[indices.index(M[c]) + 1] - 1 except IndexError: return len(occ[c]) - 1 def exact_suffix_matches(p, M, occ): """ Find the positions within the suffix array sa of the longest possible suffix of p that is a substring of s (the original string). Note that such positions must be consecutive, so we want the range of positions. Input: p: the pattern string M, occ: buckets and repeats information used by sp, ep Output: a tuple (range, length) range: a tuple (start inclusive, end exclusive) of the indices in sa that contains the longest suffix of p as a prefix. range=None if no indices matches any suffix of p length: length of the longest suffix of p found in s. length=0 if no indices matches any suffix of p An example return value would be ((2, 5), 7). This means that p[len(p) - 7 : len(p)] is found in s and matches positions 2, 3, and 4 in the suffix array. >>> s = 'ACGT' * 10 + '$' >>> sa = get_suffix_array(s) >>> sa [40, 36, 32, 28, 24, 20, 16, 12, 8, 4, 0, 37, 33, 29, 25, 21, 17, 13, 9, 5, 1, 38, 34, 30, 26, 22, 18, 14, 10, 6, 2, 39, 35, 31, 27, 23, 19, 15, 11, 7, 3] >>> L = get_bwt(s, sa) >>> L 'TTTTTTTTTT$AAAAAAAAAACCCCCCCCCCGGGGGGGGGG' >>> F = get_F(L) >>> F '$AAAAAAAAAACCCCCCCCCCGGGGGGGGGGTTTTTTTTTT' >>> M = get_M(F) >>> sorted(M.items()) [('$', 0), ('A', 1), ('C', 11), ('G', 21), ('T', 31)] >>> occ = get_occ(L) >>> type(occ) == dict, type(occ['$']) == list, type(occ['$'][0]) == int (True, True, True) >>> occ['$'] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> exact_suffix_matches('ACTGA', M, occ) ((1, 11), 1) >>> exact_suffix_matches('$', M, occ) ((0, 1), 1) >>> exact_suffix_matches('AA', M, occ) ((1, 11), 1) """ curr_range = None length = len(p) sp = M[p[length - 1]] if sp == -1: return curr_range, 0 ep = set_ep(p[length - 1], M, occ) for i in range(length - 2, -1, -1): curr_range = (sp, ep + 1) sp = M[p[i]] + occ[p[i]][sp - 1] ep = M[p[i]] + occ[p[i]][ep] - 1 if sp > ep: return curr_range, length - i - 1 return (sp, ep + 1), length MIN_INTRON_SIZE = 20 MAX_INTRON_SIZE = 10000 SEPARATOR = '#' class Aligner: def __init__(self, genome_sequence, known_genes): """ Initializes the aligner. Do all time intensive set up here. i.e. build suffix array. genome_sequence: a string (NOT TERMINATED BY '$') representing the bases of the of the genome known_genes: a python set of Gene objects (see shared.py) that represent known genes. You can get the isoforms and exons from a Gene object Time limit: 500 seconds maximum on the provided data. Note that our server is probably faster than your machine, so don't stress if you are close. Server is 1.25 times faster than the i7 CPU on my computer """ self.genome = genome_sequence self.genes = known_genes self.transcriptome = self.construct_transcriptome() s = genome_sequence[::-1] + TERMINATOR self.sa = get_suffix_array(s) L = get_bwt(s, self.sa) F = get_F(L) self.M = get_M(F) self.occ = get_occ(L) def construct_transcriptome(self): transcriptome = [] for gene in self.genes: for isoform in gene.isoforms: transcript = [] positions = {} idx = 0 for exon in isoform.exons: length = exon.end - exon.start transcript.append(self.genome[exon.start:exon.end]) positions.update({idx + i: exon.start + i for i in range(length)}) idx += (length + 1) transcript = SEPARATOR.join(transcript) transcriptome.append((transcript, positions)) return transcriptome def find_seeds(self, reversed_read, len_read, len_string, sa, M, occ): seed_matches = [] mismatches = -1 i = len_read indices = [] while i > 0: _range, length = exact_suffix_matches(reversed_read[:i], M, occ) if _range is None: mismatches += 1 if mismatches > MAX_NUM_MISMATCHES: return [] seed_matches.append([(len_read - i, -1, 0)]) length = 1 else: sp, ep = _range if len(indices) == 0: seed_matches.append([(len_read-i, len_string-sa[idx]-length, length) for idx in range(sp, ep)]) indices = [len_string - sa[idx] for idx in range(sp, ep)] else: matches = [(len_read - i, len_string - sa[idx] - length, length) for idx in range(sp, ep) if (len_string - sa[idx] - length) in indices] if len(matches) > 0: seed_matches.append(matches) else: seed_matches.append([(len_read - i, len_string - sa[sp] - length, length)]) indices = [i + length for i in indices] mismatches += 1 if mismatches > MAX_NUM_MISMATCHES: return [] i -= length return seed_matches def similarity(self, seq1, seq2): if len(seq2) < len(seq1): return MAX_NUM_MISMATCHES score = 0 for i in range(len(seq1)): if seq1[i] != seq2[i]: score += 1 return score def get_transcriptome_alignment(self, read_sequence, seed_matches, len_read, transcript, positions): genomic_windows = product(*seed_matches) best_alignment = [] best_score = -len_read len_transcipt = len(transcript) for window in genomic_windows: alignment = [] score = len_read mismatches = 0 next_idx = window[0][1] start_read_idx = window[0][0] start_genome_idx = positions[window[0][1]] length = 0 aligned = True for seed in window: if next_idx >= len_transcipt: aligned = False break elif transcript[next_idx] == SEPARATOR: next_idx += 1 read_idx, transcript_idx, len_match = seed if len_match == 0: mismatches += 1 if mismatches > MAX_NUM_MISMATCHES: aligned = False break next_idx += 1 score -= 1 length += 1 elif transcript_idx != next_idx: sim = self.similarity(read_sequence[read_idx:read_idx + len_match], transcript[next_idx:next_idx + len_match]) if sim + mismatches <= MAX_NUM_MISMATCHES: transcript_idx = next_idx mismatches += sim score -= sim else: aligned = False break if start_genome_idx + length != positions[transcript_idx]: alignment.append((start_read_idx, start_genome_idx, length)) start_read_idx = read_idx start_genome_idx = positions[transcript_idx] length = 0 next_idx += len_match length += len_match if aligned is True: alignment.append((start_read_idx, start_genome_idx, length)) if len(alignment) > 0 and score > best_score: best_alignment = alignment best_score = score return best_alignment, best_score def align_transcriptome(self, read_sequence, reversed_read, len_read): best_alignment = [] best_score = -len_read for transcript, positions in self.transcriptome: s = transcript[::-1] + TERMINATOR sa = get_suffix_array(s) L = get_bwt(s, sa) M = get_M(get_F(L)) occ = get_occ(L) seed_matches = self.find_seeds(reversed_read, len_read, len(transcript), sa, M, occ) if len(seed_matches) == 0: continue alignment, score = self.get_transcriptome_alignment(read_sequence, seed_matches, len_read, transcript, positions) if len(alignment) > 0 and score > best_score: best_alignment = alignment best_score = score return best_alignment def get_genome_alignment(self, read_sequence, seed_matches, len_read): genomic_windows = product(*seed_matches) best_alignment = [] best_score = -len_read for window in genomic_windows: alignment = [] score = len_read mismatches = 0 next_idx = window[0][1] start_read_idx = window[0][0] start_genome_idx = window[0][1] length = 0 aligned = True for seed in window: read_idx, string_idx, len_match = seed if len_match == 0: mismatches += 1 if mismatches > MAX_NUM_MISMATCHES: aligned = False break next_idx += 1 score -= 1 length += 1 elif string_idx != next_idx: diff = string_idx - next_idx if MIN_INTRON_SIZE <= diff <= MAX_INTRON_SIZE: score -= log(diff) next_idx += diff alignment.append((start_read_idx, start_genome_idx, length)) start_read_idx = read_idx start_genome_idx = string_idx length = 0 else: sim = self.similarity(read_sequence[read_idx:read_idx + len_match], self.genome[next_idx:next_idx + len_match]) if sim + mismatches <= MAX_NUM_MISMATCHES: mismatches += sim score -= sim else: aligned = False break next_idx += len_match length += len_match if aligned is True: alignment.append((start_read_idx, start_genome_idx, length)) if len(alignment) > 0 and score > best_score: best_alignment = alignment best_score = score return best_alignment, best_score def align_genome(self, read_sequence, reversed_read, len_read): seed_matches = self.find_seeds(reversed_read, len_read, len(self.genome), self.sa, self.M, self.occ) if len(seed_matches) == 0: return [] alignment, score = self.get_genome_alignment(read_sequence, seed_matches, len_read) return alignment def align(self, read_sequence): """ Returns an alignment to the genome sequence. An alignment is a list of pieces. Each piece consists of a start index in the read, a start index in the genome, and a length indicating how many bases are aligned in this piece. Note that mismatches are count as "aligned". Note that <read_start_2> >= <read_start_1> + <length_1>. If your algorithm produces an alignment that violates this, we will remove pieces from your alignment arbitrarily until consecutive pieces satisfy <read_start_2> >= <read_start_1> + <length_1> Return value must be in the form (also see the project pdf): [(<read_start_1>, <reference_start_1, length_1), (<read_start_2>, <reference_start_2, length_2), ...] If no good matches are found: return the best match you can find or return [] Time limit: 0.5 seconds per read on average on the provided data. """ len_read = len(read_sequence) reversed_read = read_sequence[::-1] alignment = self.align_transcriptome(read_sequence, reversed_read, len_read) if len(alignment) > 0: print("\nAligned to transcriptome") print(read_sequence) print(''.join([self.genome[i:i+l] for _, i, l in alignment])) print(alignment) return alignment alignment = self.align_genome(read_sequence, reversed_read, len_read) if len(alignment) > 0: print("\nAligned to genome") print(read_sequence) print(''.join([self.genome[i:i + l] for _, i, l in alignment])) print(alignment) else: print("\nUnaligned") print(read_sequence) return alignment
import turtle from math import cos,sin from time import sleep window = turtle.Screen() window.bgcolor("#FFFFFF") mySpirograph = turtle.Turtle() mySpirograph.hideturtle() mySpirograph.tracer(0) mySpirograph.speed(0) mySpirograph.pensize(2) myPen = turtle.Turtle() myPen.hideturtle() myPen.tracer(0) myPen.speed(0) myPen.pensize(3) myPen.color("#AA00AA") R = 125 r = 85 d = 125 angle = 0 myPen.penup() myPen.goto(R-r+d,0) myPen.pendown() theta = 0.2 steps = 8 * int(6*3.14/theta) for t in range(0,steps): mySpirograph.clear() mySpirograph.penup() mySpirograph.setheading(0) mySpirograph.goto(0,-R) mySpirograph.color("#999999") mySpirograph.pendown() mySpirograph.circle(R) angle+=theta x = (R - r) * cos(angle) y = (R - r) * sin(angle) mySpirograph.penup() mySpirograph.goto(x,y-r) mySpirograph.color("#222222") mySpirograph.pendown() mySpirograph.circle(r) mySpirograph.penup() mySpirograph.goto(x,y) mySpirograph.dot(5) x = (R - r) * cos(angle) + d * cos(((R-r)/r)*angle) y = (R - r) * sin(angle) - d * sin(((R-r)/r)*angle) mySpirograph.pendown() mySpirograph.goto(x,y) mySpirograph.dot(5) myPen.goto(mySpirograph.pos()) mySpirograph.getscreen().update() #sleep(0.05) sleep(0.02) #Hide Spirograph mySpirograph.clear() mySpirograph.getscreen().update()
import pygame as game import random import math from settings import LOGO_IMAGE, BACKGROUND_IMAGE, CONTAINER_SIZE # FIXME: Maybe there is a better way to store rgb colors than dict? color = { "INFECTED": (255, 0, 0), # Red in RGB "HEALTHY": (0, 0, 255) # Blue in RGB } class Container: """ Main container used for simulations""" def __init__(self): self.position = (0,0) self.size = CONTAINER_SIZE self.image = game.image.load(BACKGROUND_IMAGE) # Scale background image to fit container size self.image = game.transform.scale(self.image, self.size) @property def borders(self): """ Automatically calculate container borders. :return: dict with borders """ return { "left": self.position[0], "right": self.position[0] + self.size[0], "up": self.position[1], "down": self.position[1] + self.size[1] } class Atom: """ Class representing single atom """ def __init__(self, radius, screen, container): """ Generate atom :param radius: radius of an atom :param screen: reference to main display :param container: container object where to put atoms """ # Start positions on x and y axis self.x = random.randint(radius, container.size[0]-radius) self.y = random.randint(radius, container.size[1]-radius) self.radius = radius self.color = color['HEALTHY'] self.thickness = 1 self.speed = random.random() self.angle = random.uniform(0, math.pi*2) # Main display self.screen = screen # Container in which atoms are present self.container = container def draw(self): """ Draw atom on screen """ game.draw.circle(self.screen, self.color, (int(self.x), int(self.y)), self.radius, self.thickness) def bounce(self): """ Bounce Atom from the walls """ # Use "Exceeding boundaries" section for calculating new direction # http://archive.petercollingridge.co.uk/book/export/html/6 if self.x > self.container.size[0] - self.radius: self.x = 2*(self.container.size[0] - self.radius) - self.x self.angle = - self.angle elif self.x < self.radius: self.x = 2*self.radius - self.x self.angle = - self.angle if self.y > self.container.size[1] - self.radius: self.y = 2*(self.container.size[1] - self.radius) - self.y self.angle = math.pi - self.angle elif self.y < self.radius: self.y = 2*self.radius - self.y self.angle = math.pi - self.angle def move(self): """ Move Atom by one frame """ self.x += math.sin(self.angle) * self.speed self.y -= math.cos(self.angle) * self.speed self.bounce() class App: """ Main application window """ def __init__(self, radius, number_of_atoms): """ Generate main game :param radius: radius of single atom :param number_of_atoms: number of atoms in container """ game.init() game.display.set_caption("Atom Collisions") self.logo = game.image.load(LOGO_IMAGE) game.display.set_icon(self.logo) self.display = game.display.set_mode(CONTAINER_SIZE) self.running = True # FPS clock self.clock = game.time.Clock() # Container with atoms self.container = Container() # Generate atoms self.atoms = [Atom(radius, self.display, self.container) for i in range(number_of_atoms)] def _start(self): """ Start the simulation """ while self.running: for event in game.event.get(): if event.type == game.QUIT: self.running = False self._tick() def _tick(self): """ Frame function - called every frame """ self.display.blit(self.container.image, self.container.position) for atom in self.atoms: atom.move() atom.draw() game.display.flip() # Tick frame, increasing tick will result in faster simulation self.clock.tick(60) if __name__ == '__main__': app = App(15, 10) app._start()
""" COMP30024 Artificial Intelligence, Semester 1 2019 Solution to Project Part A: Searching Authors: John Stephenson (587636) Asil Mian (867252) """ import sys import json import heapq from board import Board from bprint import print_solution def main(): with open(sys.argv[1]) as file: data = json.load(file) board = Board(data) solution = a_star_search(board) print_solution(solution) def a_star_search(board): """ search the board for the solution and return the path leading to the solution if one is found """ start = board.initial_state #stores all visited states seen = {} queue = [start] heapq.heapify(queue) #while not all pieces are of the board while queue and not queue[0].is_goal(): parent_state = heapq.heappop(queue) #add child states to queue if not seen before for child in parent_state.child_states(): if child in seen: continue heapq.heappush(queue, child) seen[child] = True #return if solution found if queue: return reconstruct_path(queue[0]) else: return None def reconstruct_path(end_state): """ track back the path to the initial state from the end_state """ actions = [] curr_state = end_state #add all the moves until initial state is reached while curr_state.parent_state: actions.append(curr_state.poslist) curr_state = curr_state.parent_state #add the initial state actions.append(curr_state.poslist) #return action list in reverse order return actions[::-1] # when this module is executed, run the `main` function: if __name__ == '__main__': main()
import pygame if __name__ == '__main__': # try: n = int(input()) if n <= 0: raise Exception size = width, height = 300, 300 pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption("Ромбики") w, h = width, height x, y = 0, 0 rect = pygame.rect.Rect(0, 0, n, n) rect = pygame.draw.rect(screen, pygame.color.Color("orange"), pygame.rect.Rect(0, 0, n, n)) # for i in range(0, height, n): # for j in range(0, width, n): # pygame.draw.rect(screen, pygame.color.Color("orange"), (i, j, n, n)) while pygame.event.wait().type != pygame.QUIT: pygame.display.flip() pygame.quit() # except: # print("Неправильный формат ввода")
#!/bin/python import sys from math import log def main(argv): n = int(argv[1]) for i in range(n+1): print('%d: %d' % (i, count_factorial_zeros_iterative(i))) def count_factorial_zeros(n): """Succinctly returns number of trailing zeros in n!""" if n < 0: return -1 elif n == 0: return 0 return sum(int(n/5**i) for i in range(1, int(log(n)/log(5) + 1))) def count_factorial_zeros_iterative(n): """Returns number of trailing zeros in n! by iterating through factors""" if n < 0: return -1 zeros = 0 # To count the number of times n! is divisible by 2 and 5 twos_count = 0 fives_count = 0 # Iteratively count for each factor in n! for i in range(2, n+1): while (i % 2) == 0: twos_count += 1 i //= 2 while (i % 5) == 0: fives_count += 1 i //= 5 # Count the number of times 2 and 5 divides i, add to zeros while fives_count and twos_count: # counts > 0 zeros += 1 fives_count -= 1 twos_count -= 1 return zeros if __name__ == '__main__': main(sys.argv)
#!/usr/bin/env python3 # This is an extended Sieve of Erastosthenes, where it generates a complete prime # factorization of all integers up to some given maximum. from typing import List from typing import Dict def primefaclist(n:int) -> List[Dict[int,int]]: a = [dict() for i in range(n)] for p in range(2, len(a)): if len(a[p]) > 0: continue f = p while f < len(a): for i in range(f, len(a), f): if p in a[i]: a[i][p] += 1 else: a[i][p] = 1 f *= p return a def main(): a = primefaclist(10000) for i,d in enumerate(a): print(f"i={i}: ",end='') for p,e in d.items(): print(f"(p,e)=({p},{e}) ",end='') print() if __name__ == '__main__': main()
# will print [22.1, 23.4, 34.0, 23.0] #temps = [221, 234, 340, -9999, 230] #new_temps = [temp / 10 for temp in temps if temp != -9999] # if using else, to get the same results use #new_temps = [temp / 10 if temp != -9999 else 0 for temp in temps] #print(new_temps) def area(a,b): return a * b print(area(4,5))
from time import sleep from timer import RepeatedTimer def hello(name): print ("Hello %s!" % name) print ("starting...") if __name__ == "__main__": rt = RepeatedTimer(3, hello, "World") try: finally: rt.stop()
""" Count the number of unique words in a file """ import argparse import codecs import logging from collections import Counter from multiprocessing import Pool logging.basicConfig() logger = logging.getLogger(__name__) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-i','--input', help='the input corpus', required=True) args = parser.parse_args() vocab_counts = Counter() with codecs.open(args.input, encoding='utf8') as inp: for l in inp: vocab_counts.update(l.strip().split()) logger.info(u'Stats for {}'.format(args.input)) logger.info(u'Total vocab size: {}'.format(len(vocab_counts))) logger.info(u'Top 100 words: {}'.format(vocab_counts.most_common(100)))
print("Please select operation -\n " "1. Add\n " "2. Subtract\n" "3. Multiply\n" "4. Divide\n") # Take input from the user select = input("Select operations form 1, 2, 3, 4 :").strip() number_1 = int(input("Enter first number: ").strip()) number_2 = int(input("Enter second number: ").strip()) # Function to add two numbers def add(num1, num2): return num1 + num2 # Function to subtract two numbers def substract(num1, num2): return num1 - num2 # Function to multiply two numbers def multiply(num1, num2): return num1 * num2 # Function to divide two numbers def divide(num1, num2): return num1 / num2 # Calculator logic if select == '1': print(add(number_1, number_2)) elif select == '2': print(substract(number_1, number_2)) elif select == '3': print(multiply(number_1, number_2)) elif select == '4': print(divide(number_1, number_2)) else: print('You have not entered a valid number')
import operator def most_frequent(x): d = {} for i in x: d[i] = x.count(i) d1 = dict(sorted(d.items(), key=operator.itemgetter(1), reverse=True)) for i in d1: print(i,'=', d1[i]) x = input("Enter the input string: ") most_frequent(x)
def who_do_you_know(): people = input("Bitch, who do you know?").split(",") return [person.strip() for person in people] def ask_user(): person_to find = input("Who you tryna find?") if person_to_find in who_do_you_know(): print("Yeah, you know that person.") ask_user();
peso = float(input("Qual o seu peso (kg): ")) altura = float(input("Qual a sua altura (m): ")) imc = peso / (altura)**2 print("Seu IMC é de: {:.2f}. E você esta: ".format(imc)) if imc < 18.5: print("ABAIXO DO PESO.") elif imc < 25: print("COM PESO IDEAL.") elif imc < 30: print("COM SOBREPESO.") elif imc < 40: print("OBESO.") else: print("COM OBESIDADE MÓRBIDA.")
par = 0 imp = 0 count = 0 for i in range (1,7): num = int(input("Digite o valor {}: ".format(i))) if num % 2 == 0: par +=num count += 1 #else: #imp += num print("A soma dos {} número(s) pares é igual a {}.".format(count,par))
import types from itertools import islice def group(iterable, n): """Splits an iterable set into groups of size n and a group of the remaining elements if needed. Args: iterable (list): The list whose elements are to be split into groups of size n. n (int): The number of elements per group. Returns: list: The list of groups of size n, where each group is a list of n elements. """ iterable = list(iterable) # handle generator and tuple inputs mod = len(iterable) % n build = [iterable[index: index + n] for index in range(0, len(iterable) - mod, n)] # build = [list(islice(iterable, index, index + n)) for index in range(0, len(iterable) - mod, n)] if mod: build.append(iterable[-mod:]) return build if __name__ == '__main__': iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] n = 3 ret = group(iterable, n) print(ret)
from itertools import chain STAR = '*' def gen_rhombus(width): """Create a generator that yields the rows of a rhombus row by row. So if width = 5 it should generate the following rows one by one: gen = gen_rhombus(5) for row in gen: print(row) output: * *** ***** *** * """ up = range(1, width + 1, 2) if width % 2 != 0 else range(1, width, 2) down = up[:-1][::-1] # ignore last element of up and reverse sequence num_stars = chain(up, down) yield from ['{: ^{width}}'.format(STAR * count, width=width) for count in num_stars]
import re def capitalize_sentences(text: str) -> str: """Return text capitalizing the sentences. Note that sentences can end in dot (.), question mark (?) and exclamation mark (!)""" sentences = [sentence.strip() for sentence in re.split(r'(?<=[\.\!\?]) |$', text)] return ' '.join(sentence[0].upper() + sentence[1:] for sentence in sentences if len(sentence) > 0)
import re VOWELS = 'aeiou' PYTHON = 'python' def contains_only_vowels(input_str): """Receives input string and checks if all chars are VOWELS. Match is case insensitive.""" # use regex for this one vowels_found = re.findall(r'[aeiou]', input_str, flags=re.I) return len(vowels_found) == len(input_str) def contains_any_py_chars(input_str): """Receives input string and checks if any of the PYTHON chars are in it. Match is case insensitive.""" return any([True for char in input_str if char.upper() in PYTHON.upper()]) def contains_digits(input_str): """Receives input string and checks if it contains one or more digits.""" return re.search(r'\d+', input_str)
from operator import mul from functools import reduce def get_octal_from_file_permission(rwx: str) -> str: """Receive a Unix file permission and convert it to its octal representation. In Unix you have user, group and other permissions, each can have read (r), write (w), and execute (x) permissions expressed by r, w and x. Each has a number: r = 4 w = 2 x = 1 So this leads to the following input/ outputs examples: rw-r--r-- => 644 (user = 4 + 2, group = 4, other = 4) rwxrwxrwx => 777 (user/group/other all have 4 + 2 + 1) r-xr-xr-- => 554 (user/group = 4 + 1, other = 4) """ trans_table = {'r': 4, 'w': 2, 'x': 1, '-': 0} perm_groups = [rwx[i:i+3] for i in range(0, 7, 3)] to_ocatal_ = lambda rwx: str(sum(trans_table[perm] for perm in rwx)) return ''.join(to_ocatal_(group) for group in perm_groups)
import re def count_indents(text): """Takes a string and counts leading white spaces, return int count""" return re.match(r'^[ ]*', text).end()
WHITE, BLACK = ' ', '#' def create_chessboard(size=8): """Create a chessboard with of the size passed in. Don't return anything, print the output to stdout""" row = str(WHITE + BLACK) * int(size / 2) board = [row if count % 2 == 0 else row[::-1] for count in range(size)] print(*board, sep='\n')
#group 13 984165 and 965396 #we set move on valid for using it in the while loop move='valid' while move=='valid': #inputing the moves goat=str(input('Please enter the move of the goat(w/e):')) wolf=str(input('Please enter the move of the wolf(w/e):')) cabbage=str(input('Please enter the move of the cabbage(w/e):')) man=str(input('Please enter the move of the man(w/e):')) #putting move invalid if there is made a wrong move so the game is lost if goat=='e' and wolf=='e': move='invalid' if goat=='e' and cabbage=='e': move='invalid' print('This move is',move) #if all the figures are on the other side of the river the game is won and it breaks if goat=='w' and wolf=='w' and cabbage=='w' and man=='w': print('The game is won') break if man=='e' and goat=='e' and cabbage=='e'and wolf=='e': move='valid' if man=='e' and goat=='e' and cabbage=='e': move='valid' if man=='e' and goat=='e' and wolf=='e': move='valid'
# This script basically takes as first input a number from 1 to 3, by which the search engine is selected: # 1 for conjunctive query # 2 for pages ranked with cosine similarity over TfIdf of query and documents # 3 for the custom one, that computes a score given by the average distances between the query and documents over the variables Run-time, Release Year, Budget, and number of starring actors. #Both search engine 2 and 3 run on the set of documents given by the conjunctive query. #Then, it requires the text input and, for search engine 3, additional inputs for budget, runtime, release year and starring actors. #The output will be an html file (display.html) saved in the current path (given in Functions.py), and automatically opened in a new tab of the browser. from utils import * search_engine = input('Choose the search engine model [1-3] (default is 2) : ') if search_engine == '1': Run_SE1() elif search_engine == '3': search_engine3() else: Run_SE2()
aircrafts=[{'x':1,'y':7},{'x':3,'y':5},{'x':4,'y':8},{'x':9,'y':10},{'x':6,'y':12}] aircraft_number=1 for aircraft in aircrafts: print "Air-craft Number: ",aircraft_number print(aircraft['x']) print(aircraft['y']) print '\n' aircraft_number+=1
#Python Bank Main import os import csv import statistics # grabbing the csv file for budget data csvpath = os.path.join('budget_data.csv') with open(csvpath, newline='') as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') # Read the header row first (skip this step if there is no header) csv_header = next(csvreader) # print(f"CSV Header: {csv_header}") # initialize months at 0 then count for each iteration months = 0 profit_list = [] month_list = [] for row in csvreader: months = months + 1 profit_list.append(row[1]) month_list.append(row[0]) print("Total Months: " + str(months)) profit_list = list(map(int, profit_list)) print("Total Profit: $" + str(sum(profit_list))) # Turns profit_list into integers profit_list = list(map(int, profit_list)) change_list = [] i = 0 for i in range(len(profit_list) - 1): change = (profit_list[i] - (profit_list[i + 1])) * -1 change_list.append(change) print("Average Change: $" + str(round(statistics.mean(change_list),2))) minpos = change_list.index(min(change_list)) maxpos = change_list.index(max(change_list)) # Need to split the month list string adding '20' and removing the '-' max_str = str(month_list[maxpos + 1]) min_str = str(month_list[minpos + 1]) # max_str.replace('-',' 20') final_max = max_str.replace('-','-20') final_min = min_str.replace('-','-20') print("Greatest Increase in Profits: " + final_max + " ($" + str((change_list[maxpos])) + ")") print("Greatest Decrease in Profits: " + final_min + " ($" + str((change_list[minpos])) + ")")
a=int(input()) b=int(input()) for i in range(a,b): i%2==0 print("odd numbers")
line = "smile please" list = line.split(" ") print("No. of words in the list : "+str(len(list)))
list1 = [] list2 = [] list3 = [] n1 = int(input("Total elements in first list : ")) for i in range(n1): value = int(input("input no : ")) list1.append(value) n2 = int(input("Total elements in second list : ")) for i in range(n2): value = int(input("input no : ")) list2.append(value) if(n1 == n2): print("same length") else: print("Not same length") if(sum(list1) == sum(list2)): print("same sum") else: print("sum are different") list3 = [each for each in list1 if each in list2] print("same members are :",list3)
print("enter 3 number/n") num1=int(input("first number:")) num2=int(input("second number:")) num3=int(input("third number:")) if num1>num3 and num1>num2: print(num1,"is large") elif num2>num3: print(num2,"is large") else: print(num3,"is large")
import networkx as nx class SocialGraph(): """ Creates a graph of twitter friends representing a community """ def gen_user_friends_graph(self, user: str, user_friends_getter, social_graph_setter): """ Generates a user friends graph for a given user @param user the user to generate the graph for @param user_friends_getter the dao to retrieve the given users friends from @param social_graph_setter the dao to store the computed social graph """ user_friends_graph = self.get_user_friends_graph(user, user_friends_getter) social_graph_setter.store_user_friends_graph(user, user_friends_graph) return user_friends_graph def get_user_friends_graph(self, user: str, user_friends_getter) -> nx.Graph: """ Constructs the social graph of a given user, assuming that the users local neighbourhood has already been stored, and is accessible from user_friends_getter @param user the user to generate the graph for @param user_friends_getter the dao to retrieve the user's friends from @return the social graph of the user's local neighbourhood """ graph = nx.Graph() user_friends_list = user_friends_getter.get_friends_by_name(user) local = [user] + user_friends_list # Nodes are friends of user for agent in local: graph.add_node(agent) # Edges between user1 and user2 indicate that both users follow each other li = list(graph.nodes) for i in range(len(li)): for j in range(i, len(li)): user1 = li[i] user2 = li[j] user1_friends_list = user_friends_getter.get_friends_by_name(user1) user2_friends_list = user_friends_getter.get_friends_by_name(user2) if user1 in user2_friends_list and user2 in user1_friends_list: graph.add_edge(li[j], li[i]) return graph
from typing import List, Dict from src.model.user import User class FriendSetter: """ An abstract class representing an object that stores all of a users friends in a datastore """ def store_friends(self, user_id: str, friends_ids: List[str]): raise NotImplementedError("Subclasses should implement this")
from typing import List, Dict from src.model.ranking import Ranking class RankingSetter: """ An abstract class representing an object that stores tweets in a datastore """ def store_ranking(self, ranking: Ranking): raise NotImplementedError("Subclasses should implement this") def store_rankings(self, rankings: List[Ranking]) -> None: for ranking in rankings: self.store_ranking(ranking)
from typing import List, Dict from src.model.user import User class UserSetter: """ An abstract class representing an object that stores users in a datastore """ def store_user(self, user: User): raise NotImplementedError("Subclasses should implement this") def store_users(self, users: List[User]): for user in users: self.store_user(user)
import msds510.util as mod import csv import sys arg_list = sys.argv #fieldname variable takes the argument list 1 filename = arg_list[1] lines = [] #use reader as a dictionary which is how the lines will be formatted with open(filename,'r') as csv_file: csv_reader = csv.DictReader(csv_file) #for each line in reader, add line to the name lines for line in csv_reader: lines.append(line) #the conditions to print the content of the record print('Input Record - {\'year\':' +line['year']+', \'intro\': '+line['full_reserve_avengers_intro']+'}') print('Date joined - '+str(mod.get_date_joined(str(line['year']),str(line['full_reserve_avengers_intro'])))) print('Days since joined - '+str(mod.days_since_joined(str(line['year']),str(line['full_reserve_avengers_intro'])))) print() print()
#!/usr/local/bin python3 # -*- coding: utf-8 -*- # https://www.programiz.com/python-programming/global-local-nonlocal-variables x = "global" def foo(): #global x # x = x * 3 # 如果不使用global关键字, 则python 会查找local variable x 并进行赋值,由于没有找到 local variable x而抛出错误 print(x) #即使不使用global,print 也可以访问 全局变量 foo() ''' Traceback (most recent call last): File "variable_scope.py", line 9, in <module> foo() File "variable_scope.py", line 7, in foo x = x * 2 UnboundLocalError: local variable 'x' referenced before assignment '''
#!/usr/local/bin python3 # -*- coding: utf-8 -*- #python 约定使用大写定义常量,例如 JAN = 1 FEB = 2 #好处是简单,缺点是类型是int,并且仍然是变量。 #更好的方法是为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例。Python提供了Enum类来实现这个功能: from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) #这样我们就获得了Month类型的枚举类,可以直接使用Month.Jan来引用一个常量,或者枚举它的所有成员: for name,member in Month.__members__.items(): print(name, '=>', member, ',', member.value) #value属性则是自动赋给成员的int常量,默认从1开始计数。 #如果需要更精确地控制枚举类型,可以从Enum派生出自定义类: from enum import unique @unique #@unique装饰器可以帮助我们检查保证没有重复值。 class Weekday(Enum): Sun = 0 # Sun的value被设定为0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 print(Weekday['Sun']) #用成员名称引用枚举常量 print(Weekday[7]) #可以直接根据value的值获得枚举常量
#!/usr/local/bin python3 # -*- coding: utf-8 -*- #------------------------------------------------------------------------------------------------------------------------- # slice #------------------------------------------------------------------------------------------------------------------------- #L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。 print([1,2,3,4][0:3]) #如果第一个索引是0,还可以省略: print([1,2,3,4][:3]) #类似的,既然Python支持L[-1]取倒数第一个元素,那么它同样支持倒数切片,试试: print([1,2,3,4][-1:]) print([1,2,3,4][-3:-1]) print('slice tuple', (1,2,3,4)[1:3]) L = list(range(100)) # start from 0 to 100, 100 omitted print(L[:10]) # start default to 0 # step print(L[:10:2]) print(L[:]) # copy list #slice for string print('abcdefg'[:5]) # trim end def trim(s): if len(s)>0: return s[1:][:-1] else: return s print(len(trim(' abc '))) print(trim(' ')=='') #------------------------------------------------------------------------------------------------------------------------- # iteration #------------------------------------------------------------------------------------------------------------------------- #list这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代: from collections import Iterable d = {'a': 1, 'b': 2, 'c': 3} for key in d: print(key) for value in d.values(): print(value) for k,v in d.items(): print(k,v) print(isinstance('abc', Iterable)) print(isinstance(123, Iterable)) #!important #如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身: for i, value in enumerate(['a','b','c']): print(i,value) #------------------------------------------------------------------------------------------------------------------------- # 列表生成式 list comprehensions, 语法 [] 内编写生成表达式 #------------------------------------------------------------------------------------------------------------------------- #写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来,十分有用,多写几次,很快就可以熟悉这种语法。 print([x*x for x in range(1,11)]) #for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方: print([x*x for x in range(1,11) if x%2==0]) # two layers loop print([m+n for m in 'abc' for n in 'xyz']) import os print([dir for d in os.listdir('.')]) print([k+'=' + v for k,v in {'x': 'A', 'y': 'B', 'z': 'C' }.items()]) print([item for item in ['Hello', 'World', 18, 'Apple', None] if isinstance(item,str)]) #------------------------------------------------------------------------------------------------------------------------- # generator () 内编写生成表达式 #------------------------------------------------------------------------------------------------------------------------- #通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表, # 不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。 print((x*x for x in range(10))) #<generator object <genexpr> at 0x1022ef630> g = (x*x for x in range(10)) #<class 'generator'> print(type(g)) for i in g: print(i) #call next(g) to print next value, but need to handl StopIteration error def fib(max): n,a,b = 0, 0, 1 while n< max: print(b) a,b = b, a + b n = n +1 return 'done' #仔细观察,可以看出,fib函数实际上是定义了斐波拉契数列的推算规则,可以从第一个元素开始,推算出后续任意的元素,这种逻辑其实非常类似generator。 #也就是说,上面的函数和generator仅一步之遥。要把fib函数变成generator,只需要把print(b)改为yield b就可以了: def fib(max): n,a,b = 0, 0, 1 while n< max: yield b #这就是定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator #这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。 # 而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。 a,b = b, a + b n = n +1 return 'done' print(fib(10)) def odd(): print('step 1') yield 1 print('step 2') yield 2 print('step 3') yield 3 o = odd() print(next(o)) print(next(o)) g = fib(6) while True: try: x = next(g) print('next:', x) except StopIteration as e: print('generator return value', e.value) break def triangles(): pass #------------------------------------------------------------------------------------------------------------------------- # iterator #------------------------------------------------------------------------------------------------------------------------- #我们已经知道,可以直接作用于for循环的数据类型有以下几种: #一类是集合数据类型,如list、tuple、dict、set、str等; #一类是generator,包括生成器和带yield的generator function。 #这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。 print(isinstance(1,Iterable)) from collections import Iterator #可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。 print(isinstance((x for x in range(10)), Iterator)) # print(isinstance('abc',Iterator)) # false ### 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。 #你可能会问,为什么list、dict、str等数据类型不是Iterator? # 这是因为Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据, # 直到没有数据时抛出StopIteration错误。可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度, # 只能不断通过next()函数实现按需计算下一个数据,所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。 #小结 #凡是可作用于for循环的对象都是Iterable类型; #凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列; # 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。 #Python的for循环本质上就是通过不断调用next()函数实现的,例如: for x in [1,2,3,4]: pass #equals to it = iter([1,2,3,4]) while True: try: x = next(it) except StopIteration: break
"""Python serial number generator.""" class SerialGenerator: """Machine to create unique incrementing serial numbers. >>> serial = SerialGenerator(start=100) >>> serial.generate() 100 >>> serial.generate() 101 >>> serial.generate() 102 >>> serial.reset() >>> serial.generate() 100 """ def __init__(self, start): ''' initiation method of the class SerialGenerator __________________________________________________ property is used to operate in the class self.start = (int or float) property is used to hold the original start number self.default = self.start ''' self.start = start self.default = self.start def generate(self): ''' the method increases the amount of the start number by one time per run ''' a = self.start self.start += 1 return a def reset(self): ''' the method is used to reset to the original number ''' self.start = self.default def __repr__(self): ''' returns string description of the class ''' return f'<SerialGenerator start={self.start} next={self.start+1}>'
player1 = "1 or 2" player2 = "2 or 1" Board = [["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"]] def Battle (b): for i in range(0,len(b)): for j in range(0,len(b[i])): print(" " + b[i][j] + " ",end="") print(" ") Battle(Board) run = True playernum = 1 numplaced = 0 while run: print("Player 1: You can position five ships: Carrier(5 spaces), Battleship(4 spaces), Cruiser(3 spaces), Submarine(3 spaces), and Destroyer(2 spaces)") pieces = input("What piece do you want to pick?") if(pieces == "Carrier"): column = int(input("Which column do you want it in?") ) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" Board[row][column+2] = "*" Board[row][column+3] = "*" Board[row][column+4] = "*" numplaced+=1 Battle(Board) if(pieces == "Battleship"): column = int(input("Which column do you want it in?") ) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" Board[row][column+2] = "*" Board[row][column+3] = "*" numplaced+=2 Battle(Board) if(pieces == "Cruiser"): column = int(input("Which column do you want it in?")) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" Board[row][column+2] = "*" numplaced+=3 Battle(Board) if(pieces == "Submarine"): column = int(input("Which column do you want it in?") ) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" Board[row][column+2] = "*" numplaced+=4 Battle(Board) if(pieces == "Destroyer"): column = int(input("Which column do you want it in?") ) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" numplaced+=5 Battle(Board) if(numplaced == 5): run = False Board2 = [["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"]] Battle(Board2) playernum = 1 numplaced = 0 while run: print("Player 2: You can position five ships: Carrier(5 spaces), Battleship(4 spaces), Cruiser(3 spaces), Submarine(3 spaces), and Destroyer(2 spaces)") pieces = input("What piece do you want to pick?") if(pieces == "Carrier"): column = int(input("Which column do you want it in?") ) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" Board[row][column+2] = "*" Board[row][column+3] = "*" Board[row][column+4] = "*" numplaced+=1 Battle(Board2) if(pieces == "Battleship"): column = int(input("Which column do you want it in?") ) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" Board[row][column+2] = "*" Board[row][column+3] = "*" numplaced+=2 Battle(Board2) if(pieces == "Cruiser"): column = int(input("Which column do you want it in?") ) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" Board[row][column+2] = "*" numplaced+=3 Battle(Board2) if(pieces == "Submarine"): column = int(input("Which column do you want it in?") ) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" Board[row][column+2] = "*" numplaced+=4 Battle(Board2) if(pieces == "Destroyer"): column = int(input("Which column do you want it in?") ) row = int(input("Which row do you want it in?")) Board[row][column] = "*" Board[row][column+1] = "*" numplaced+=5 Battle(Board2) if(numplaced == 5): run = False while(run): first_collumn = input("Player "+str(playernum)+":Which Column would you like to move to?") ind = eval(first_collumn) for check in range(9,0): if(Board[check][ind] is "_"): if(playernum == 2): Board[check][ind] = "1" break if(playernum == 1): Board[check][ind] = "2" break Battle(Board) for r in range(0,len(Board)): for c in range(0,len(Board[r])): if(c+3<len(Board[r])): if(Board[r][c] != "_" and Board[r][c] == Board[r][c+1] and Board[r][c] == Board[r][c+2] and Board[r][c] == Board[r][c+3]): print(Board[r][c]+" wins!") run=False if(r+3<len(Board)): if(Board[r][c] != "_" and Board[r][c] == Board[r+1][c] and Board[r][c] == Board[r+2][c] and Board[r][c] == Board[r+3][c]): run=False print(Board[r][c]+" wins!") if(c-3<len(Board[r]) and r+3<len(Board)): if(Board[r][c] != "_" and Board[r][c] == Board[r+1][c-1] and Board[r][c] == Board[r+2][r-2] and Board[r][c] == Board[r+3][r-3]): run=False print(Board[r][c]+" wins!") if(c+3<len(Board[r]) and r+3<len(Board)): if(Board[r][c] != "_" and Board[r][c] == Board[r+1][c+1] and Board[r][c] == Board[r+2][r+2] and Board[r][c] == Board[r+3][c+3]): run=False print(Board[r][c]+"wins!")
with open("./input.txt") as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] # print(content) def build_path(right,down): output = "" current_y = 0 current_x = 0 height = len(content) width = len(content[0]) while current_y < height: output += content[current_y][current_x] current_x = (current_x + right) % width current_y = current_y + down return output #part 1 answer print(build_path(3,1).count("#")) #part 2 answer first = build_path(1,1).count("#") second = build_path(3,1).count("#") third = build_path(5,1).count("#") fourth = build_path(7,1).count("#") fifth = build_path(1,2).count("#") print (first * second * third * fourth * fifth)
fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: slst = list() slst = line.split() for num in range(len(slst)) : if slst[num] not in lst : lst.append(slst[num]) lst.sort() print(lst)
""" This is was Part 1 of a Python Skills Refresher assignment. """ import string def preceding(letter): alphabet = string.ascii_letters alphabet_as_list = list(alphabet) alphabet_as_list.remove('A') alphabet_as_list.remove('a') if letter is 'A': code = chr(int(ord('Z'))) elif letter is 'a': code = chr(int(ord('z'))) elif letter in alphabet_as_list: code = chr(int(ord(letter)) - 1) else: code = chr(int(ord(letter))) return(code) def succeeding(letter): alphabet = string.ascii_letters alphabet_as_list = list(alphabet) alphabet_as_list.remove('Z') alphabet_as_list.remove('z') if letter is 'Z': code = chr(int(ord('A'))) elif letter is 'z': code = chr(int(ord('a'))) elif letter in alphabet_as_list: code = chr(int(ord(letter)) + 1) else: code = chr(int(ord(letter))) return(code) def message_coder(phrase, function): phrase_characters = list(phrase) if function is 'preceding': encoded_string = list() for i in range(0, len(phrase_characters)): characters_encoded = preceding(phrase_characters[i]) encoded_string.append(characters_encoded) print("".join(encoded_string)) elif function is 'succeeding': encoded_string = list() for i in range(0, len(phrase_characters)): characters_encoded = succeeding(phrase_characters[i]) encoded_string.append(characters_encoded) print("".join(encoded_string)) message_coder('Hello World!', 'preceding') message_coder('Hello World!', 'succeeding')
def reverse_detail(str1): return str1[-1:] + str1[1:-1] + str1[:1] print(reverse_detail('ears'))
def odd_remove(str1): str2="" for st in range(len(str1)): if st % 2 == 0: str2 += str1[st] return str2 print(odd_remove('legs'))
# Jordan Leung # 2/13/2019 # printing out what is given print("Given: ") cubes = [num**3 for num in range(1,11)] print(cubes) # printing out the first three items print("The first three items in the list are: ") print(cubes[:3]) # printing out the middle of the list print("Three items from the middle of the list are: ") mid = int(len(cubes)/2) mid_Start = int(mid - 1) mid_End = int(mid + 2) print(cubes[mid_Start:mid_End]) # printing out the last three items in the list print("The last three iems in the list are: ") print(cubes[-3:]) # making a copy of a list by slicing and verifying that they are stored seperately my_fav_foods = ['cookies', 'clams', 'pickles'] friends_foods = my_fav_foods[:] my_fav_foods.append('okura') friends_foods.append('buns') print("My favorite foods include: ") for food in my_fav_foods: print(food) print("My friend's favorite foods include: ") for food in friends_foods: print(food)
# Jordan Leung # 2/11/2019 guests = ['Henry', 'Sifu Jeff', 'Tayler', 'Mat'] print(guests) print(guests[0] + ", " + guests[1] + ", " + guests[2] + ", and " + guests[3] + " are invited to this family dinner!") print("But I just realized that not everyone on the list are part of my family...") print(guests[0] + " and " + guests[1] + 'need to be replaced') # modifying family names guests[0] = "Dad" guests[1] = "Mom" print(guests) # add family members print("Now adding other family members...") guests.insert(2,'Preston') guests.insert(3,'Kaden') print(guests) # Just immediate family print("Now the boss wants just the immediate family...sorry cuz") guests.remove("Mat") guests.remove("Tayler") print(guests)
print("Mary had a little lamb.") print("Its fleece was white as %s." % 'snow') #전체 괄호 치면 됨 print("And everywhere that Mary went.") print("." * 10) # what'd that do? end01 = "C" end02 = "h" end03 = "e" end04 = "e" end05 = "s" end06 = "e" end07 = "b" end08 = "u" end09 = "r" end10 = "g" end11 = "e" end12 = "r" # watch that comma ac the end print (end01 + end02 + end03 + end04 + end05 + end06, end=' ') print (end07 + end08 + end09 + end10 + end11 + end12)
class Person: TITLES = ('Dr', 'Mr', 'Mrs', 'Ms') def __init__(self, title, name, surname, allowed_titles=TITLES): if title not in allowed_titles: raise ValueError("%s is not a valid title." % title) self.title = title self._name = name self.__surname = surname
""" Program: employee.py Author: Spencer Cress Date: 6/30/2020 """ import datetime class Person: def __init__(self, _last_name, _first_name, _address, _phone_number, _salaried, _salary, _start_date): """ :param _last_name: string, employee's last name :param _first_name: string, employee's first name :param _address: string, employee's address :param _phone_number: string, employee's phone number :param _salaried: boolean, True, False is employee salaried :param _salary: double, employee's salary, either yearly or hourly :param _start_date: datetime, employee's start date """ self.last_name = _last_name self.first_name = _first_name self.address = _address self.phone_number = _phone_number self.salaried = _salaried self.salary = _salary self.start_date = _start_date if _salaried is True: self.salary_statement = "Salaried Employee: $"+str(+_salary)+"/year" elif _salaried is False: self.salary_statement = "Hourly Employee: $"+str(_salary)+"/hour" #year = _start_date.strftime("%Y") #month = _start_date.strftime("%m") #day = _start_date.strftime("%d") def __str__(self): return "First name: " + str(self.first_name) + "\n" + "Last name: " + str(self.last_name) + "\n"\ + "Address: " + str(self.address) + "\n" + "Phone Number: " + str(self.phone_number) + "\n" + "Salary: "\ + str(self.salary) + "\n" + "Start Date: " + str(self.start_date) + "\n" def __repr__(self): print(str(self.first_name)) print(str(self.last_name)) print(str(self.address)) print(str(self.phone_number)) print(str(self.salary)) print(str(self.start_date)) def display(self): """ :return: a string """ return str(self.first_name + " " + self.last_name + "\n" + self.address + "\n" + self.salary_statement + "\n" + "Start date: " + self.start_date.strftime("%m") + "-" + self.start_date.strftime("%d") + "-" + self.start_date.strftime("%Y")) if __name__ == "__main__": emp = Person('Hall', 'Jackie', '555 5th Street \nMaxwell, Iowa', '865-1344', False, 9.85, datetime.datetime.now()) print(emp.display()) del emp
# -*- coding: utf-8 -*- """ Created on Sun Oct 22 00:00:16 2017 @author: ANEESH """ import numpy as np import matplotlib.pyplot as plt #x = np.random.randn(10,1) ranges = [i for i in range(1,101)] angle = [i*np.pi/16 for i in ranges] radius = [6.5*(104-i) for i in ranges] x1 = radius*np.cos(angle) y1 = radius*np.sin(angle) x2=-1*x1 y2=-1*y1 plt.plot(x1,y1,c='r', label = 'Class 1') plt.plot(x2,y2,c='b', label = 'Class 2') plt.title('Not linearly separable') plt.xlabel('X - axis') plt.ylabel('Y - axis') plt.legend(loc='upper right') plt.show()
# Выведите первый и последний элемент списка. lst = [1, 2, 3, 4, 5, 6, 7] print(lst[0], lst[-1])
# Нужно проверить, все ли числа в последовательности уникальны. lst1 = [34, 60, 44, 15, 99] lst2 = [34, 60, 34, 15, 99] print(len(lst1) == len(set(lst1))) print(len(lst2) == len(set(lst2)))
"""Provides methods for getting user input for Mastermind game.""" import random class MastermindUI: def __init__(self): self.keywords = {'help' : 'help', 'info' : 'info'} self.color_options = ('black', 'blue', 'green', 'red', 'white', 'yellow') print('Welcome to Mastermind in Python, written by Daniel Harada') self.info ='\nIn this game you are trying to break a 4 item code. Each slot in the code will'\ ' be filled by a colored peg. If you guess a color in the code in the correct position'\ ' you will recieve a black result peg. If you guess the correct color but in an incorrect'\ ' location, you will recieve a white result peg. For each peg you guess which is not in the'\ ' code, you recieve no result pegs.\n' print(self.info) print('If you have any questions, please type "help" or "info" at any time. Good luck!\n') def helpMe(self, keyword): help_with_spaces = '\nIn the base game there are 6 color options for code pegs: black, blue, green, red, '\ 'white, and yellow, which gives 1,296 possible 4 peg patterns. Adding space as an'\ ' option(no peg placed) increases the number of possibilities to 2401. Please enter'\ ' "yes" to allow spaces in the codes or "no" to disallow spaces.\n' help_with_guesses = '\nPlease pick a four color code as your guess. The possible colors are: {}.'\ ' Each color in your code should be separated by a space.\n'.format(', '.join(self.color_options)) help_generic = '\nThis is equal to the generic help message. It should not be reached\n' help_keywords = {'help' : help_generic, 'help with spaces' : help_with_spaces, 'help with guesses' : help_with_guesses, 'info' : self.info} print(help_keywords[keyword]) def userDecidesIfWithSpaces(self): self.keywords['help'] = 'help with spaces' while True: user_spaces_decision = input('Play with spaces? Yes or No: ').lower() self.checkForKeywords(user_spaces_decision) if (user_spaces_decision == 'yes') or (user_spaces_decision == 'no'): break self.use_spaces = user_spaces_decision def checkForKeywords(self, user_input): if user_input in self.keywords: self.helpMe(self.keywords[user_input]) return True def setColorOptions(self): color_options = ['black', 'blue', 'green', 'red', 'white', 'yellow'] if self.use_spaces == 'yes': color_options += ['space'] self.color_options = tuple(color_options) def generateSolution(self): self.solution_pegs = tuple(random.choice(self.color_options) for x in range(4)) def userInputsGuess(self): self.keywords['help'] = 'help with guesses' valid_guess = False while not valid_guess: user_input = input('Please enter your guess: ').lower() if not self.checkForKeywords(user_input): user_guess = tuple(user_input.split()) valid_guess = validateGuess(user_guess) self.guess_pegs = user_guess def validateGuess(user_guess): if not (set(user_guess) < set(self.color_options)): print('Guess needs to only include colors from: ', ', '.join(self.color_options)) elif (len(user_guess) != 4): print('Please enter a 4 color guess, each color separated by a space') else: return True def userDecidesPlayAgain(self): play_again_TF = {'yes' : True, 'no' : False} while True: play_again = input('Would you like to play again? Yes or No: ').lower() if (play_again == 'yes') or (play_again == 'no'): break return play_again_TF[play_again] if __name__ == '__main__': thisUI = MastermindUI() thisUI.userDecidesIfWithSpaces() thisUI.setColorOptions() thisUI.generateSolution() thisUI.userInputsGuess() play_again = thisUI.userDecidesPlayAgain() print(thisUI.color_options) print(thisUI.solution_pegs) print(thisUI.guess_pegs) print(play_again)
A=[] B=[] A= input('enter for list A:') B= input('enter for list B:') def fizzbuzz (A,B): C=len(A)+len(B) if (C%5==0 and C%3==0): print( 'fizzbuzz') elif (C%3==0): print ('fizz') elif (C%5==0): print ('buzz') else: print (C) fizzbuzz(A,B)
list=[1,2,3,4,5,6,7,8,9,0] i = 0 z = [] while i < len(list): j = 0 x = [] while j < 3: d = i+j x.append(d) j += 1 z.append(x) i += 3 print(z)
import pandas as pd import seaborn as sns from sklearn.decomposition import PCA sns.set(style="white", color_codes=True) import warnings import matplotlib.pyplot as plt warnings.filterwarnings("ignore") dataset = pd.read_csv('CC.csv') dataset = dataset.fillna(dataset.mean()) x = dataset.iloc[:,[1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17]] y = dataset.iloc[:,12] ##building the model from sklearn.cluster import KMeans wcss = [] for i in range(1,11): kmeans = KMeans(n_clusters=i, max_iter=300, random_state=0) kmeans.fit(x) wcss.append(kmeans.inertia_) plt.plot(range(1,11),wcss) plt.title('the elbow method') plt.xlabel('Number of Clusters') plt.ylabel('Wcss') plt.show() nclusters = 3 # this is the k in kmeans km = KMeans(n_clusters=nclusters) km.fit(x) # predict the cluster for each data point y_cluster_kmeans = km.predict(x) from sklearn import metrics score = metrics.silhouette_score(x, y_cluster_kmeans) print("KMeans:",score) #PCA from sklearn.preprocessing import StandardScaler scaler = StandardScaler() # Fit on training set only. scaler.fit(x) x_scaler = scaler.transform(x) pca = PCA(16) x_pca = pca.fit_transform(x_scaler) PCA_components = pd.DataFrame(x_pca) features = range(pca.n_components_) plt.bar(features, pca.explained_variance_ratio_, color='black') plt.xlabel('PCA features') plt.ylabel('variance %') plt.xticks(features) plt.show() top_n_components = 2 x = PCA_components.iloc[:,:top_n_components] wcss = [] for i in range(1,11): kmeans = KMeans(n_clusters=i, max_iter=300, random_state=0) kmeans.fit(x) wcss.append(kmeans.inertia_) plt.plot(range(1,11),wcss) plt.title('the elbow method') plt.xlabel('Number of Clusters') plt.ylabel('Wcss') plt.show() nclusters = 3 # this is the k in kmeans km = KMeans(n_clusters=nclusters) km.fit(x) y_cluster_kmeans = km.predict(x) score = metrics.silhouette_score(x, y_cluster_kmeans) print("PCA:", score) plt.scatter(x[0], x[1], c=y_cluster_kmeans, s=50, cmap='viridis') centers = km.cluster_centers_ plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, alpha=0.5); plt.show() # df2 = pd.DataFrame(data=x_pca) # finaldf = pd.concat([df2,dataset[['CREDIT_LIMIT']]],axis=1) # print(finaldf)
#Author: Nithin Prasasd #Date Created: 28/09/2019 #Program Name: palindrome_permutation.py #Program Description: (CTCI 1.4) Given a string, write a function to check if it is a # permutation of a palindrome (not limited to dictionary words). #Note: case of letters are irrelevant AND ignore non-letters! #Note: Function is of complexity: O(n) in time, O(1) in space def palindrome_permutation(str_in): str_in = str_in.lower() allowable_chars = list("abcdefghijklmnopqrstuvwxyz") dict_chars = {} onezie = False #Set to true if an odd count of characters is found. If more than # one odd count exists, the string cannot be a palindrome! #Collect counts of every character in word for char in str_in: if char in allowable_chars: if char in dict_chars.keys(): dict_chars[char] += 1 else: dict_chars[char] = 1 #Check if more than one onezie exists! for char in dict_chars.keys(): if dict_chars[char]%2 == 1: if onezie: return False else: onezie = True #A max of one onezie exists (one character of this set goes into the center of the # string, allowing all other characters, for which a pair exists to alternate # on either side of the string. Thus the remaining string is a palindrome! return True def palindrome_permutation_harness(func): print(func("")) #True print(func("lru")) #False print(func("obl!&bol")) #True print(func("obolLOOB")) #True print(func("oblo clb")) #True if __name__ == "__main__": palindrome_permutation_harness(palindrome_permutation)
#Author: Nithin Prasad #Date Created: 28/09/2019 #Program Name: one_away.py #Program Description: Given 2 strings, this program checks if they are one away (by # insert, remove or delete) #Note: spaces and non-alphabetic characters count, case does not! #Note: algorithm is of complexity O(n) in time, O(1) in space def one_away(str1, str2): str1 = str1.lower() str2 = str2.lower() len_diff = abs(len(str1)-len(str2)) len_max = max(len(str1),len(str2)) if len_diff > 1: #Fails if more than 1 away by remove or delete return False #Iterate through both strings by 1 char at a time. If unequality is reached # at a given index, advance the longest string's index by 1. #NOTE: here we handle inserts and removes identically (or agnostically) str_long = None str_short = None if len(str1) >= len(str2): str_long = str1 str_short = str2 else: str_long = str2 str_short = str1 i = 0 #points through str_L j = 0 #points through str_S mirrored = True #See if strings are a mirrored to any given iteration/index of loop #print("-------------------------------") #print("<"+str_long+">") #print("<"+str_short+">") #NOTE: length 0 strings while i < len(str_long) and j < len(str_short): char_long = str_long[i] char_short = str_short[j] if char_long != char_short: #characters seem different ... if mirrored: mirrored = False if len_diff == 0: #Increment for replacement i += 1 j += 1 else: #Increment for inserted string ONLY so that the next iteration, # we remember to check the new character in the long string with # the old one in the short string. i += 1 else: # 1 character was already different prior return False else: #characters are the same! i += 1 j += 1 return True def one_away_harness(func): print("Testing for function: ",func.__name__) print(func("","")) #True - base case print(func(" ","")) #True - base case print(func("a","")) #True - base case print(func("a","b")) #True print(func("a","ab")) #True print(func("ba","a")) #True print(func("abca","aca")) #True print(func("asdfasdf","asdfas")) #False print(func("asadaf","asabgf")) #False print(func("abdca","abua")) #False - 0 insert and mod, side by side if __name__ == "__main__": one_away_harness(one_away)
# 基于灰度的形态学的车牌定位: # 首先根据车牌区域中丰富的纹理特征,提取车牌图像中垂直方向的边缘并二值化。 # 然后对得到的二值图像进行数学形态学(膨胀、腐烛、幵闭运算等)的运算,使得车牌区域形成一个闭合的连通区域。 # 最后通过车牌的几何特征(高、宽、宽高比等)对得到的候选区域进行筛选,最终得到车牌图像。 import numpy as np import cv2 __GaussianKernelSize = 5 __closingKernelSize = np.ones((3, 17), np.uint8) __SobelOperatorSize = 3 ASPECT_RATIO = 44 / 14 # 中国车牌标准高宽比 AREA = 44 * 14 # 中国车牌标准面积 __maxRatio, __minRatio = ASPECT_RATIO * 1.7, ASPECT_RATIO * 0.8 __maxArea, __minArea = AREA * 20, AREA * 5 __maxAngle = 25 def setGaussianKernelSize(size): global __GaussianKernelSize __GaussianKernelSize = size def setClosingKernel(height, width): global __closingKernelSize __closingKernelSize = np.ones((height, width), np.uint8) def setSobelOperatorSize(size): global __SobelOperatorSize __SobelOperatorSize = size def setMinRatio(x): global __minRatio __minRatio = ASPECT_RATIO * x def setMaxRatio(x): global __maxRatio __maxRatio = ASPECT_RATIO * x def setMinArea(x): global __minArea __minArea = AREA * x def setMaxArea(x): global __maxArea __maxArea = AREA * x def setMaxAngle(angle): global __maxAngle __maxAngle = angle # 1.预处理:高斯模糊以减少噪点,灰度化以减少处理难度 def __preprocess(img): blur = cv2.GaussianBlur(img, (__GaussianKernelSize, __GaussianKernelSize), 0) gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) return gray # 2.提取边缘: # 用Sobel算子求X方向导数得竖直方向上边缘,并用Otsu(大津算法)二值化 def __extractEdge(img): edge = cv2.Sobel(img, cv2.CV_64F, 1, 0, __SobelOperatorSize) edge_abs = cv2.convertScaleAbs(edge) ret, binary = cv2.threshold(edge_abs, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return binary # 3.数学形态学运算:使得车牌区域形成一个闭合的连通区域 def __morphologicalOperate(img): close = cv2.morphologyEx(img, cv2.MORPH_CLOSE, __closingKernelSize) return close # 4.筛选: # 求连通区域的最小外接矩形,并从中筛选出符合车牌形状的矩形,最后将候选区域调整成统一形状以输出 def __screen(ori, binary): image, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) rois = [] for contour in contours: rect = cv2.minAreaRect(contour) # 返回的是Box2D结构:包含矩形某角点的坐标(x, y),矩形的宽和高(w, h),以及旋转角度 if __verify(rect): plate = __adjust(ori, rect) rois.append(plate) return rois # 调整函数:将符合条件的矩形区域进行旋转、缩放等,输出为统一尺寸 def __adjust(ori, rect): points = cv2.boxPoints(rect).astype(int).reshape(-1, 1, 2) for point in points: # 在points中找到左上角点坐标 if point[0][0] < rect[0][0] and point[0][1] < rect[0][1]: x, y = point[0][0], point[0][1] width, height, angle = int(rect[1][0]), int(rect[1][1]), rect[2] if width < height: width, height = height, width angle += 90 rows, cols = ori.shape[0], ori.shape[1] rotmat = cv2.getRotationMatrix2D((x, y), angle, 1) rotated = cv2.warpAffine(ori, rotmat, (cols, rows)) plate = cv2.resize(rotated[y:y + height, x:x + width], (136, 36)) # cv2和numpy索引方式不同 return plate # 验证函数:通过验证尺寸、高宽比和角度等判断矩形是否符合车牌形状 def __verify(rect): global __maxRatio, __minRatio, __maxArea, __minArea, __maxAngle area = rect[1][0] * rect[1][1] if area < __minArea or area > __maxArea: return False ratio = rect[1][0] / rect[1][1] angle = abs(rect[2]) if rect[1][0] < rect[1][1]: ratio = rect[1][1] / rect[1][0] angle = 90 - angle if __minRatio < ratio < __maxRatio and angle < __maxAngle: return True return False def plate_locate(img_address): ori = cv2.imread(img_address) gray = __preprocess(ori) binary = __extractEdge(gray) close = __morphologicalOperate(binary) rois = __screen(ori, close) cv2.imshow("ori", ori) cv2.imshow("edge", binary) cv2.imshow("close", close) for i in range(len(rois)): cv2.imshow(str(i), rois[i]) cv2.waitKey(0) # new_address = os.path.join(img_address, "plates", # img_address.split(".")[0] + "-" + str(i) + ".jpg") # cv2.imwrite(plate, new_address) if __name__ == "__main__": plate_locate(r"C:\Projects\PR\tests\1.jpg")
import os import sys sys.path.append('.') import numpy as np import pandas as pd import psycopg2 # Import survey data loading script from src.data.make_survey_dataset import load_data_as_dataframe ### ----- Set up project directory path names to load and save data ----- ### FILE_DIRECTORY = os.path.split(os.path.realpath(__file__))[0] SRC_DIRECTORY = os.path.split(FILE_DIRECTORY)[0] ROOT_DIRECTORY = os.path.split(SRC_DIRECTORY)[0] SENSITIVE_DATA_DIRECTORY = os.path.join(ROOT_DIRECTORY, '../SENSITIVE') class BuildSurveyFeatures(object): """ Vinyl Me, Please survey cleaning and featurizing class. Loads survey data from .csv, numerically encodes columns of interest, saves featurized DataFrame to .csv in secure directory outside of git repo. """ def __init__(self): """ Load survey data and create main DataFrame df and df_col_names.""" self.df, self.df_col_names = load_data_as_dataframe( filename='2019 Member Survey - Raw Data.csv') print(f"Loaded survey DataFrame of size {self.df.shape}.\n") def col_how_much_use_encode(self, data_frame, col_idx_list): """Featurizes pandas DataFrame columns. Numerically encodes the values in pandas DataFrame columns that answer the following question: How often do you use/interact with the following Vinyl Me, Please elements? - Survey columns 133-145 Args: data_frame: DataFrame with columns to be encoded. col_idx_list (list of int): Numerical indicies of the columns to be encoded. Returns: DataFrame column with values encoded via the 'use' dictionary below. """ use = {"I don't know about it": 0, "I don't care about it": 0, "Used it once": 1, "Sometimes": 2, "Frequently": 3} for col_idx in col_idx_list: # Filling NaN values with base case. data_frame.iloc[:, col_idx].fillna("I don't know about it", inplace=True) data_frame.iloc[:, col_idx] = [use[val] for val in data_frame.iloc[:,col_idx]] print(f"Encoded \"how much use\" columns: {col_idx_list}") def col_how_often_do_encode(self, data_frame, col_idx_list): """Featurizes pandas DataFrame columns. Numerically encodes the values in pandas DataFrame columns that answer the following question: How often you do these things? - Survey columns 415-420 Args: data_frame: DataFrame with columns to be encoded. col_idx_list (list of int): Numerical indicies of the columns to be encoded. Returns: DataFrame column with values encoded via the 'freq' dictionary below. """ freq = {'Hardly ever': 0, 'Every few months': 1, 'A few times a month': 2, 'About once a week': 3, 'Several times per week': 4, 'Every day': 5} for col_idx in col_idx_list: # Filling NaN values with base case. data_frame.iloc[:,col_idx].fillna("Hardly ever", inplace=True) data_frame.iloc[:,col_idx] = [freq[val] for val in data_frame.iloc[:,col_idx]] print(f"Encoded \"how often\" columns: {col_idx_list}") def col_how_long_records_encode(self, data_frame, col_idx_list=[33]): """Featurizes pandas DataFrame columns. Numerically encodes the values in pandas DataFrame columns that answer the following question: How long have you been buying records? - Survey column 33 Args: data_frame: DataFrame with columns to be encoded. col_idx_list (list of int): Numerical indicies of the columns to be encoded. Returns: DataFrame column with values encoded via the 'length' dictionary below. """ length = {'I just started': 0, '6 - 12 months': 0.5, '1-3 years': 1, '3-5 years': 1.5, '5-10 years': 2, '10-15 years': 2.5, 'More than 15 years': 3} for col_idx in col_idx_list: # Filling NaN values with base case. data_frame.iloc[:,col_idx].fillna('I just started', inplace=True) data_frame.iloc[:,col_idx] = [length[val] for val in data_frame.iloc[:,col_idx]] print(f"Encoded \"how long collect records\" column: {col_idx_list}") def encode_records_own(self, data_frame, col_idx=34): """Featurizes pandas DataFrame column. Numerically encodes (bins and normalizes) the values in pandas DataFrame columns that answer the following question: About how many records do you own? - Survey column 34 Args: data_frame: DataFrame with column to be encoded. col_idx (int): The numerical index of the column to be encoded. Returns: DataFrame column with values encoded on a scale of 0-5, binned to the nearest whole number, with values at the 90th percentile and up set to 5. """ # Filling NaN values with median number of records owned. median_num_owned = data_frame.iloc[:,col_idx].median() data_frame.iloc[:,col_idx].fillna(median_num_owned, inplace=True) # Setting max at 90th percentile of population to limit outliers. max_cutoff = np.percentile(data_frame.iloc[:,col_idx].to_numpy(), 90) data_frame.iloc[:,col_idx] = np.where( data_frame.iloc[:,col_idx] >= max_cutoff, max_cutoff, data_frame.iloc[:,col_idx]) data_frame.iloc[:,col_idx] = (data_frame.iloc[:,col_idx] / max_cutoff) * 5 data_frame.iloc[:,col_idx] = data_frame.iloc[:,col_idx].apply( lambda x: int(x)) print(f"Encoded \"how many records own\" column: {col_idx}") def col_binary_encode(self, data_frame, col_idx_list): """Featurizes pandas DataFrame column. Numerically encodes the values in pandas DataFrame columns that contain only two options (yes/no questions). Args: data_frame: DataFrame with columns to be encoded. col_idx_list (list of int): Numerical indicies of the columns to be encoded. Returns: DataFrame column with values encoded as follows: 'str(column title)' --> 1 anything else --> -1 """ for col_idx in col_idx_list: label = data_frame.columns.get_level_values(1)[col_idx] data_frame.iloc[:,col_idx] = data_frame.iloc[:,col_idx].apply( lambda x: 1 if (str(x) == str(label)) | (x == 1) else -1) print(f"Binary encoded columns: {col_idx_list}") def col_age_encode(self, data_frame, col_idx_list=[9]): """Featurizes pandas DataFrame column. Numerically encodes the values in pandas DataFrame columns that answer the following question: How old are you? - Survey column 9 Args: data_frame: DataFrame with columns to be encoded. col_idx_list (list of int): Numerical indicies of the columns to be encoded. Returns: DataFrame column with values encoded via the 'age' dict below. """ age = {'Under 18': 0, '18-20': 0.5, '21-24': 1, '25-34': 1.5, '35-44': 2, '45-54': 2.5, '55-64': 3, '65+': 3.5} for col_idx in col_idx_list: # Filling NaN values with most common age group. data_frame.iloc[:,col_idx].fillna('25-34', inplace=True) data_frame.iloc[:,col_idx] = [age[val] for val in data_frame.iloc[:,col_idx]] print(f"Encoded \"how old are you\" column: {col_idx}") def col_gender_encode(self, data_frame, col_idx_list=[10]): """Featurizes pandas DataFrame column. Numerically encodes the values in pandas DataFrame columns that answer the following question: To what gender do you identify? - Survey column 10 Args: data_frame: DataFrame with columns to be encoded. col_idx_list (list of int): Numerical indicies of the columns to be encoded. Returns: DataFrame column with values encoded as follows: Male --> 1 Female, Other --> 0 """ for col_idx in col_idx_list: data_frame.iloc[:,col_idx] = data_frame.iloc[:,col_idx].apply( lambda x: 1 if (str(x) == 'Male') else 0) print(f"Encoded \"gender identity\" column: {col_idx_list}") def col_records_month_encode(self, data_frame, col_idx_list=[36]): """Featurizes pandas DataFrame column. Numerically encodes the values in pandas DataFrame columns that answer the following question: About how many records do you buy per month? - Survey column 36 Args: data_frame: DataFrame with columns to be encoded. col_idx_list (list of int): Numerical indicies of the columns to be encoded. Returns: DataFrame column with values encoded via the 'record_nums' dictionary below. Note date-type formatting issue with source data. 0 - 1 --> 0-1 --> 0 3-Feb --> 2-3 --> 1 5-Apr --> 4-5 --> 2 10-Jun --> 6-10 --> 3 More than 10 --> More than 10 --> 4 """ record_nums = {'0 - 1': 0, '3-Feb': 1, '5-Apr': 2, '10-Jun': 3, 'More than 10': 4} for col_idx in col_idx_list: # Filling NaN values with base case (0-1 records/month). data_frame.iloc[:,col_idx].fillna('0 - 1', inplace=True) data_frame.iloc[:,col_idx] = [record_nums[num] for num in data_frame.iloc[:,col_idx]] print(f"Encoded \"records buy per month\" column: {col_idx_list}") def col_satisfy_encode(self, data_frame, col_idx_list): """Featurizes pandas DataFrame column. Numerically encodes the values in pandas DataFrame columns that answer the following question: How satisfied are you with the following? - Survey columns 125 - 132 Args: data_frame: DataFrame with columns to be encoded. col_idx_list (list of int): Numerical indicies of the columns to be encoded. Returns: DataFrame column with values encoded via the 'sentiment' dictionary below. """ sentiment = {'Very Satisfied': 2, 'Satisfied': 1, 'Neutral': 0, 'Dissatisfied': -1, 'Very Dissatsified': -2} for col_idx in col_idx_list: data_frame.iloc[:,col_idx].fillna('Neutral', inplace=True) data_frame.iloc[:,col_idx] = [sentiment[rating] for rating in data_frame.iloc[:,col_idx]] print(f"Encoded \"how satisfied are you\" columns: {col_idx_list}") def col_agree_encode(self, data_frame, col_idx_list): """Featurizes pandas DataFrame column. Numerically encodes the values in pandas DataFrame columns that answer the following question: How much do you agree with these statements? - Survey columns 180 - 216 Args: data_frame: DataFrame with columns to be encoded. col_idx_list (list of int): Numerical indicies of the columns to be encoded. Returns: DataFrame column with values encoded via the 'sentiment' dictionary below. """ sentiment = {'strongly agree': 2, 'agree': 1, 'neutral': 0, 'disagree': -1, 'strongly disagree': -2} for col_idx in col_idx_list: # Filling NaN values with base case 'Neutral'. data_frame.iloc[:,col_idx].fillna('Neutral', inplace=True) data_frame.iloc[:,col_idx] = [sentiment[str(rating).lower()] for rating in data_frame.iloc[:,col_idx]] print(f"Encoded \"how much agree\" columns: {col_idx_list}") def save_to_csv(self, data_frame, file_name='featurized_survey_data.csv'): """Saves DataFrame to .csv. Saves .csv to SENSITIVE_DATA_DIRECTORY, which must be located outside of any git repo due to Personally Identifiable Information (PII). Args: data_frame: DataFrame to be saved to .csv. file_name (str): Name of resulting .csv file. Returns: DataFrame saved as .csv to SENSITIVE_DATA_DIRECTORY. """ featurized_df_filepath = os.path.join(SENSITIVE_DATA_DIRECTORY, file_name) data_frame.to_csv(featurized_df_filepath, index=False) print(f"Saved featurized survey data to {featurized_df_filepath}.") if __name__ == '__main__': build_features = BuildSurveyFeatures() build_features.col_age_encode(build_features.df, col_idx_list=[9]) build_features.col_gender_encode(build_features.df, col_idx_list=[10]) encode_col_list = list(range(17, 33)) build_features.col_binary_encode(build_features.df, encode_col_list) build_features.col_how_long_records_encode(build_features.df, col_idx_list=[33]) build_features.encode_records_own(build_features.df, col_idx=34) build_features.col_records_month_encode(build_features.df, col_idx_list=[36]) agree_encode_col_list = list(range(63, 83)) build_features.col_agree_encode(build_features.df, agree_encode_col_list) encode_col_list = list(range(108, 120)) build_features.col_binary_encode(build_features.df, encode_col_list) satisfy_encode_col_list = list(range(125, 133)) build_features.col_satisfy_encode(build_features.df, satisfy_encode_col_list) how_much_use_encode_list = list(range(133, 146)) build_features.col_how_much_use_encode(build_features.df, how_much_use_encode_list) agree_encode_col_list = list(range(180, 217)) build_features.col_agree_encode(build_features.df, agree_encode_col_list) encode_col_list = list(range(406, 414)) build_features.col_binary_encode(build_features.df, encode_col_list) often_col_list = list(range(415, 422)) build_features.col_how_often_do_encode(build_features.df, often_col_list) build_features.save_to_csv(build_features.df, file_name='featurized_survey_data.csv')
#-*- coding:utf-8 -*- # 18) Seja a lista [3, 5, 1, 7, 2, 8, 11, -2, 3 -6, 0]. # Escreva um programa em Python que gere esta lista e apresente seus valores na ordem original e na ordem invertida. numbers = [3, 5, 1, 7, 2, 8, 11, -2, 3 -6, 0] print(numbers) print(numbers[::-1])
#-*- coding:utf-8 -*- # 8) Escreva um programa em Python que escreva na tela os números de 1 a 10. Use a estrutura de repetição for. numberList = [] for i in range(1,11): numberList.append(i) print(f'Lista: {numberList}')
#-*- coding:utf-8 -*- # 11) Escreva um programa em Python que leia repetidamente 5 números do teclado e indique, para cada, se é positivo. for i in range(1,6): number = int(input(f'Digite o {i}º número: ')) print(f'Número é {"positivo" if number >= 0 else "negativo"}.')
import pprint birthdays={'Austin':'April 30','Joseph':'August 8','Rozy':'June 04','Hawi':'September 25','Rosa':'October 10'} while True: print("Enter Your name:(Blank to quit)") name=input() if name=='': break if name in birthdays: print(birthdays[name]+" is the birthday of "+ name) else: print("I do not have birthday information for "+name) print("What is your birthday?") bday=input() birthdays[name]=bday print('Birthday database updated.') for a in birthdays.values(): print(a) for b in birthdays.keys(): print(b) for c in birthdays.items(): print (c) birthdays.setdefault('color','white') wewe=input('A sentence you like\n') wewe=wewe.strip() count={} for character in wewe: count.setdefault(character,0) count[character]=count[character]+1 pprint.pprint(count)
# This program says hello and asks for my name. print('Hello World!') print('What is Your Name?')#as for their name myName = input() print('it is Good to meetyou, ' + myName) print('the length of your name is:') print(len(myName)) print('What is Your age?')# ask for their age myAge = input() print('You will be ' +str(int(myAge) + 1) + ' in a year.') print("Enter you're best Interger") nt(s)=input() s=input() #print(int(s)) if myName=='Austin': print('You Have Such a Nice Name,'+myName) else: print("Si Ungeitwa Jina Ingine") if int(s)<9: print('Nice Choice of Interger') else: print('Chagua vitu Ndogo haitabadilishwa kuwa food') if myName=='Austin': print('Welcome,') elif int(myAge)>5: print('You"re not Austin, So we Ni?') else: print('Good Bye Hacker') i=0 while True: print("ERROR0077, You have just activated wanacry virus in you're system\nEnter you're email to stop the infection from spreading!!!") #mail=input() mail=[i] i=input() i=i+1 if i==5: break
#This is a guessing game. import random secretnumber=random.randint(1,10) print("I am thinking of a number between 1 AND 10") # ask the player to guess 5 time. for guesstaken in range(1,6): print('Take A guess.') guess=int(input()) if guess<secretnumber: print("The guess is too low.") elif guess>secretnumber: print("The Guess is Too High.") else: break #This condtion is the correct guess if guess == secretnumber: print("Good job! You guessed my number in "+ str(guesstaken) +" guesses") else: print("Nope. The number I was thinking of was "+ str(secretnumber))