text
stringlengths
37
1.41M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 23 22:59:00 2017 @author: habiba script that converts Celsius to Fahrenheit and creates a text file and stores the converted values inside the text file Write a program that converted Celsius degrees to Fahrenheit Consider the following list: temperatures=[10,-20,-289,100] The lowest possible temperature that physical matter can reach is -273.15 °C. Please don't write any message in the text file when input is lower than -273.15. """ t=[10,-20,-289,100] def writer (t): with open ("ctof file handling results .txt",'w') as file : for c in t : if c >-273.15: f=c*9/5+32 file.write(str(f)+"\n") writer(t)
import math #l=[1,2,None,None,None,8,10,9,None,None,8] def fillNone(num_list): #this function find where None value start and where end #and pass start and end index,None count to setMean function with list start_none=False count=0 for i in range(0,len(num_list)): if num_list[i]==None and start_none==False: start_index=i start_none=True count+=1 elif(num_list[i]==None and start_none==True): count+=1 continue elif(num_list[i]!=None and start_none==True): end_index=i-1 start_none=False setMean(num_list,start_index,end_index,count) #return start_index,end_index def setMean(num_list,start_index,end_index,count): '''this function take first and last None value index and put mean to all of them ''' f_num=num_list[start_index-1] l_num=num_list[end_index+1] diff=math.floor((l_num-f_num)/(count+1)) if l_num>f_num else -math.floor((f_num-l_num)/(count+1)) #print(f_num,l_num,diff) for i in range(start_index,end_index+1): num_list[i]=num_list[i-1]+diff #print(setNone(l)) #print(l)
salario = float(input('Quanto de salario voce ganha atualmente? R$')) a = salario + (salario * 15/100) print(f'O aumento salarial foi de 15%, entao voce recebera no proximo pagamento {a}')
dia = int(input('Quantos dias ficou com o carro?')) valor1 = dia * 60 km = float(input('Quantos km rodou desde que pegou o carro?')) valor2 = (km * 0.15) conta_final = valor1 + valor2 print(f'Por dias usados o valor fica em {valor1}R$, em km rodado {valor2:.0F}R$, voce precisa pagar {conta_final:.0F}R$')
def maybe_return_el_at_tuple(tupla: tuple, el): return tupla.index(el) def return_two_tuples(tupla: tuple): len_tuple = int(len(tupla)/2) return tupla[0:len_tuple], tupla[len_tuple:int(len_tuple*2)] def remove_el_tuple(tupla: tuple, el): lista = list(tupla) lista.remove(el) new_tuple = tuple(lista) return new_tuple def invert_tuple(tupla: tuple): return tupla[::-1] t = ("x", "y", 10, 20, "c", 11) first = maybe_return_el_at_tuple(t, 20) print(first) second = return_two_tuples(t) print(second) third = remove_el_tuple(t, "y") print(third) fourth = invert_tuple(t) print(fourth)
import requests from bs4 import BeautifulSoup import pandas as pd url = "https://fgopassos.github.io/pagina_exemplo/estadosCentroOeste.html" requisicao = requests.get(url) if requisicao.status_code != 200: requisicao.raise_for_status() else: print("Conectado com Sucesso") html = requisicao.text soup = BeautifulSoup(html, "lxml") def fix_quebra_linha(obj): return obj.text.replace('\n', '//')[2:-2].split('//') rows = [] title = [] for div_table in soup.find_all('div', class_='tabela'): for div_titulo in div_table.find_all('div', class_='titulo'): title.append(fix_quebra_linha(div_titulo)) for div_linha in div_table.find_all('div', class_='linha'): rows.append(fix_quebra_linha(div_linha)) data_frame = pd.DataFrame(data=rows, columns=title) result_a = data_frame.to_html(index=False) print(result_a) sigla_estado = input("Digite uma região: ") exist = False for row in rows: if sigla_estado.upper() in row[0]: exist = True print(row) break if not exist: print("Sigla não existe!")
""" Usando Python, faça o que se pede (código e printscreen) """ # a - Crie uma lista vazia list = [] # b - Adicione os elementos: 1, 2, 3, 4 e 5, usando append() list.append(1) list.append(2) list.append(3) list.append(4) list.append(5) # c - Imprima a lista; print(list) # d - Agora, remova os elementos 3 e 6 (não esqueça de checar se eles estão na lista); if(3 in list): list.remove(3) if(6 in list): list.remove(6) # e - Imprima a lista modificada; print(list) # f - Imprima também o tamanho da lista usando a função len(); len_list = len(list) print(len_list) # g - Altere o valor do último elemento para 6 e imprima a lista modificada. list[len_list - 1] = 6 print(list)
def potencia(a, b): return (a**b) n1 = int(input("insira um numero inteiro: ")) n2 = int(input("insira um numero inteiro: ")) if n1 and n2 >= 0: print('O resultado é', potencia(n1, n2)) else: print("Digite numeros inteiros positivos")
luna=[28,29,30,31] n=int(input("n=")) if n in luna: if n==luna[0]: print("Februarie") elif n==luna[2]: print("Aprilie,Iunie,Septembrie,Noiembrie") elif n==luna[3]: print("Ianuarie,Martie,Mai,Julie,August,Octombrie,Decembrie") elif (n==luna[1]): anul=int(input("anul:")) if anul%4==0: print("februarie") else: print("inexistent") else: print("inexistent")
#Written by Paul Wallace March 8th, 2016 class Writer: """ Method to write n (num_addresses) addresses to a new file while incrementing """ def writeAddresses(self, num_addresses, old_file_name, new_file_name): #initialize constants to avoid hard coding ONE = 1 TWO = 2 TWO_FIFTY_SIX = 256 try: with open(old_file_name) as curr_file: try: with open(new_file_name, "w") as new_file: for address in curr_file: (key, val) = address.split() #assume file is correct address_list = map(int, val.split('.')) #[1, 0, 0, 2] count = 0 #start a count to be checked to the num_addresses param for i in range(TWO_FIFTY_SIX): #outer loop if count == num_addresses: break # address_list[ONE] = i for j in range(TWO_FIFTY_SIX): #inner loop #increment then write to the file if count == num_addresses: break #reached param? address_list[TWO] = j string = key + ' ' + '.'.join(str(x) for x in address_list) + '\n' new_file.write(string) count += 1 except IOError: print "Unable to open file: ", new_file_name except IOError: print "Unable to read file:", old_file_name print "Please enter an existing file" writer = Writer() char = '' while(char != 'n'): print "Do you want to enter parameters or go with default? (e or d)" char = raw_input() if char == 'd': print "Running program..." writer.writeAddresses(1000, "addresses.txt" ,"new_addresses.txt") print "Program finished do you want to continue? (y or n)" char = raw_input() elif char == 'e': print "How many times do you want to increment each R* address?" n = raw_input() print "Please enter the read file" old_file = raw_input() print "Please enter the file to be written to" new_file = raw_input() print "Thank you, program is running..." writer.writeAddresses(n, old_file, new_file) print "Program is finished, do you want to continue? (y or n)" char = raw_input() else: print "Not a valid character" print "Thanks Pamela!"
sum = 0 for i in range(1,1000) : if(i%3==0 or i%5==0) : sum = sum + i print sum
from collections import Sized, Hashable, Iterable, Container class Vertex(object): """ Represent a Vertex of a Graph. Each Vertex has a name and may be connected to unlimited amount of other Vertices. """ name = None def __init__(self, name): super(Vertex, self).__init__() if not isinstance(name, Hashable): raise TypeError('Vertex name should be string or integer value.') self.name = name self.connections = {} def connect_to(self, vertex, weight=None, bidirectional=False): self.connections[vertex.name] = weight if bidirectional: vertex.connections[self.name] = weight def __repr__(self): return "Vertex({})".format(self.name) class Graph(Sized, Iterable, Container): """ Represents a Graph data structure which comprises a set of Vertices. May be directed (the connection between Vertices matters) or undirected. """ def __init__(self, undirected=True): self.vertices = {} self._undirected = undirected def add_vertex(self, name): vertex = Vertex(name) self.vertices[name] = vertex return vertex def add_edge(self, name_a, name_b, weight=None): if name_a == name_b: raise ValueError() vertex_a = self.vertices.get(name_a) or self.add_vertex(name_a) vertex_b = self.vertices.get(name_b) or self.add_vertex(name_b) vertex_a.connect_to(vertex_b, weight, self._undirected) def find_path(self, name_a, name_b): pass def dfs_paths(self, current_vertex, end_vertex, path=[]): path += [current_vertex] if current_vertex == end_vertex: yield path for adjacent_name in current_vertex.connections.keys(): adjacent = self.vertices[adjacent_name] if adjacent in path: continue # no turning back for p in self.dfs_paths(adjacent, end_vertex, path): yield p def lowest_weight(self, name_a, name_b): pass def shortest_way(self, name_a, name_b): pass def __iter__(self): for name, vertex in self.vertices.iteritems(): yield vertex def __contains__(self, name): return name in self.vertices def __len__(self): return len(self.vertices) def __repr__(self): vertices = ', '.join(map(str, self)) return "Graph({})".format(vertices) if __name__ == '__main__': g = Graph(undirected=True) g.add_edge('Lviv', 'Kiev', 540) g.add_edge('Lviv', 'Odessa', 600) g.add_edge('Kiev', 'Odessa', 700) g.add_edge('Kiev', 'Town', 100) g.add_edge('Town', 'Odessa', 200) g.add_edge('Lviv', 'A', 200) g.add_edge('Kiev', 'B', 200) g.add_edge('B', 'C', 200) g.dfs_paths(g.vertices['C'], g.vertices['A'])
from collections import defaultdict global time class Node: def __init__(self,name): self.name = name self.ChildNodes = [] self.predecessorNode = None self.start = 0 self.finish = 0 def DFS(Nodes,s): global time time = 0 for node_name in ['s','t','u', 'w', 'v', 'y', 'x', 'z']: #Nodes.keys(): if Nodes[node_name].start==0: DFS_visit(Nodes,node_name) def DFS_visit(Nodes,u): global time time = time+1 Nodes[u].start = time for node_name in Nodes[u].ChildNodes: if Nodes[node_name].start==0: Nodes[node_name].predecessorNode=u DFS_visit(Nodes,node_name) time+=1 Nodes[u].finish = time def printPath(Nodes,u,v): if u==v: print v, elif Nodes[v].predecessorNode==None: print 'No path from soure node '+ u +' to '+ v else: printPath(Nodes,u,Nodes[v].predecessorNode) print v, if __name__ == '__main__': ## directed graph # GraphMap= {'u':['v','x'],'v':['y'],'w':['z'],'x':['v'],'y':'x','z':['z']} GraphMap= {'y':['x'],'z':['y','w'],'s':['z','w'],'x':['z'],'w':['x'],'t':['v','u'],'v':['s','w'],'u':['t','v']} Nodes = dict() for node_name in GraphMap.keys(): Nodes[node_name]= Node(node_name) Nodes[node_name].ChildNodes=GraphMap[node_name] DFS(Nodes,'s') printPath(Nodes,'s','w') # for node_name in GraphMap.keys(): # print node_name,Nodes[node_name].start,Nodes[node_name].finish
"""annotator_distance.py - statistical significance of distance between genomic segments ===================================================================================== Purpose ------- The script :file:`annotator_distance.py` computes the statististical significance of the association between segments on a genome. The genome is arranged into ``workspaces``, contiguous blocks in the genome that are labeled at their termini. An example of workspaces are intergenic spaces labeled ``3'`` or ``5'`` according to the adjacent gene. Within the workspace are ``segments`` of interest, for example transcription factor binding sites. The script counts the distance of a segment to the nearest ``workspace`` terminus. The counts are aggregated over all workspaces. Next, the script randomly rearranges ``segments`` within a ``workspace`` in order to test the statistical significance of the observed counts. The script implements various sampling and counting methods. Usage ----- Type:: python annotator_distances.py --help for command line usage. Command line options -------------------- """ import os import sys import collections import itertools import CGAT.GTF as GTF import CGAT.Bed as Bed import CGAT.Intervals as Intervals import CGAT.IOTools as IOTools import CGAT.Experiment as E import bx.intervals.intersection import numpy import random import math import array import scipy import scipy.stats import matplotlib.pyplot as plt # global functions, defined once for optimization purposes normalize_transform = lambda x, y: numpy.array(x, float) / (sum(x) + y) cumulative_transform = lambda x, y: numpy.cumsum( numpy.array(x, float) / (sum(x) + y)) def readWorkspace(infile, workspace_builder="raw", label="none", map_id2annotation={}): """read workspace from infile. A workspace is a collection of intervals with two labels associated to each interval, one for the 5' and one for the 3' end. Available workspace builders are: gff take a gff file. gtf-intergenic build workspace from intergenic segments in a gtf file. gtf-intronic build workspace from intronic segments in a gtf file gtf-genic the workspace is built from genes (first to last exon). Available labels are: none no labels are given to the ends of workspaces direction labels are given based on the 5'/3' end of the bounding exon annotation labels are given based on a gene2annotation map. returns a list of segments for each contig in a dictionary """ if label == "none": label_f = lambda x, y: (("X",), ("X",)) info_f = lambda x: None elif label == "direction": label_f = lambda x, y: ((("5", "3")[x],), (("3", "5")[y],)) info_f = lambda x: x.strand == "+" elif label == "annotation": label_f = lambda x, y: (map_id2annotation[x], map_id2annotation[y]) info_f = lambda x: x.gene_id if workspace_builder == "gff": workspace = GTF.readAsIntervals(GFF.iterator(infile)) elif workspace_builder == "gtf-intergenic": workspace = collections.defaultdict(list) # get all genes for e in GTF.merged_gene_iterator(GTF.iterator(infile)): workspace[e.contig].append((e.start, e.end, info_f(e))) # convert to intergenic regions. # overlapping genes are merged and the labels # of the right-most entry is retained for contig in workspace.keys(): segs = workspace[contig] segs.sort() last = segs[0] new_segs = [] for this in segs[1:]: if last[1] >= this[0]: if this[1] > last[1]: last = (last[0], this[1], this[2]) continue assert last[1] < this[0], "this=%s, last=%s" % (this, last) new_segs.append((last[1], this[0], label_f(last[2], this[2]))) last = this workspace[contig] = new_segs elif workspace_builder == "gtf-intronic": workspace = collections.defaultdict(list) # the current procedure will count nested genes # twice for ee in GTF.flat_gene_iterator(GTF.iterator(infile)): exons = Intervals.combine([(e.start, e.end) for e in ee]) introns = Intervals.complement(exons) r = ee[0] for start, end in introns: workspace[r.contig].append((start, end, label_f(info_f(r), info_f(r)) )) elif workspace_builder == "gtf-genic": workspace = collections.defaultdict(list) # the current procedure will count nested genes # twice for ee in GTF.flat_gene_iterator(GTF.iterator(infile)): exons = Intervals.combine([(e.start, e.end) for e in ee]) start, end = exons[0][0], exons[-1][1] r = ee[0] workspace[r.contig].append((start, end, label_f(info_f(r), info_f(r)) )) else: raise ValueError("unknown workspace_builder %s" % workspace_builder) return workspace def readSegments(infile, indexed_workspace, truncate=False, format="gtf", keep_ambiguous=False, remove_overhangs=False): """read segments from infile. segments not overlapping with indexed_workspace are removed. If :attr: truncate is given, segments extending beyond the workspace are truncated. returns a list of segments for each contig in a dictionary """ counter = E.Counter() segments = collections.defaultdict(list) def addSegment(contig, start, end, counter): if contig in indexed_workspace: r = indexed_workspace[contig].find(start, end) if not r: counter.nskipped += 1 return if len(r) > 1: counter.nambiguous += 1 if not keep_ambiguous: return if truncate: for x in r: wstart, wend = x.start, x.end rstart, rend = max(start, wstart), min(end, wend) if start < wstart or end > wend: counter.ntruncated += 1 segments[contig].append((rstart, rend)) counter.added += 1 elif remove_overhangs: for x in r: wstart, wend = x.start, x.end rstart, rend = max(start, wstart), min(end, wend) if start < wstart or end > wend: counter.overhangs += 1 break else: segments[contig].append((start, end)) else: segments[contig].append((start, end)) counter.added += 1 counter.nkept += 1 if format == "gtf": gtf_iterator = GTF.flat_gene_iterator(GTF.iterator(infile)) for gene in gtf_iterator: # get start and end ignoring introns # contig, start, end = gene[0].contig, min( [x.start for x in gene] ), max( [x.end for x in gene] ) contig, coords = gene[0].contig, [(x.start, x.end) for x in gene] counter.ninput += 1 for start, end in coords: addSegment(contig, start, end, counter) elif format == "bed": bed_iterator = Bed.iterator(infile) for bed in bed_iterator: counter.ninput += 1 addSegment(bed.contig, bed.start, bed.end, counter) E.info("read segments: %s" % str(counter)) return segments class Sampler(object): """base clase for objcects that create a sample of randomly arranged segments in a workspace. """ def __init__(self, observed, work_start, work_end): self.mObserved = observed self.mWorkStart, self.mWorkEnd = work_start, work_end self.mLengths = [x[1] - x[0] for x in observed] self.mTotalLength = sum(self.mLengths) self.mFreeLength = work_end - work_start - self.mTotalLength assert self.mFreeLength >= 0, "negative length: workspace=(%i,%i) %i-%i<0, segments=%s, lengths=%s" % \ (work_start, work_end, work_end - work_start, self.mTotalLength, self.mObserved, self.mLengths) def sample(self): raise NotImplementedError("define sample() in base classes") class SamplerPermutation(Sampler): """permute order of fragments and distribute randomly. The permutation works like this: 1. Randomly permutate the order of segments 2. Split the free space (:attr:mFreeSpace) within the workspace into n+1 randomly sized gaps 3. Insert the gaps between permutated segments """ def sample(self): """return simulated fragments.""" simulated = [] # 1. permutate order of segments random.shuffle(self.mLengths) # 2. determine size of space between samples points = [] for x in range(len(self.mLengths) + 1): points.append(random.randint(0, self.mFreeLength)) points.sort() # 3. move segments to appropriate place start = self.mWorkStart simulated = [] last = 0 for x in range(len(self.mLengths)): start += points[x] - last simulated.append((start, start + self.mLengths[x])) start += self.mLengths[x] last = points[x] assert start + (points[-1] - last) <= self.mWorkEnd, "start=%i, points[-1]=%i, work_end=%i" % \ (start, points[-1] - last, self.mWorkEnd) return simulated class SamplerBlocks(Sampler): """move blocks of fragments to take into account clustering.""" def sample(self): """return simulated fragments.""" simulated = [] raise NotImplementedError class SamplerGaps(Sampler): """rearrange gaps within a block randomly. This sampler will preserve same of the clustering structure of segments.""" def __init__(self, *args, **kwargs): Sampler.__init__(self, *args, **kwargs) self.mGapLengths = [x[1] - x[0] for x in Intervals.complement(self.mObserved, self.mWorkStart, self.mWorkEnd)] def sample(self): """return simulated fragments.""" simulated = [] gaps = self.mGapLengths random.shuffle(gaps) start = self.mWorkStart for x in range(len(self.mLengths)): start += gaps[x] simulated.append((start, start + self.mLengths[x])) start += self.mLengths[x] return simulated class CountingResults(object): """a container for observed and simulated counts. """ def __init__(self, labels): self.mLabels = labels self.mTransform = None self.mEnvelopes = {} self.mMedians = {} self.mObservedCounts = None self.mSimulatedCounts = None self.mStats = None def updateFDR(self, obs_pvalues, sim_pvalues): """compute fdr stats with given counts. If obs_pvalues and sim_pvalues are given, computes the FDR (q-value) for the observed p-value. The q-value is the expected proportion of false positive observations at the observed p-value. qvalue = A / B A: average proportion of simulated data with P-Values < pvalue (expected false positive RATE) B: number of observed data with P-Values < pvalue (NUMBER of true positives) As there are several counters and labels, all observed and simulated pvalues are taken into account. The method needs to be called after :meth:update. """ assert self.mStats is not None, "updateFDR called before calling update." for label in self.mLabels: pvalue = self.mStats[label].pvalue a = scipy.stats.percentileofscore(sim_palues, pvalue) / 100.0 b = scipy.stats.percentileofscore( obs_pvalues, pvalue) / 100.0 * len(obs_pvalues) if b >= 0: qvalue = min(1.0, a / b) else: qvalue = 0 self.mStats[label] = self.mStats[label]._replace(qvalue=qvalue) def update(self): """update stats from given counts. """ assert self.mObservedCounts is not None, "update called without observed counts." assert self.mSimulatedCounts is not None, "update called without simulated counts." self.mStats = {} cls = collections.namedtuple( "st", "observed expected ci95lower ci95upper pvalue qvalue") for label in self.mLabels: obs = cumulative_transform( self.mObservedCounts[label], self.mObservedCounts.mOutOfBounds[label]) pobs = findMedian(obs) medians = self.getMedians(label) medians.sort() pvalue = float( scipy.stats.percentileofscore(medians, pobs)) / 100.0 self.mStats[label] = cls( pobs, scipy.mean(medians), scipy.stats.scoreatpercentile(medians, 5), scipy.stats.scoreatpercentile(medians, 95), pvalue, None) def getLabels(self): return self.mLabels def getMedians(self, label): """compute medians of all samples.""" if label not in self.mMedians: num_samples = len(self.mSimulatedCounts) medians = [] for x in range(num_samples): data = self.mSimulatedCounts[x][label] threshold = self.mSimulatedCounts[x].mTotals[label] / 2 t = 0 for d in range(len(data)): if t > threshold: break t += data[d] medians.append(d) self.mMedians[label] = medians return self.mMedians[label] def getEnvelope(self, label, transform): """compute envelope for label using transform. The envelope is the min, max and mean of the observed counts add a certain position. This function does a lazy evaluation. Pre-computed results are stored and returned if the same transform is applied. """ if label in self.mEnvelopes and transform == self.mTransform: E.debug("returning cached envelope for transform %s" % str(transform)) return self.mEnvelopes[label] E.debug("computing new envelope for transform %s" % str(transform)) num_samples = len(self.mSimulatedCounts) mmin = numpy.array(transform(self.mSimulatedCounts[0][ label], self.mSimulatedCounts[0].mOutOfBounds[label]), numpy.float) msum = numpy.array(transform(self.mSimulatedCounts[0][ label], self.mSimulatedCounts[0].mOutOfBounds[label]), numpy.float) mmax = numpy.array(transform(self.mSimulatedCounts[0][ label], self.mSimulatedCounts[0].mOutOfBounds[label]), numpy.float) for x in range(1, num_samples): v = transform( self.mSimulatedCounts[x][label], self.mSimulatedCounts[x].mOutOfBounds[label]) mmin = numpy.minimum(mmin, v) mmax = numpy.maximum(mmax, v) msum = msum + v msum /= num_samples self.mTransform = transform self.mEnvelopes[label] = (mmin, mmax, msum) return self.mEnvelopes[label] class Counter(object): """return object that counts segments in a workspace. A counter will implement an addCounts method that expects a sorted list of intervals within a region bounded by start,end. """ # python list is fastest for single value access, but requires a lot of # memory. python array is a good compromise - slightly slower than python list # but uses much less space. For range access, use numpy arrays. mBuildCounts = lambda self, num_bins, dtype: array.array( "I", [0] * num_bins) def __init__(self, labels, num_bins, resolution=1, dtype=numpy.int8): self.mCounts = {} self.mTotals = {} # keep separate out-of-bounds counts in order to not interfere with # dtype self.mOutOfBounds = {} b = self.mBuildCounts for l in labels: self.mCounts[l] = self.mBuildCounts(num_bins, dtype) self.mTotals[l] = 0 self.mOutOfBounds[l] = 0 self.mNumBins = num_bins self.mResolution = resolution def __getitem__(self, key): return self.mCounts[key] def getLabels(self): return self.mCounts.keys() def resolve(self, value): if self.mResolution > 1: return int(math.floor(float(value) / self.mResolution)) else: return value class CounterTranscription(Counter): """count transcription per base.""" mName = "Transcription" # numpy is fastest for counting with blocks of data mBuildCounts = lambda self, num_bins, dtype: numpy.zeros(num_bins, dtype) def addCounts(self, rr, start, end, left_labels, right_labels): counts = self.mCounts totals = self.mTotals ofb = self.mOutOfBounds nbins = self.mNumBins resolve = self.resolve for istart, iend in rr: l = iend - istart dl = istart - start dr = end - iend l = self.resolve(l) if dl < dr: pos = self.resolve(dl) labels = left_labels elif dl > dr: pos = self.resolve(dr) labels = right_labels else: continue if pos >= nbins: for label in labels: ofb[label] += l totals[label] += l else: for label in labels: counts[label][pos:pos + l] += 1 totals[label] += l class CounterClosestDistance(Counter): """count closest distance.""" mName = "Closest distance" def addCounts(self, rr, start, end, left_labels, right_labels): counts = self.mCounts totals = self.mTotals ofb = self.mOutOfBounds nbins = self.mNumBins resolve = self.resolve def __add(pos, labels): if pos >= nbins: for label in labels: self.mOutOfBounds[label] += 1 totals[label] += 1 else: for label in labels: counts[label][pos] += 1 totals[label] += 1 pos = self.resolve(rr[0][0] - start) __add(pos, left_labels) pos = self.resolve(end - rr[-1][1]) __add(pos, right_labels) class CounterAllDistances(Counter): """count all distances.""" mName = "All distances" def addCounts(self, rr, start, end, left_labels, right_labels): counts = self.mCounts totals = self.mTotals ofb = self.mOutOfBounds nbins = self.mNumBins resolve = self.resolve for istart, iend in rr: dl = istart - start dr = end - iend if dl < dr: pos = resolve(dl) labels = left_labels elif dl > dr: pos = resolve(dr) labels = right_labels else: continue if pos >= nbins: for label in labels: ofb[label] += 1 totals[label] += 1 else: for label in labels: counts[label][pos] += 1 totals[label] += 1 def indexIntervals(intervals, with_values=False): """index intervals using bx. """ indexed = {} for contig, values in intervals.iteritems(): intersector = bx.intervals.intersection.Intersecter() if with_values: for start, end, value in values: intersector.add_interval( bx.intervals.Interval(start, end, value=value)) else: for start, end in values: intersector.add_interval(bx.intervals.Interval(start, end)) indexed[contig] = intersector return indexed def plotCounts(counter, options, transform=lambda x: x): """create plots from counter.""" num_bins = options.num_bins resolution = options.resolution bins = numpy.array(xrange(num_bins)) * resolution for label in counter.getLabels(): fig = plt.figure() if options.plot_samples: for x in range(options.num_samples): counts = transform(counter.mSimulatedCounts[x][ label], counter.mSimulatedCounts[x].mOutOfBounds[label]) plt.plot(bins, counts / t, label="sample_%i" % x) if options.plot_envelope: # counts per sample are in row mmin, mmax, mmean = counter.getEnvelope(label, transform) plt.plot(bins, mmin, label="min") plt.plot(bins, mmax, label="max") plt.plot(bins, mmean, label="mean") plt.plot(bins, transform(counter.mObservedCounts[ label], counter.mObservedCounts.mOutOfBounds[label]), label="observed") plt.xlim(options.xrange) plt.legend() plt.title(counter.mName) plt.xlabel("distance from gene / bp") plt.ylabel("frequency") fig.suptitle(str(label)) if options.logscale: if "x" in options.logscale: plt.gca().set_xscale('log') if "y" in options.logscale: plt.gca().set_yscale('log') if options.hardcopy: plt.savefig(os.path.expanduser(options.hardcopy % label)) def findMedian(dist): """find median in cumulative and normalized distribution.""" x = 0 while dist[x] < 0.5: x += 1 return x def main(argv=sys.argv): parser = E.OptionParser( version="%prog version: $Id: annotator_distance.py 2861 2010-02-23 17:36:32Z andreas $", usage=globals()["__doc__"]) parser.add_option("-a", "--annotations-tsv-file", dest="filename_annotations", type="string", help="filename mapping gene ids to annotations (a tab-separated table with two-columns) [default=%default].") parser.add_option("-r", "--resolution", dest="resolution", type="int", help="resolution of count vector [default=%default].") parser.add_option("-b", "--num-bins", dest="num_bins", type="int", help="number of bins in count vector [default=%default].") parser.add_option("-i", "--num-samples", dest="num_samples", type="int", help="sample size to compute [default=%default].") parser.add_option("-w", "--workspace-bed-file", dest="filename_workspace", type="string", help="filename with workspace information [default=%default].") parser.add_option("--workspace-builder", dest="workspace_builder", type="choice", choices=( "gff", "gtf-intergenic", "gtf-intronic", "gtf-genic"), help="given a gff/gtf file build a workspace [default=%default].") parser.add_option("--workspace-labels", dest="workspace_labels", type="choice", choices=("none", "direction", "annotation"), help="labels to use for the workspace workspace [default=%default].") parser.add_option("--sampler", dest="sampler", type="choice", choices=("permutation", "gaps"), help="sampler to use. The sampler determines the null model of how segments are distributed in the workspace [default=%default]") parser.add_option("--counter", dest="counters", type="choice", action="append", choices=( "transcription", "closest-distance", "all-distances"), help="counter to use. The counter computes the quantity of interest [default=%default]") parser.add_option("--analysis", dest="analysis", type="choice", action="append", choices=("proximity", "area-under-curve"), help="analysis to perform [default=%default]") parser.add_option("--transform-counts", dest="transform_counts", type="choice", choices=("raw", "cumulative"), help="cumulate counts [default=%default].") parser.add_option("-s", "--segments", dest="filename_segments", type="string", help="filename with segment information [default=%default].") parser.add_option("--xrange", dest="xrange", type="string", help="xrange to plot [default=%default]") parser.add_option("-o", "--logscale", dest="logscale", type="string", help="use logscale on x, y or xy [default=%default]") parser.add_option("-p", "--plot", dest="plot", action="store_true", help="output plots [default=%default]") parser.add_option("--hardcopy", dest="hardcopy", type="string", help="output hardcopies to file [default=%default]") parser.add_option("--no-fdr", dest="do_fdr", action="store_false", help="do not compute FDR rates [default=%default]") parser.add_option("--segments-format", dest="segments_format", type="choice", choices=("gtf", "bed"), help="format of segments file [default=%default].") parser.add_option("--truncate", dest="truncate", action="store_true", help="truncate segments extending beyond a workspace [default=%default]") parser.add_option("--remove-overhangs", dest="remove_overhangs", action="store_true", help="remove segments extending beyond a workspace[default=%default]") parser.add_option("--keep-ambiguous", dest="keep_ambiguous", action="store_true", help="keep segments extending to more than one workspace [default=%default]") parser.set_defaults( filename_annotations=None, filename_workspace="workspace.gff", filename_segments="FastDown.gtf", filename_annotations_gtf="../data/tg1_territories.gff", workspace_builder="gff", workspace_labels="none", sampler="permutation", truncate=False, num_bins=10000, num_samples=10, resolution=100, plot_samples=False, plot_envelope=True, counters=[], transform_counts="raw", xrange=None, plot=False, logscale=None, output_all=False, do_test=False, analysis=[], do_fdr=True, hardcopy="%s.png", segments_format="gtf", remove_overhangs=False, ) (options, args) = E.Start(parser, argv=argv, add_output_options=True) ########################################### # setup options if options.sampler == "permutation": sampler = SamplerPermutation elif options.sampler == "gaps": sampler = SamplerGaps if options.xrange: options.xrange = map(float, options.xrange.split(",")) if len(options.counters) == 0: raise ValueError("please specify at least one counter.") if len(options.analysis) == 0: raise ValueError("please specify at least one analysis.") if options.workspace_labels == "annotation" and not options.filename_annotations: raise ValueError( "please specify --annotations-tsv-file is --workspace-labels=annotations.") ########################################### # read data if options.workspace_labels == "annotation": def constant_factory(value): return itertools.repeat(value).next def dicttype(): return collections.defaultdict(constant_factory(("unknown",))) map_id2annotations = IOTools.readMultiMap(open(options.filename_annotations, "r"), dtype=dicttype) else: map_id2annotations = {} workspace = readWorkspace(open(options.filename_workspace, "r"), options.workspace_builder, options.workspace_labels, map_id2annotations) E.info("read workspace for %i contigs" % (len(workspace))) indexed_workspace = indexIntervals(workspace, with_values=True) segments = readSegments(open(options.filename_segments, "r"), indexed_workspace, format=options.segments_format, keep_ambiguous=options.keep_ambiguous, truncate=options.truncate, remove_overhangs=options.remove_overhangs) nsegments = 0 for contig, vv in segments.iteritems(): nsegments += len(vv) E.info("read %i segments for %i contigs" % (nsegments, len(workspace))) indexed_segments = indexIntervals(segments, with_values=False) if nsegments == 0: E.warn("no segments read - no computation done.") E.Stop() return # build labels labels = collections.defaultdict(int) for contig, vv in workspace.iteritems(): for start, end, v in vv: for l in v[0]: labels[l] += 1 for l in v[1]: labels[l] += 1 E.info("found %i workspace labels" % len(labels)) ########################################### # setup counting containers counters = [] for cc in options.counters: if cc == "transcription": counter = CounterTranscription elif cc == "closest-distance": counter = CounterClosestDistance elif cc == "all-distances": counter = CounterAllDistances if nsegments < 256: dtype = numpy.uint8 elif nsegments < 65536: dtype = numpy.uint16 elif nsegments < 4294967296: dtype = numpy.uint32 else: dtype = numpy.int E.debug("choosen dtype %s" % str(dtype)) E.info("samples space is %i bases: %i bins at %i resolution" % (options.num_bins * options.resolution, options.num_bins, options.resolution, )) E.info("allocating counts: %i bytes (%i labels, %i samples, %i bins)" % (options.num_bins * len(labels) * dtype().itemsize * (options.num_samples + 1), len(labels), options.num_samples, options.num_bins, )) c = CountingResults(labels) c.mObservedCounts = counter( labels, options.num_bins, options.resolution, dtype=dtype) simulated_counts = [] for x in range(options.num_samples): simulated_counts.append( counter(labels, options.num_bins, options.resolution, dtype=dtype)) c.mSimulatedCounts = simulated_counts c.mName = c.mObservedCounts.mName counters.append(c) E.info("allocated memory successfully") segments_per_workspace = [] segment_sizes = [] segments_per_label = collections.defaultdict(int) workspaces_per_label = collections.defaultdict(int) ############################################ # get observed and simpulated counts nworkspaces, nempty_workspaces, nempty_contigs, nmiddle = 0, 0, 0, 0 iteration2 = 0 for contig, vv in workspace.iteritems(): iteration2 += 1 E.info("counting %i/%i: %s %i segments" % (iteration2, len(workspace), contig, len(vv))) if len(vv) == 0: continue iteration1 = 0 for work_start, work_end, v in vv: left_labels, right_labels = v[0], v[1] iteration1 += 1 # ignore empty segments if contig not in indexed_segments: nempty_contigs += 1 continue r = indexed_segments[contig].find(work_start, work_end) segments_per_workspace.append(len(r)) if not r: nempty_workspaces += 1 continue # collect segments and stats nworkspaces += 1 observed = [(x.start, x.end) for x in r] observed.sort() segments_per_workspace.append(len(observed)) segment_sizes.extend([x[1] - x[0] for x in observed]) # collect basic counts for label in list(left_labels) + list(right_labels): workspaces_per_label[label] += 1 segments_per_label[label] += len(observed) # add observed counts for counter in counters: counter.mObservedCounts.addCounts( observed, work_start, work_end, left_labels, right_labels) # create sampler s = sampler(observed, work_start, work_end) # add simulated counts for iteration in range(options.num_samples): simulated = s.sample() for counter in counters: counter.mSimulatedCounts[iteration].addCounts( simulated, work_start, work_end, left_labels, right_labels) E.info("counting finished") E.info("nworkspaces=%i, nmiddle=%i, nempty_workspaces=%i, nempty_contigs=%i" % (nworkspaces, nmiddle, nempty_workspaces, nempty_contigs)) ###################################################### # transform counts if options.transform_counts == "cumulative": transform = cumulative_transform elif options.transform_counts == "raw": transform = normalize_transform #################################################### # analysis if "proximity" in options.analysis: outfile_proximity = E.openOutputFile("proximity") outfile_proximity.write("\t".join(("label", "observed", "pvalue", "expected", "CIlower", "CIupper", "qvalue", "segments", "workspaces")) + "\n") else: outfile_proximity = None if "area-under-curve" in options.analysis: outfile_auc = E.openOutputFile("auc") outfile_auc.write("label\tobserved\texpected\tCIlower\tCIupper\n") else: outfile_auc = None # qvalue: expected false positives at p-value # qvalue = expected false positives / if options.do_fdr: E.info("computing pvalues for fdr") for counter in counters: for label in labels: E.info("working on counter:%s label:%s" % (counter, label)) # collect all P-Values of simulated results to compute FDR sim_pvalues = [] medians = counter.getMedians(label) for median in medians: pvalue = float( scipy.stats.percentileofscore(medians, median)) / 100.0 sim_pvalues.append(pvalue) sim_pvalues.sort() else: sim_pvalues = [] # compute observed p-values for counter in counters: counter.update() obs_pvalues = [] for counter in counters: for label in labels: obs_pvalues.append(counter.mStats[label].pvalue) obs_pvalues.sort() # compute observed p-values if options.do_fdr: for counter in counters: counter.updateFDR(obs_pvalues, sim_pvalues) for counter in counters: outofbounds_sim, totals_sim = 0, 0 outofbounds_obs, totals_obs = 0, 0 for label in labels: for sample in range(options.num_samples): if counter.mSimulatedCounts[sample].mOutOfBounds[label]: E.debug("out of bounds: sample %i, label %s, counts=%i" % (sample, label, counter.mSimulatedCounts[sample].mOutOfBounds[label])) outofbounds_sim += counter.mSimulatedCounts[ sample].mOutOfBounds[label] totals_sim += counter.mSimulatedCounts[sample].mTotals[label] outofbounds_obs += counter.mObservedCounts.mOutOfBounds[label] totals_obs += counter.mObservedCounts.mTotals[label] E.info("out of bounds observations: observed=%i/%i (%5.2f%%), simulations=%i/%i (%5.2f%%)" % (outofbounds_obs, totals_obs, 100.0 * outofbounds_obs / totals_obs, outofbounds_sim, totals_sim, 100.0 * outofbounds_sim / totals_sim, )) for label in labels: if outfile_auc: mmin, mmax, mmean = counter.getEnvelope( label, transform=normalize_transform) obs = normalize_transform( counter.mObservedCounts[label], counter.mObservedCounts.mOutOfBounds[label]) def block_iterator(a1, a2, a3, num_bins): x = 0 while x < num_bins: while x < num_bins and a1[x] <= a2[x]: x += 1 start = x while x < options.num_bins and a1[x] > a2[x]: x += 1 end = x total_a1 = a1[start:end].sum() total_a3 = a3[start:end].sum() if total_a1 > total_a3: yield (total_a1 - total_a3, start, end, total_a1, total_a3) blocks = list( block_iterator(obs, mmax, mmean, options.num_bins)) if options.output_all: for delta, start, end, total_obs, total_mean in blocks: if end - start <= 1: continue outfile_auc.write("%s\t%i\t%i\t%i\t%f\t%f\t%f\t%f\t%f\n" % (label, start * options.resolution, end * options.resolution, (end - start) * options.resolution, total_obs, total_mean, delta, total_obs / total_mean, 100.0 * (total_obs / total_mean - 1.0))) # output best block blocks.sort() delta, start, end, total_obs, total_mean = blocks[-1] outfile_auc.write("%s\t%i\t%i\t%i\t%f\t%f\t%f\t%f\t%f\n" % (label, start * options.resolution, end * options.resolution, (end - start) * options.resolution, total_obs, total_mean, delta, total_obs / total_mean, 100.0 * (total_obs / total_mean - 1.0))) if outfile_proximity: # find error bars at median st = counter.mStats[label] outfile_proximity.write("%s\t%i\t%f\t%i\t%i\t%i\t%s\t%i\t%i\n" % (label, st.observed * options.resolution, st.pvalue, st.expected * options.resolution, st.ci95lower * options.resolution, st.ci95upper * options.resolution, IOTools.val2str(st.qvalue), segments_per_label[label], workspaces_per_label[label], )) if options.plot: for counter in counters: plotCounts(counter, options, transform) # plot summary stats plt.figure() plt.title("distribution of workspace length") data = [] for contig, segs in workspace.iteritems(): if len(segs) == 0: continue data.extend([x[1] - x[0] for x in segs]) vals, bins = numpy.histogram( data, bins=numpy.arange(0, max(data), 100), new=True) t = float(sum(vals)) plt.plot(bins[:-1], numpy.cumsum(vals) / t) plt.gca().set_xscale('log') plt.legend() t = float(sum(vals)) plt.xlabel("size of workspace") plt.ylabel("cumulative relative frequency") if options.hardcopy: plt.savefig( os.path.expanduser(options.hardcopy % "workspace_size")) plt.figure() plt.title("segments per block") vals, bins = numpy.histogram(segments_per_workspace, bins=numpy.arange( 0, max(segments_per_workspace), 1), new=True) plt.plot(bins[:-1], vals) plt.xlabel("segments per block") plt.ylabel("absolute frequency") if options.hardcopy: plt.savefig( os.path.expanduser(options.hardcopy % "segments_per_block")) plt.figure() plt.title("workspaces per label") plt.barh( range(0, len(labels)), [workspaces_per_label[x] for x in labels], height=0.5) plt.yticks(range(0, len(labels)), labels) plt.ylabel("workspaces per label") plt.xlabel("absolute frequency") plt.gca().set_xscale('log') if options.hardcopy: plt.savefig( os.path.expanduser(options.hardcopy % "workspaces_per_label")) plt.figure() plt.title("segments per label") plt.barh(range(0, len(labels)), [segments_per_label[x] for x in labels], height=0.5) plt.yticks(range(0, len(labels)), labels) plt.ylabel("segments per label") plt.xlabel("absolute frequency") plt.xticks(range(0, len(labels)), labels) if options.hardcopy: plt.savefig( os.path.expanduser(options.hardcopy % "segments_per_label")) if not options.hardcopy: plt.show() E.Stop() if __name__ == "__main__": sys.exit(main())
''' r_table2scatter.py - R based plots and stats ============================================ :Author: Andreas Heger :Release: $Id$ :Date: |today| :Tags: Python Purpose ------- This script reads a table from a file or stdin. It can compute various stats (correlations, ...) and/or plot the data using R. Usage ----- Example:: python r_table2scatter.py --help Type:: python r_table2scatter.py --help for command line help. Command line options -------------------- ''' import os import sys import string import re import tempfile import math import code import CGAT.Experiment as E import CGAT.MatlabTools as MatlabTools import numpy import CGAT.Stats as Stats from rpy2.robjects import r as R def readTable(lines, assign, separator="\t", numeric_type=numpy.float, take_columns="all", headers=True, row_names=None, colours=None, ): """read a matrix. There probably is a routine for this in Numpy, which I haven't found yet. The advantage of using rpy's mechanism is to allow for missing values. row_names: column with row names """ # now import R as stdin has been read. take = take_columns handle, name = tempfile.mkstemp() os.close(handle) if take_columns == "all": num_cols = len(string.split(lines[0][:-1], "\t")) take = range(0, num_cols) elif take_columns == "all-but-first": num_cols = len(string.split(lines[0][:-1], "\t")) take = range(1, num_cols) outfile = open(name, "w") c = [] # delete columns with colour information/legend to_delete = [] if row_names is not None: legend = [] if take_columns == "all": to_delete.append(row_names) else: legend = None if colours is not None: if take_columns == "all": to_delete.append(colours) to_delete.sort() to_delete.reverse() for x in to_delete: del take[x] # get column headers if headers: headers = lines[0][:-1].split("\t") headers = map(lambda x: headers[x], take) del lines[0] for l in lines: data = [x.strip() for x in l[:-1].split("\t")] if not data or not [x for x in data if x != ""]: continue outfile.write(string.join(map(lambda x: data[x], take), "\t") + "\n") if row_names is not None: legend.append(data[row_names]) if colours is not None: c.append(data[colours]) outfile.close() # rpy.set_default_mode(rpy.NO_CONVERSION) # note that the conversion # is not perfect. Some missing values are assigned to "nan", while # some are -2147483648. They seem to treated correctly, though, # within R, but note that when computing something like sum(), the # result in python after conversion might be -2147483648. if headers: matrix = R("""%s <- read.table( '%s', na.string = c("NA", "na", 'nan', 'NaN'), col.names=c('%s'), sep="\t" )""" % (assign, name, "','".join(headers))) else: matrix = R( """%s <- read.table( '%s', na.string = c("NA", "na", 'nan', 'NaN'), col.names=headers, sep="\t" )""" % (assign, name)) # rpy.set_default_mode(rpy.BASIC_CONVERSION) os.remove(name) return matrix, headers, c, legend def writeMatrix(file, matrix, separator="\t", headers=[], format="%f"): """write a matrix to file. if headers are given, add them to columns and rows. """ if headers: file.write("\t" + string.join(headers, "\t") + "\n") nrows, ncols = matrix.shape for x in range(nrows): if headers: file.write(headers[x] + "\t") file.write( string.join(map(lambda x: format % x, matrix[x]), "\t") + "\n") def FuncScatterDiagonal(data): R.points(data) R.abline(0, 1) def main(argv=None): if argv is None: argv = sys.argv parser = E.OptionParser( version="%prog version: $Id: r_table2scatter.py 2782 2009-09-10 11:40:29Z andreas $") parser.add_option("-c", "--columns", dest="columns", type="string", help="columns to take from table. Choices are 'all', 'all-but-first' or a ','-separated list of columns.") parser.add_option("--logscale", dest="logscale", type="string", help="log-transform one or both axes [default=%Default].") parser.add_option("-a", "--hardcopy", dest="hardcopy", type="string", help="write hardcopy to file [default=%default].", metavar="FILE") parser.add_option("-f", "--file", dest="input_filename", type="string", help="filename with table data [default=%default].", metavar="FILE") parser.add_option("-2", "--file2", dest="input_filename2", type="string", help="additional data file [default=%default].", metavar="FILE") parser.add_option("-s", "--stats", dest="statistics", type="choice", choices=("correlation", "spearman", "pearson", "count"), help="statistical quantities to compute [default=%default]", action="append") parser.add_option("-p", "--plot", dest="plot", type="choice", choices=("scatter", "pairs", "panel", "bar", "bar-stacked", "bar-besides", "1_vs_x", "matched", "boxplot", "scatter+marginal", "scatter-regression"), help="plots to plot [default=%default]", action="append") parser.add_option("-t", "--threshold", dest="threshold", type="float", help="min threshold to use for counting method [default=%default].") parser.add_option("-o", "--colours", dest="colours", type="int", help="column with colour information [default=%default].") parser.add_option("-l", "--plot-labels", dest="labels", type="string", help="column labels for x and y in matched plots [default=%default].") parser.add_option("-d", "--add-diagonal", dest="add_diagonal", action="store_true", help="add diagonal to plot [default=%default].") parser.add_option("-e", "--plot-legend", dest="legend", type="int", help="column with legend [default=%default].") parser.add_option("-r", "--options", dest="r_options", type="string", help="R plotting options [default=%default].") parser.add_option("--format", dest="format", type="choice", choices=("full", "sparse"), help="output format [default=%default].") parser.add_option("--title", dest="title", type="string", help="""plot title [default=%default].""") parser.add_option("", "--xrange", dest="xrange", type="string", help="x viewing range of plot [default=%default].") parser.add_option("", "--yrange", dest="yrange", type="string", help="y viewing range of plot[default=%default].") parser.add_option("--allow-empty-file", dest="fail_on_empty", action="store_false", help="do not fail on empty input [default=%default].") parser.add_option("--fail-on-empty", dest="fail_on_empty", action="store_true", help="fail on empty input [default=%default].") parser.set_defaults( hardcopy=None, input_filename="", input_filename2=None, columns="all", logscale=None, statistics=[], plot=[], threshold=0.0, labels="x,y", colours=None, diagonal=False, legend=None, title=None, xrange=None, yrange=None, r_options="", fail_on_empty=True, format="full") (options, args) = E.Start(parser) if len(args) == 1 and not options.input_filename: options.input_filename = args[0] if options.columns not in ("all", "all-but-first"): options.columns = map(lambda x: int(x) - 1, options.columns.split(",")) if options.colours: options.colours -= 1 if options.legend: options.legend -= 1 table = {} headers = [] # read data matrix if options.input_filename: lines = open(options.input_filename, "r").readlines() else: # note: this will not work for interactive viewing, but # creating hardcopy plots works. lines = sys.stdin.readlines() lines = filter(lambda x: x[0] != "#", lines) if len(lines) == 0: if options.fail_on_empty: raise IOError("no input") E.warn("empty input") E.Stop() return matrix, headers, colours, legend = readTable(lines, "matrix", take_columns=options.columns, headers=True, colours=options.colours, row_names=options.legend) if options.input_filename2: # read another matrix (should be of the same format. matrix2, headers2, colours2, legend2 = readTable( lines, "matrix2", take_columns=options.columns, headers=True, colours=options.colours, row_names=options.legend) R.assign("headers", headers) ndata = R("""length( matrix[,1] )""")[0] if options.loglevel >= 1: options.stdlog.write("# read matrix: %ix%i\n" % (len(headers), ndata)) if colours: R.assign("colours", colours) for method in options.statistics: if method == "correlation": cor = R.cor(matrix, use="pairwise.complete.obs") writeMatrix(sys.stdout, cor, headers=headers, format="%5.2f") elif method == "pearson": options.stdout.write("\t".join(("var1", "var2", "coeff", "passed", "pvalue", "n", "method", "alternative")) + "\n") for x in range(len(headers) - 1): for y in range(x + 1, len(headers)): try: result = R( """cor.test( matrix[,%i], matrix[,%i] )""" % (x + 1, y + 1)) except rpy.RPyException, msg: E.warn("correlation not computed for columns %i(%s) and %i(%s): %s" % ( x, headers[x], y, headers[y], msg)) options.stdout.write("%s\t%s\t%s\t%s\t%s\t%i\t%s\t%s\n" % (headers[x], headers[y], "na", "na", "na", 0, "na", "na")) else: options.stdout.write( "%s\t%s\t%6.4f\t%s\t%e\t%i\t%s\t%s\n" % (headers[x], headers[y], result.rx2('estimate').rx2( 'cor')[0], Stats.getSignificance( float(result.rx2('p.value')[0])), result.rx2('p.value')[0], result.rx2('parameter').rx2( 'df')[0], result.rx2('method')[0], result.rx2('alternative')[0])) elif method == "spearman": options.stdout.write("\t".join(("var1", "var2", "coeff", "passed", "pvalue", "method", "alternative")) + "\n") for x in range(len(headers) - 1): for y in range(x + 1, len(headers)): result = R( """cor.test( matrix[,%i], matrix[,%i], method='spearman')""" % (x + 1, y + 1)) options.stdout.write( "%s\t%s\t%6.4f\t%s\t%e\t%i\t%s\t%s\n" % (headers[x], headers[y], result['estimate']['rho'], Stats.getSignificance(float(result['p.value'])), result['p.value'], result['parameter']['df'], result['method'], result['alternative'])) elif method == "count": # number of shared elements > threshold m, r, c = MatlabTools.ReadMatrix(open(options.input_filename, "r"), take=options.columns, headers=True) mask = numpy.greater(m, options.threshold) counts = numpy.dot(numpy.transpose(mask), mask) writeMatrix(options.stdout, counts, headers=c, format="%i") if options.plot: # remove columns that are completely empty if "pairs" in options.plot: colsums = R('''colSums( is.na(matrix ))''') take = [x for x in range(len(colsums)) if colsums[x] != ndata] if take: E.warn("removing empty columns %s before plotting" % str(take)) matrix = R.subset(matrix, select=[x + 1 for x in take]) R.assign("""matrix""", matrix) headers = [headers[x] for x in take] if legend: legend = [headers[x] for x in take] if options.r_options: extra_options = ", %s" % options.r_options else: extra_options = "" if options.legend is not None and len(legend): extra_options += ", legend=c('%s')" % "','".join(legend) if options.labels: xlabel, ylabel = options.labels.split(",") extra_options += ", xlab='%s', ylab='%s'" % (xlabel, ylabel) else: xlabel, ylabel = "", "" if options.colours: extra_options += ", col=colours" if options.logscale: extra_options += ", log='%s'" % options.logscale if options.xrange: extra_options += ", xlim=c(%f,%f)" % tuple( map(float, options.xrange.split(","))) if options.yrange: extra_options += ", ylim=c(%f,%f)" % tuple( map(float, options.yrange.split(","))) if options.hardcopy: if options.hardcopy.endswith(".eps"): R.postscript(options.hardcopy) elif options.hardcopy.endswith(".png"): R.png(options.hardcopy, width=1024, height=768, type="cairo") elif options.hardcopy.endswith(".jpg"): R.jpg(options.hardcopy, width=1024, height=768, type="cairo") for method in options.plot: if ndata < 100: point_size = "1" pch = "o" elif ndata < 1000: point_size = "1" pch = "o" else: point_size = "0.5" pch = "." if method == "scatter": R("""plot( matrix[,1], matrix[,2], cex=%s, pch="o" %s)""" % ( point_size, extra_options)) if method == "scatter-regression": R("""plot( matrix[,1], matrix[,2], cex=%s, pch="o" %s)""" % ( point_size, extra_options)) dat = R( """dat <- data.frame(x = matrix[,1], y = matrix[,2])""") R( """new <- data.frame(x = seq( min(matrix[,1]), max(matrix[,1]), (max(matrix[,1]) - min(matrix[,1])) / 100))""") mod = R("""mod <- lm( y ~ x, dat)""") R("""predict(mod, new, se.fit = TRUE)""") R("""pred.w.plim <- predict(mod, new, interval="prediction")""") R("""pred.w.clim <- predict(mod, new, interval="confidence")""") R( """matpoints(new$x,cbind(pred.w.clim, pred.w.plim[,-1]), lty=c(1,2,2,3,3), type="l")""") R.mtext( "y = %f * x + %f, r=%6.4f, n=%i" % (mod["coefficients"]["x"], mod["coefficients"][ "(Intercept)"], R("""cor( dat )[2]"""), ndata), 3, cex=1.0) elif method == "pairs": if options.add_diagonal: R( """panel.hist <- function( x,y,... ) { points(x,y,...); abline(0,1); }""") else: R( """panel.hist <- function( x,y,... ) { points(x,y,...); }""") # There used to be a argument na_action="na.omit", but # removed this as there appeared error messages saying # "na.action is not a graphical parameter" and the # plots showed occasionally the wrong scale. # cex=point_size also caused trouble (error message: # "X11 used font size 8 when 2 was requested" or # similar) if options.colours: R.pairs(matrix, pch=pch, col=colours, main=options.title, panel="panel.hist", labels=headers, cex_labels=2.0) else: R.pairs(matrix, pch=pch, panel="panel.hist", main=options.title, labels=headers, cex_labels=2.0) elif method == "boxplot": extra_options += ",main='%s'" % options.title # set vertical orientation if max([len(x) for x in headers]) > 40 / len(headers): # remove xlabel: extra_options = re.sub(", xlab='[^']+'", "", extra_options) extra_options += ", names.arg=headers, las=2" R( """op <- par(mar=c(11,4,4,2))""") # the 10 allows the names.arg below the barplot R("""boxplot( matrix %s)""" % extra_options) elif method == "bar" or method == "bar-stacked": if not options.colours: extra_options += ", col=rainbow(5)" # set vertical orientation if max([len(x) for x in headers]) > 40 / len(headers): # remove xlabel: extra_options = re.sub(", xlab='[^']+'", "", extra_options) extra_options += ", names.arg=headers, las=2" R( """op <- par(mar=c(11,4,4,2))""") # the 10 allows the names.arg below the barplot R("""barplot(as.matrix(matrix), %s)""" % extra_options) elif method == "bar-besides": if not options.colours: extra_options += ", col=rainbow(%i)" % ndata # set vertical orientation if max([len(x) for x in headers]) > 40 / len(headers): # remove xlabel: extra_options = re.sub(", xlab='[^']+'", "", extra_options) extra_options += ", names.arg=headers, las=2" R( """op <- par(mar=c(11,4,4,2))""") # the 10 allows the names.arg below the barplot R("""barplot(as.matrix(matrix), beside=TRUE %s)""" % extra_options) elif method == "scatter+marginal": if options.title: # set the size of the outer margins - the title needs to be added at the end # after plots have been created R.par(oma=R.c(0, 0, 4, 0)) R("""matrix""") R(""" x <- matrix[,1]; y <- matrix[,2]; xhist <- hist(x, breaks=20, plot=FALSE); yhist <- hist(y, breaks=20, plot=FALSE); top <- max(c(xhist$counts, yhist$counts)); nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), respect=TRUE ); par(mar=c(3,3,1,1)) ; plot(x, y, cex=%s, pch="o" %s) ; par(mar=c(0,3,1,1)) ; barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0 ) ; par(mar=c(3,0,1,1)) ; title(main='%s'); barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE ) ; title(main='%s'); """ % (point_size, extra_options, xlabel, ylabel)) if options.title: R.mtext(options.title, 3, outer=True, line=1, cex=1.5) elif method in ("panel", "1_vs_x", "matched"): if method == "panel": pairs = [] for x in range(len(headers) - 1): for y in range(x + 1, len(headers)): pairs.append((x, y)) elif method == "1_vs_x": pairs = [] for x in range(1, len(headers)): pairs.append((0, x)) # print matching columns elif method == "matched": pairs = [] for x in range(len(headers) - 1): for y in range(x + 1, len(headers)): if headers[x] == headers[y]: pairs.append((x, y)) break w = int(math.ceil(math.sqrt(len(pairs)))) h = int(math.ceil(float(len(pairs)) / w)) PosInf = 1e300000 NegInf = -1e300000 xlabel, ylabel = options.labels.split(",") R("""layout(matrix(seq(1,%i), %i, %i, byrow = TRUE))""" % (w * h, w, h)) for a, b in pairs: new_matrix = filter(lambda x: x[0] not in (float("nan"), PosInf, NegInf) and x[1] not in ( float("nan"), PosInf, NegInf), zip(matrix[a].values()[0], matrix[b].values()[0])) try: R("""plot(matrix[,%i], matrix[,%i], main='%s versus %s', cex=0.5, pch=".", xlab='%s', ylab='%s' )""" % ( a + 1, b + 1, headers[b], headers[a], xlabel, ylabel)) except rpy.RException, msg: print "could not plot %s versus %s: %s" % (headers[b], headers[a], msg) if options.hardcopy: R['dev.off']() E.info("matrix added as >matrix< in R.") if not options.hardcopy: if options.input_filename: interpreter = code.InteractiveConsole(globals()) interpreter.interact() else: E.info( "can not start new interactive session as input has come from stdin.") E.Stop() if __name__ == "__main__": main()
import mrs_strings as Strings import csv import os # reades the original csv - reads the MRS keys and values def read_series_MRS_keys_values(path): with open(path, 'rb') as csvinput: reader = csv.reader(csvinput) # read the headers row.First time we do reader.next we get the first row keys_line = reader.next() # read the values row. Second time reader.next gives us the second row values_line = reader.next() return keys_line, values_line def write_series_to_database_csv(data_dict, path, headers): if not os.path.isfile(path): is_new_database = True else: is_new_database = False if is_new_database: database_file = open(path, 'wb') # opening the file with "WB" will format the file befor it opens it - which mean we will get an empty file database_file_writer = csv.DictWriter(database_file, headers) # creating a dictionary writer database_file_writer.writeheader() else: database_file = open(path, 'ab') # opening file with "ab" opens the file and start writing from the last written row. database_file_writer = csv.DictWriter(database_file, headers) # creating a dictionary writer database_file_writer.writerow(data_dict) database_file.close() # writes a row with ALL the data - patient info, series general data, and MRS values to the specific series csv def write_series_to_series_csv(path, keys, values): with open(path, 'wb') as csvoutput: #now we open the same file only for writing writer = csv.writer(csvoutput, lineterminator='\n') writer.writerow(keys) # first row is the originals headers and after them the new headers writer.writerow(values) #now we add the originals values with the new values after them ##### THE FOLLOWING FUNCTIONS ARE NOT IN USE, BUT MY BE IN USE FOR FUTURE FEATURES ##### #in case we want to read the complete series data from CSV. We already have this data in pkl and and exam dic def get_series_data_from_series_csv (series_csv_path): #each series has it's own csv file. csv_file = open(series_csv_path, 'rb') reader_dict = csv.DictReader (csv_file) #series csv file only hold header and 1 row of data series_dic = reader_dict.next() #we read the first row as dict and save it csv_file.close() return series_dic def get_database_data(database_path): database_data = [] database_file = open(database_path,'rb') reader_dict = csv.DictReader(database_file) for row in reader_dict: #since we can't use the reader_dict after we close the file, I copy it to a new list. database_data.append(row) database_file.close() return database_data #returns a list of dictionaries - each row in the list is a series def get_clean_database_data(database_path): database_data = [] database_file = open(database_path,'rb') reader_dict = csv.DictReader(database_file) for row in reader_dict: database_data.append(row) database_file.close() return database_data def find_series_csv(series_folder_path): series_csv_path = None files = os.listdir(series_folder_path) for file in files: if Strings.CSV_WITH_INFO in file: series_csv_path = os.path.join (series_folder_path, file) break if series_csv_path == None: easygui.msgbox("Data is missing for this series. Please add the exam using \"Add New Exam\" before comparing this series.", "OK") sys.exit() return series_csv_path
from datetime import datetime if __name__ == '__main__': date1 = datetime.strptime("2016-09-01", "%Y-%m-%d") date2 = datetime.strptime("2016-09-02", "%Y-%m-%d") print (date1-date2).days
# Determinar la cantidad de dígitos de un número ingresado import math def digitos(n): if n < 0: n *= -1 if n != 0: return math.floor(math.log10(n)) + 1 return 1 try: n = int(input('Ingrese un número entero: ')) print('El número', n, 'tiene', digitos(n), 'dígitos') except ValueError: print('El valor ingresado debe ser un número entero')
# Implementar la clase Persona que cumpla las siguientes condiciones: # Atributos: # - nombre. # - edad. # - sexo (H hombre, M mujer). # - peso. # - altura. # Métodos: # - es_mayor_edad(): indica si es mayor de edad, devuelve un booleano. # - print_data(): imprime por pantalla toda la información del objeto. # - generar_dni(): genera un número aleatorio de 8 cifras y lo guarda dentro del atributo dni. import random class Persona: def __init__(self, nombre, edad, sexo, peso, altura): self.generar_dni() self.nombre = nombre self.edad = edad self.sexo = sexo self.peso = peso self.altura = altura def es_mayor_edad(self): return self.edad >= 18 # llamarlo desde __init__ def generar_dni(self): self.dni = random.randrange(10000000, 100000000) def print_data(self): print('Nombre: {nombre}'.format(nombre=self.nombre)) print('Edad: {edad}'.format(edad=self.edad)) print('Sexo: {sexo}'.format(sexo=self.sexo)) print('Peso: {peso}'.format(peso=self.peso)) print('Altura: {altura}'.format(altura=self.altura)) print('DNI: {dni}'.format(dni=self.dni)) if __name__ == '__main__': p = Persona('Carlos', 42, 'M', 50.0, 1.6) p.print_data() assert p.es_mayor_edad() p.edad = 17 assert not p.es_mayor_edad() p.edad = 18 assert p.es_mayor_edad()
# Escribir una función mas_larga() que tome una lista de palabras y devuelva la más larga def mas_larga(palabras): larga = '' for p in palabras: if len(p) > len(larga): larga = p return larga assert mas_larga(['hola', 'mundo', 'cadena', 'palabra']) == 'palabra' assert mas_larga(['palabra', 'mundo', 'cadena', 'a']) == 'palabra' assert mas_larga(['']) == '' assert mas_larga(['hola']) == 'hola' assert mas_larga(['hola', 'cadena', 'a']) == 'cadena'
import random mylist=[] # Generate random number on the list x = int(input("Masukkan jumlah data yang akan diiterasi: ")) for i in range(x): mylist.append(random.randrange(1,200)) def maxima(list_a): indexing_length = len(list_a)-1 #[1,2,3,4,5==> tdk bisa dibandingkan karena paling kanan] sorted = False while not sorted: sorted = True for i in range(0, indexing_length): if list_a[i]>list_a[i+1]: sorted = False list_a[i], list_a[i+1] = list_a[i+1], list_a[i] #swapping location based on value return list_a[-1] print((mylist),"==> Belum Sort") print(maxima(mylist),"==> Menggunakan Maxima") def minima(list_b): indexing_length = len(list_b)-1 #[1,2,3,4,5==> tdk bisa dibandingkan karena paling kanan] sorted = False while not sorted: sorted = True for i in range(0, indexing_length): if list_b[i]>list_b[i+1]: sorted = False list_b[i], list_b[i+1] = list_b[i+1], list_b[i] #swapping location based on value return list_b[0] print(minima(mylist)," ==> Menggunakan Minima")
barang = {} pilih1 = "" while pilih1 != "5" : print("===========LIST DATA BARANG===========") print("1. Cetak isi daftar barang\n2. Menambahkan data ke daftar barang\n3. Menghapus data dari daftar barang\n4. Mengubah data dalam daftar barang\n5. Exit") print("\n") pilih1 = input("Masukkan pilihan angka: ") ## OPSI 1 if pilih1 == "1" : if len(barang) == 0: print("Daftar barang masih kosong!") print("\n") else: print("=NAMA BARANG=||=JUMLAH=") print("") for item in sorted(barang, key=barang.get, reverse=False): print(item,":",barang[item]) print("") ## OPSI 2 elif pilih1 =="2": item = input("Masukkan nama barang: ") quantity = int(input("Masukkan jumlah barang: ")) barang[item] =+ quantity if item == barang[item]: YorN = input("Data barang yang sama terdeteksi, apakah barang tetap disimpan (Y/N)?") if YorN == "y" or "Y": barang[item] =+ quantity print("Data berhasil dimasukkan") elif YorN == "n" or "N": print("Data tidak dimasukkan") ### OPSI 3 elif pilih1 == "3": item = input("Masukkan data barang yang akan dihapus: ") item = item.lower() if item not in barang: print("Data barang tidak ditemukan!") print("\n") else: del(barang[item]) print("Data berhasil dihapus") print("") ### OPSI 4 elif pilih1 == "4": item = input("Masukkan data barang yang akan diubah: ") item = item.lower() if item not in barang: print(f"Nama barang '{item}' tidak tersedia!") print("\n") else: item = input("Masukkan perubahan data: ") quantity = int(input("Masukkan perubahan jumlah data: ")) barang[item]=quantity print("Data terupdate!") print("\n") ### OPSI 5 elif pilih1 == "5": print("Anda Telah Keluar Dari Aplikasi!") ### INPUT SALAH else: print("Pilihan anda tidak ada dalam opsi, mohon masukkan pilihan yang benar!") print("\n")
a=10 b=82 if a>b: print("A is greater") else: print("B is greater.") # Key Value fees={'Java':10000,'Python':12000,'Android':15000} print("Java fees @ out institute is :-",end="") print(fees.get("Java","invalid")) print(fees.get('java','invalid')) print(f"{a} and {b} are 2 numbers") print(a,"and",b,"are 2 numbers.") print("%d and %d are 2 numbers."%(a,b)) #Enter a number and find whether the given number is odd or even. number=int(input("Enter a number ")) if number%2==0: print("The number is even.") else: print("The nUmber is odd.") #----------------------------------------------- #Enter the year and find if it is leap year or not. year=int(input("Enter the year ")) if year%4==0: print("The year is a leap year.") else: print("THe year is not a leap year.") #----------------------------------------------- #ENter 3 nos and find the greatest of the three. first_number=int(input("Enter the first number. ")) second_number=int(input("Enter the second number. ")) third_number=int(input("Enter the third number. ")) if first_number>second_number and first_number>third_number: print(f"{first_number} is the greatest.") elif second_number>first_number and second_number>third_number: print(f"{second_number} is the greatest.") if third_number>second_number and third_number>first_number: print(f"{third_number} is the greatest.") #----------------------------------------------- #Insert a dictionary for the week. print("Enter a weekday:-") weekdays={'Monday':"First","Tuesday":"Second","Wednesday":"Third","Thursday":"Fourth","Friday":"Fifth","Saturday":"Sixth","Sunday":"Seventh"} day=input("").title() weekday=(weekdays.get(day)) print(f"{day} is the {weekday.lower()} day of the week.") #----------------------------------------------- print("Enter a weekday:- ",end="") weekdays={'Monday':"First","Tuesday":"Second","Wednesday":"Third","Thursday":"Fourth","Friday":"Fifth","Saturday":"Sixth","Sunday":"Seventh"} day=input("").title() weekday=(weekdays.get(day,'invalid')) print(day,"is",(weekdays.get(day,'invalid').lower()),"day of the week.")
"""Ladybug analysis period class.""" from .dt import DateTime from datetime import datetime, timedelta class AnalysisPeriod(object): """Ladybug Analysis Period. A continuous analysis period between two days of the year between certain hours Attributes: stMonth: An integer between 1-12 for starting month (default = 1) stDay: An integer between 1-31 for starting day (default = 1). Note that some months are shorter than 31 days. stHour: An integer between 0-23 for starting hour (default = 0) endMonth: An integer between 1-12 for ending month (default = 12) endDay: An integer between 1-31 for ending day (default = 31) Note that some months are shorter than 31 days. endHour: An integer between 0-23 for ending hour (default = 23) timestep: An integer number from 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60 """ _validTimesteps = {1: 60, 2: 30, 3: 20, 4: 15, 5: 12, 6: 10, 10: 6, 12: 5, 15: 4, 20: 3, 30: 2, 60: 1} _numOfDaysEachMonth = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # TODO: handle timestep between 1-60 def __init__(self, stMonth=1, stDay=1, stHour=0, endMonth=12, endDay=31, endHour=23, timestep=1): """Init an analysis period.""" stMonth = stMonth or 1 stDay = stDay or 1 stHour = stHour or 0 endMonth = endMonth or 12 endDay = endDay or 31 endHour = endHour or 23 timestep = timestep or 1 # calculate start time and end time self.stTime = DateTime(int(stMonth), int(stDay), int(stHour)) if int(endDay) > self._numOfDaysEachMonth[int(endMonth) - 1]: end = self._numOfDaysEachMonth[endMonth - 1] print "Updated endDay from {} to {}".format(endDay, end) endDay = end self.endTime = DateTime(int(endMonth), int(endDay), int(endHour)) if self.stTime.hour <= self.endTime.hour: self.overnight = False # each segments of hours will be in a single day else: self.overnight = True # A reversed analysis period defines a period that starting month is after # ending month (e.g DEC to JUN) if self.stTime.hoy > self.endTime.hoy: self.reversed = True else: self.reversed = False # check time step if timestep not in self._validTimesteps: raise ValueError("Invalid timestep." "Valid values are %s" % str(self._validTimesteps)) # calculate time stamp self.timestep = timestep self.minuteIntervals = timedelta(1 / (24.0 * self.timestep)) # calculate timestamps and hoursOfYear # A dictionary for datetimes. Key values will be minute of year self._timestampsData = [] self._calculateTimestamps() @classmethod def fromAnalysisPeriod(cls, analysisPeriod=None): """Create and AnalysisPeriod from an analysis period. This method is useful to be called from inside Grasshopper or Dynamo """ if not analysisPeriod: return cls() elif hasattr(analysisPeriod, 'isAnalysisPeriod'): return analysisPeriod elif isinstance(analysisPeriod, str): try: return cls.fromAnalysisPeriodString(analysisPeriod) except Exception as e: raise ValueError( "{} is not convertable to an AnalysisPeriod: {}".format( analysisPeriod, e) ) @classmethod def fromAnalysisPeriodString(cls, analysisPeriodString): """Create an Analysis Period object from an analysis period string.""" # %s/%s to %s/%s between %s to %s @%s ap = analysisPeriodString.lower().replace(' ', '') \ .replace('to', ' ') \ .replace('/', ' ') \ .replace('between', ' ') \ .replace('@', ' ') try: stMonth, stDay, endMonth, endDay, stHour, endHour, timestep = ap.split(' ') return cls(stMonth, stDay, stHour, endMonth, endDay, endHour, int(timestep)) except Exception as e: raise ValueError(str(e)) @property def isAnalysisPeriod(self): """Return True.""" return True def isPossibleHour(self, hour): """Check if a float hour is a possible hour for this analysis period.""" if hour > 23 and self.isPossibleHour(0): hour = int(hour) if not self.overnight: return self.stTime.hour <= hour <= self.endTime.hour else: return self.stTime.hour <= hour <= 23 or \ 0 <= hour <= self.endTime.hour def _calcTimestamps(self, stTime, endTime): """Calculate timesteps between start time and end time. Use this method only when start time month is before end time month. """ # calculate based on minutes # I have to convert the object to DateTime because of how Dynamo # works: https://github.com/DynamoDS/Dynamo/issues/6683 # Do not modify this line to datetime curr = datetime(stTime.year, stTime.month, stTime.day, stTime.hour, stTime.minute) endTime = datetime(endTime.year, endTime.month, endTime.day, endTime.hour, endTime.minute) while curr <= endTime: if self.isPossibleHour(curr.hour + (curr.minute / 60.0)): time = DateTime(curr.month, curr.day, curr.hour, curr.minute) self._timestampsData.append(time.moy) curr += self.minuteIntervals if self.timestep != 1 and curr.hour == 23 and self.isPossibleHour(0): # This is for cases that timestep is more than one # and last hour of the day is part of the calculation curr = endTime for i in range(self.timestep)[1:]: curr += self.minuteIntervals time = DateTime(curr.month, curr.day, curr.hour, curr.minute) self._timestampsData.append(time.moy) def _calculateTimestamps(self): """Return a list of Ladybug DateTime in this analysis period.""" if not self.reversed: self._calcTimestamps(self.stTime, self.endTime) else: self._calcTimestamps(self.stTime, DateTime.fromHoy(8759)) self._calcTimestamps(DateTime.fromHoy(0), self.endTime) @property def datetimes(self): """A sorted list of datetimes in this analysis period.""" # sort dictionary based on key values (minute of the year) return tuple(DateTime.fromMoy(moy) for moy in self._timestampsData) @property def hoys(self): """A sorted list of hours of year in this analysis period.""" return tuple(moy / 60.0 for moy in self._timestampsData) @property def intHoys(self): """A sorted list of hours of year as float values in this analysis period.""" return tuple(int(moy / 60) for moy in self._timestampsData) @property def isAnnual(self): """Check if an analysis period is annual.""" return True if len(self._timestampsData) / self.timestep == 8760 \ else False def isTimeIncluded(self, time): """Check if time is included in analysis period. Return True if time is inside this analysis period, otherwise return False Args: time: A DateTime to be tested Returns: A boolean. True if time is included in analysis period """ # time filtering in Ladybug and honeybee is slightly different since # start hour and end hour will be applied for every day. # For instance 2/20 9am to 2/22 5pm means hour between 9-17 # during 20, 21 and 22 of Feb. return time.moy in self._timestampsData def ToString(self): """Overwrite .NET representation.""" return self.__repr__() def __str__(self): """Return analysis period as a string.""" return self.__repr__() def __repr__(self): """Return analysis period as a string.""" return "%s/%s to %s/%s between %s to %s @%d" % \ (self.stTime.month, self.stTime.day, self.endTime.month, self.endTime.day, self.stTime.hour, self.endTime.hour, self.timestep)
import turtle class Bullet_Handler(): def __init__(self): self.bullet_list = [] def create_bullet(self, move_speed, is_enemy): bullet = Bullet(move_speed, is_enemy) return bullet def advance_bullet(self): for bullet in self.bullet_list: bullet.forward(bullet.move_speed) if abs(bullet.ycor()) > 300: self.remove_bullet(bullet) def remove_bullet(self, bullet): bullet.clear() bullet.hideturtle() self.bullet_list.remove(bullet) class Bullet(turtle.Turtle): def __init__(self, move_speed, is_enemy): turtle.Turtle.__init__(self) self.hideturtle() self.penup() self.move_speed = move_speed self.shapesize(0.75, 0.75) self.speed(0) self.is_enemy = is_enemy if self.is_enemy: self.shape("circle") self.color("yellow") else: self.shape("classic") self.color("red")
#PROGRAM TO GENERATE AN APPROPRIATE GREETING name = input("Enter your name: ") #T_O_D stands for time of the day(either morning, afternoon or night) T_O_D = (input("What time of the day is it: ")) if T_O_D >= 6:00 and T_O_D < 12:00: print("Hi " + name + " and good " + T_O_D) elif T_O_D == "afternoon": print("Hi " + name + " and good " + T_O_D)
""" Задача 36. Создать класс Транспортное средство и его потомков - классы Поезд и Самолет. В родительском классе должно быть определено минимум 1 конструктор, 3 атрибута и 1 метод. В классах-потомках должны быть добавлены минимум по 1 новому методу и по 1 новому атрибуту. """ class Vehicle(): EXTRA_CHARGE = 4 def __init__(self, speed, life_time, price): self.speed = speed self.price = price self.life_time = life_time self.color = "" def pretty_print(self): print('Speed, km/hour:', self.speed) print('Lifetime, year:', self.life_time) print('Price of vehicle, USD:', self.price) print('Revenue, USD:', self.revenue_for_year()) print('Color:', self.color) def revenue_for_year(self): revenue_for_year = (self.price * self.EXTRA_CHARGE / self.life_time) return revenue_for_year def set_color(self, color): if not isinstance(color, str): print("Is invlid data!!!") else: self.color = color def get_color(self): return self.color def main(): if __name__ == '__main__': main()
import math print('''Написать функцию решения квадратного уравнения. def solve_quadratic_equation(a, b, c): # always returns 2(!) values: either 2 roots, 1 root and None or 2 Nones ''') def solved_equation(a, b, c): print('Найдем решение квадратного уранвения: a*pow(x, 2) + b*x + c = 0') a = float(a) b = float(b) c = float(c) discriminant = pow(b, 2) - 4 * a * c print(discriminant) if discriminant == 0: x1 = ((-b + math.sqrt(Discriminant)) / (2 * a)) print(x1) x2 = None return x1, x2 if discriminant > 0: x1 = ((-b + math.sqrt(discriminant)) / (2 * a)) x2 = ((-b - math.sqrt(discriminant)) / (2 * a)) print(x1) print(x2) return x1, x2 if discriminant < 0: x1 = None x2 = None return x1, x2 root_1, root_2 = solved_equation(input('Введите число а: '), input('Введите число b: '), input('Введите число c: ')) print('Roots of a given quadratic equation : %.4s, %.4s' % (root_1, root_2))
import string import random def password(): pwd = "" limits = [3, 3, 2] for i in range(len(limits)): delta = random.randint(1, limits[i] - 1) limits[i] -= delta limits[random.randint(0, len(limits) - 1)] += delta sources = [ string.ascii_lowercase, string.ascii_uppercase, string.digits + "_" ] while sum(limits) > 0: i = random.randint(0, len(limits)-1) if limits[i]: pwd += random.choice(sources[i]) limits[i] -= 1 return pwd print(password()) # limits = [3, 3, 2] # for i in range(len(limits)): # delta = random.randint(1, limits[i]-1) # limits[i] -= delta # limits[random.randint(0, len(limits)-1)] += delta
import random print("""Задача №12. Для проверки остаточных знаний учеников после летних каникул, учитель младших классов решил начинать каждый урок с того, чтобы задавать каждому ученику пример из таблицы умножения, но в классе 15 человек, а примеры среди них не должны повторяться. В помощь учителю напишите программу, которая будет выводить на экран 15 случайных примеров из таблицы умножения (от 2*2 до 9*9, потому что задания по умножению на 1 и на 10 — слишком просты). При этом среди 15 примеров не должно быть повторяющихся (примеры 2*3 и 3*2 и им подобные пары считать повторяющимися) """) def pretty_print_matrix(matrix): def find_max(matrix): max = matrix[0][0] for i in range(len(matrix)): for j in range(len(matrix[0])): if max < matrix[i][j]: max = matrix[i][j] return max formatter = "%%%dd" % (len(str(find_max(matrix)))+1) for i in range(len(matrix)): for j in range(len(matrix[0])): print(formatter % matrix[i][j], end="") print() multiplication_table = [[(i+1)*(j+1) for i in range(10)] for j in range(10)] print() def summer_test(): matrix = [[0 for i in range(3)] for j in range(15)] for i in range(len(matrix)): end = True while end == True: for j in range(len(matrix[i]) - 1): matrix[i][j] = random.randint(2, 9) matrix[i][j + 1] = (matrix[i][j]) * (matrix[i][j - 1]) end = False elem = matrix[i][j + 1] idx = 0 for k in range(len(matrix)): if elem == matrix[k][j + 1]: idx +=1 if idx > 1: end = True lst = [str(elem[0]) + '*' + str(elem[1]) for elem in matrix] return lst print(summer_test())
print('''Условия задачи: Два поезда движутся на скорости V1 и V2 навстречу друг другу. Между ними 10 км. пути. Через 4 км пути первый поезд может свернуть на запасной путь. При заданных скоростях узнать столкнутся ли поезда. def have_trains_crashed(v1, v2): # returns boolean value ''') def have_trains_crashed(v1, v2): t = 1 if v1 * t <= 4 and v2 * t >= 6: return True else: return False if have_trains_crashed(1, 1): print('Поезда столкнутся') else: print('Поезда не столкнутся')
import re def statement_syntax(text): if_pattern = r'if\(.+\)(\n)*{(\n)?.+(\n)?}' while_pattern = r'while\(.+\)(\n)*{(\n)?.+(\n)?}' for_pattern = r'for\((.+=.+);(.+[\<\>]\=?.+);(.+);?\)(\n)*{(\n)?.+(\n)?}' if 'if' in text: if re.search(if_pattern, text): pass else: print('<< if >> syntax is wrong') if 'while' in text: if re.search(while_pattern, text): pass else: print('<< while >> syntax is wrong') if 'for' in text: if re.search(for_pattern, text): pass else: print('<< for >> syntax is wrong')
""" Implementation of the class `Field`. """ import os import numpy from matplotlib import pyplot, cm from mpl_toolkits.axes_grid1.inset_locator import inset_axes class Field(object): """ Contains information about a 2D field (pressure for example) on a structured Cartesian grid. """ def __init__(self, x=None, y=None, values=None, time_step=None, label=None): """ Initializes the field by its grid and its values. Parameters ---------- x: numpy 1D array of floats, optional Stations along a gridline in the x-direction; default: None. y: numpy 1D array of floats, optional Stations along a gridline in the y-direction; default: None. values: numpy 2D array of floats, optional Discrete field values; default: None. time_step: integer, optional Time-step; default: None. label: string, optional Description of the field; default: None. """ self.label = None self.x, self.y = None, None self.values = None self.time_step = None if numpy.any(x) and numpy.any(y) and values.shape == (y.size, x.size): self.set(x, y, values, time_step=time_step, label=label) def set(self, x, y, values, time_step=None, label=None): """ Sets the stations along a gridline in each direction, the field values, the time-step, and the label. Parameters ---------- x: numpy 1D array of floats Stations along a gridline in the x-direction. y: numpy 1D array of floats Stations along a gridline in the y-direction. values: numpy 2D array of floats Discrete field values. time_step: integer, optional Time-step; default: None. label: string, optional Description of the field; default: None. """ assert values.shape == (y.size, x.size) self.x, self.y = x, y self.values = values self.time_step = time_step self.label = label def subtract(self, other, label=None, atol=1.0E-12): """ Subtracts a given field to the current one (returns 'self' - 'other'). Note: the other field must be defined on the same grid. Parameters ---------- other: Field object The field that is subtracted. label: string, optional Label of the Field object to create; default: None (will be '<current label>-subtracted'). atol: float, optional Absolute-tolerance to define if two grid nodes have the same location; default: 1.0E-12. Returns ------- subtracted_field: Field object The subtracted field. """ # check the two solutions share the same grid assert numpy.allclose(self.x, other.x, atol=atol) assert numpy.allclose(self.y, other.y, atol=atol) assert self.values.shape == other.values.shape if not label: label = self.label + '-subtracted' return Field(label=label, time_step=self.time_step, x=self.x, y=self.y, values=self.values - other.values) def restrict(self, x, y, label=None, atol=1.0E-12): """ Restricts the field solution onto a coarser grid. Note: all nodes on the coarser grid are present in the actual grid. Parameters ---------- x: numpy 1D array of floats Stations along a gridline in the x-direction. y: numpy 1D array of floats Stations along a gridline in the y-direction. label: string, optional Label of the restricted field; default: None (will be '<current label>-restricted'). atol: float, optional Absolute tolerance used to define shared nodes between two grids; default: 1.0E-06. Returns ------- restricted_field: Field object Field restricted onto the coarser grid. """ def intersection(a, b, atol=atol): return numpy.any(numpy.abs(a - b[:, numpy.newaxis]) <= atol, axis=0) mask_x = intersection(self.x, x, atol=atol) mask_y = intersection(self.y, y, atol=atol) if not label: label = self.label + '-restricted' return Field(x=self.x[mask_x], y=self.y[mask_y], values=numpy.array([self.values[j][mask_x] for j in range(self.y.size) if mask_y[j]]), time_step=self.time_step, label=label) def get_difference(self, other, x, y, norm='L2'): """ Returns the difference between two fields in a given norm and on a given grid. The grid is defined by its stations along a gridline in the x-direction and its stations along a gridline in the y-direction. Parameters ---------- other: Field object The other field used for comparison. x: numpy 1D array of floats Stations along a gridline in the x-direction. y: numpy 1D array of floats Stations along a gridline in the y-direction. norms: string, optional Norm to use; choices: 'L2', 'Linf'; default: 'L2'. Returns ------- norm: float The difference in the given norm. """ norms = {'L2': None, 'Linf': numpy.inf} field = self.restrict(x, y) other = other.restrict(x, y) subtracted = field.subtract(other) return numpy.linalg.norm(subtracted.values, ord=norms[norm]) def get_gridline_values(self, x=None, y=None): """ Returns the field values along either a vertical or an horizontal gridline. The vertical gridline is defined by its x-position. The horizontal gridline is defined by its y-position. Parameters ---------- x: float, optional x-position of the vertical gridline; default: None. y: float, optional y-position of the horizontal gridline; default: None. Returns ------- stations, values: two numpy 1D arrays of floats Stations and values along the gridline. """ if (x and y) or not (x or y): print('[error] use either x or y keyword arguments ' 'to define the gridline position') return elif x: return self.get_vertical_gridline_values(x) elif y: return self.get_horizontal_gridline_values(y) def get_vertical_gridline_values(self, x): """ Returns field values along a vertical gridline defined by its x-position. If the x-position of the gridline does not match any gridline of the Cartesian grid, we interpolate the values. Parameters ---------- x: float x-position of the vertical gridline. Returns ------- y, u: two numpy 1D arrays of floats Stations and values along the vertical gridline. """ indices = numpy.where(numpy.abs(self.x - x) <= 1.0E-06)[0] # if no station matches the given value, we interpolate if indices.size == 0: i = numpy.where(self.x > x)[0][0] return (self.y, (abs(self.x[i] - x) * self.values[:, i - 1] + abs(self.x[i - 1] - x) * self.values[:, i]) / abs(self.x[i] - self.x[i - 1])) else: i = indices[0] return self.y, self.values[:, i] def get_horizontal_gridline_values(self, y): """ Returns field values along an horizontal gridline defined by its y-position. If the y-position of the gridline does not match any gridline of the Cartesian grid, we interpolate the values. Parameters ---------- y: float y-position of the horizontal gridline. Returns ------- x, u: two numpy 1D arrays of floats Stations and values along the horizontal gridline. """ indices = numpy.where(numpy.abs(self.y - y) <= 1.0E-06)[0] # if no station matches the given value, we interpolate if indices.size == 0: j = numpy.where(self.y > y)[0][0] return (self.x, (abs(self.y[j] - y) * self.values[j - 1, :] + abs(self.y[j - 1] - y) * self.values[j, :]) / abs(self.y[j] - self.y[j - 1])) else: j = indices[0] return self.x, self.values[j, :] def plot_vertical_gridline_values(self, x, boundaries=(None, None), plot_settings={}, plot_limits=(None, None, None, None), save_directory=None, show=False, other_data=None, other_plot_settings={}, style=None): """ Plots the field values along a group of vertical gridlines. Parameters ---------- x: list of floats Group of vertical gridlines defined by their x-position. boundaries: 2-tuple of floats, optional Gridline limits to consider; default: (None, None) (the entire gridline) plot_settings: dictionary of (string, object) items, optional Contains optional arguments to call pyplot.plot function for the gridline data; default: empty dictionary. plot_limits: 4-tuple of floats, optional Limits of the plot (x-start, x-end, y-start, y-end); default: (None, None, None, None) save_directory: string, optional Directory where to save the figure; default: None (does not save). show: boolean, optional Set 'True' if you want to display the figure; default: False. other_data: 2-tuple of 1d arrays of floats, optional Other data to add to the figure (1st array contains the y-stations, 2nd array contains the values at the stations); default: None. other_plot_settings: dictionary of (string, object) items, optional Contains optional arguments to call pyplot.plot function for the other data; default: empty dictionary. style: string, optional Path of a Matplotlib style-sheet; default: None. """ print('[info] plotting field values along vertical gridline(s) ...'), if style: pyplot.style.use(style) fig, ax = pyplot.subplots(figsize=(6, 6)) ax.grid(True, zorder=0) ax.set_xlabel('y-coordinate', fontsize=16) ax.set_ylabel('{} along vertical gridline'.format(self.label), fontsize=16) if not isinstance(x, (list, tuple)): x = [x] for x_target in x: y, u = self.get_vertical_gridline_values(x_target) if all(boundaries): mask = numpy.where(numpy.logical_and(y >= boundaries[0], y <= boundaries[1]))[0] y, u = y[mask], u[mask] ax.plot(y, u, **plot_settings) if other_data: y, u = other_data if all(boundaries): mask = numpy.where(numpy.logical_and(y >= boundaries[0], y <= boundaries[1]))[0] y, u = y[mask], u[mask] ax.plot(y, u, **other_plot_settings) ax.axis(plot_limits) ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax.legend(prop={'size': 16}) if save_directory and os.path.isdir(save_directory): file_name = '{}VerticalGridline{:0>7}.png'.format(self.label, self.time_step) pyplot.savefig(os.path.join(save_directory, file_name)) if show: pyplot.show() print('done') def plot_horizontal_gridline_values(self, y, boundaries=(None, None), plot_settings={}, plot_limits=(None, None, None, None), save_directory=None, show=False, other_data=None, other_plot_settings={}, style=None): """ Plots the field values along a group of horizontal gridlines. Parameters ---------- y: list of floats Group of horizontal gridlines defined by their y-position. boundaries: 2-tuple of floats, optional Gridline limits to consider; default: (None, None) (the entire gridline) plot_settings: dictionary of (string, object) items, optional Contains optional arguments to call pyplot.plot function for the gridline data; default: empty dictionary. plot_limits: 4-tuple of floats, optional Limits of the plot (x-start, x-end, y-start, y-end); default: (None, None, None, None) save_directory: string, optional Directory where to save the figure; default: None (does not save). show: boolean, optional Set 'True' if you want to display the figure; default: False. other_data: 2-tuple of 1d arrays of floats, optional Other data to add to the figure (1st array contains the y-stations, 2nd array contains the values at the stations); default: None. other_plot_settings: dictionary of (string, object) items, optional Contains optional arguments to call pyplot.plot function for the other data; default: empty dictionary. style: string, optional Path of a Matplotlib style-sheet; default: None. """ print('[info] plotting field values along horizontal gridline(s) ...'), if style: pyplot.style.use(style) fig, ax = pyplot.subplots(figsize=(6, 6)) ax.grid(True, zorder=0) ax.set_xlabel('x-coordinate', fontsize=16) ax.set_ylabel('{} along horizontal gridline'.format(self.label), fontsize=16) if not isinstance(y, (list, tuple)): y = [y] for y_target in y: x, u = self.get_horizontal_gridline_values(y_target) if all(boundaries): mask = numpy.where(numpy.logical_and(x >= boundaries[0], x <= boundaries[1]))[0] x, u = x[mask], u[mask] ax.plot(x, u, **plot_settings) if other_data: x, u = other_data if all(boundaries): mask = numpy.where(numpy.logical_and(x >= boundaries[0], x <= boundaries[1]))[0] x, u = x[mask], u[mask] ax.plot(x, u, **other_plot_settings) ax.axis(plot_limits) ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax.legend(prop={'size': 16}) if save_directory and os.path.isdir(save_directory): file_name = '{}HorizontalGridline{:0>7}.png'.format(self.label, self.time_step) pyplot.savefig(os.path.join(save_directory, file_name)) if show: pyplot.show() print('done') def plot_contour(self, field_range=None, filled_contour=True, view=[float('-inf'), float('-inf'), float('inf'), float('inf')], bodies=[], time_increment=None, save_name=None, save_directory=os.getcwd(), fmt='png', colorbar=True, cmap=None, colors=None, width=8.0, dpi=100): """ Plots and saves the field. Parameters ---------- field_range: 3-list of floats, optional Min, max and number of contours to plot; default: None. filled_contour: boolean, optional Set 'True' to create a filled contour; default: True. view: 4-list of floats, optional Bottom-left and top-right coordinates of the rectangular view to plot; default: the whole domain. bodies: list of Body objects or single Body object, optional The immersed bodies to add to the figure; default: [] (no immersed body). time_increment: float, optional Time-increment used to advance the simulation; default: None. save_name: string, optional Prefix used to create the images directory and to save the .png files; default: None. save_directory: string, optional Directory where to save the image; default: '<current directory>'. fmt: string, optional Format of the file to save; default: 'png'. colorbar: boolean, optional Set 'True' to display an horizontal colorbar at the bottom-left of the figure; default: True. cmap: string, optional The Matplotlib colormap to use; default: None. colors: string, optional The Matplotlib colors to use; default: None. width: float, optional Width of the figure (in inches); default: 8. dpi: integer, optional Dots per inch (resolution); default: 100 """ if abs(self.values.min() - self.values.max()) <= 1.0E-06: print('[warning] uniform field; plot contour skipped!') return # convert bodies in list if single body provided if not isinstance(bodies, (list, tuple)): bodies = [bodies] print('[time-step {}] plotting the {} contour ...'.format(self.time_step, self.label)) height = width * (view[3] - view[1]) / (view[2] - view[0]) fig, ax = pyplot.subplots(figsize=(width, height), dpi=dpi) ax.tick_params(axis='x', labelbottom='off') ax.tick_params(axis='y', labelleft='off') # create filled contour if field_range: levels = numpy.linspace(*field_range) print('\tmin={}, max={}'.format(self.values.min(), self.values.max())) colorbar_ticks = numpy.linspace(field_range[0], field_range[1], 5) colorbar_format = '%.01f' else: levels = numpy.linspace(self.values.min(), self.values.max(), 101) print('\tmin={}, max={}, steps={}'.format(levels[0], levels[-1], levels.size)) colorbar_ticks = numpy.linspace(self.values.min(), self.values.max(), 3) colorbar_format = '%.04f' color_map = {'pressure': cm.jet, 'vorticity': cm.RdBu_r, 'x-velocity': cm.RdBu_r, 'y-velocity': cm.RdBu_r} X, Y = numpy.meshgrid(self.x, self.y) contour_type = ax.contourf if filled_contour else ax.contour if not colors: if not cmap: cmap = (cm.RdBu_r if self.label not in color_map.keys() else color_map[self.label]) cont = contour_type(X, Y, self.values, levels=levels, extend='both', colors=colors, cmap=cmap) if colorbar: ains = inset_axes(pyplot.gca(), width='30%', height='2%', loc=3) cont_bar = fig.colorbar(cont, cax=ains, orientation='horizontal', ticks=colorbar_ticks, format=colorbar_format) cont_bar.ax.tick_params(labelsize=10) cont_bar.ax.xaxis.set_ticks_position('top') if time_increment: ax.text(0.05, 0.85, '{} time-units'.format(time_increment * self.time_step), transform=ax.transAxes, fontsize=10) # draw body for body in bodies: ax.plot(body.x, body.y, color='black', linewidth=1, linestyle='-') # set limits ax.set_xlim(view[::2]) ax.set_ylim(view[1::2]) ax.set_aspect('equal') # save image save_name = (self.label if not save_name else save_name) file_path = os.path.join(save_directory, '{}{:0>7}.{}'.format(save_name, self.time_step, fmt)) pyplot.savefig(file_path, dpi=dpi, bbox_inches='tight', pad_inches=0, format=fmt) pyplot.close()
""" PptxConstructor is the user interface to create the presentation file. The steps are described as follows: (1) Specifying the layout of the presentation file (width, height,...) (2) Adding object by using add_object() method: add_object(data, object_type, object_format, slide_page, location) data: str or pandas dataframe object_type: "text", "chart", "table" object_format: format for above type slide_page: int or None; if None, create a new slide at the end location: (x, y, w, h) or None; if None, handled by the PrsLayoutDesigner (3) call execute() to create the presentation (4) DataProcessor will transform the data based on corresponding object type, and packaged all data into data_container (5) PrsLayoutDesigner provides layout_design_container (6) layout_design_container and data_container are passed to PrsLayoutManager (7) PrsLayoutManager will call data2chart, data2table, data2text to create the object, using data from data_container, and put the object at the location (8) Optional: Auditor will check each object and issue warning if necessary (e.g. insufficient sample size) (9) call save() to save the presentation file """ import pandas as pd import data2table from pptx import Presentation from pptx.util import Inches from utils import pptx_layout, pptx_auditor from preprocessing import data_preprocessor from collections import namedtuple class PptxConstructor: def __init__(self, config): self.config = config self.presentation = Presentation() self.presentation.slide_width = config['prs_width'] self.presentation.slide_height = config['prs_height'] self.prs_object_pool = {} self.page_stack = {0: []} def add_object(self, data, object_type: str, object_format=None, slide_page=None, position=None): # assure the object type is text, chart, or table assert (object_type == 'text') or (object_type == 'chart') or (object_type == 'table') if position is not None: # three types of position representation: # 1. absolute position ("a", x, y, w, h) # 2. relative position to boundary ("rb", x%, y%, w%, h%) # 3. relative position to object ("rr/rl/ru/rd", uid, x, y, w, h) # assure the location is in the format of three assert isinstance(position, tuple) assert position[0] in ['a', 'rb', 'rr', 'ru', 'rl', 'rd'] if slide_page is None: # if no slide_page is given, create a new slide directly # TODO: slide_page can be str or int, but if string how to determine choose the page number slide_page = max(self.page_stack) + 1 self.page_stack[slide_page] = [] if slide_page not in self.page_stack: self.page_stack[slide_page] = [] # TODO: In the future, uid is produced by a hashmap based on the object argument. # If an object already exists, then the ObjectContainer can be reused to save space. # Currently do not apply this since no mechanism to handle duplicate objects with different location. uid = f"{object_type}_{len(self.prs_object_pool)}" ObjectContainer = namedtuple("obj", ['uid', 'data', "obj_type", "obj_format", "slide_page", 'position']) self.prs_object_pool[uid] = ObjectContainer(uid, data, object_type, object_format, slide_page, position) self.page_stack[slide_page].append(uid) return uid def pptx_execute(self): layout_designer = pptx_layout.PrsLayoutDesigner(self.config, self.prs_object_pool, self.page_stack) layout_designer.execute() design_structure = layout_designer.layout_design_export() data_processor = data_preprocessor.DataProcessor(self.prs_object_pool) data_container = data_processor.data_container_export() layout_manager = pptx_layout.PrsLayoutManager(presentation=self.presentation, object_stack=self.prs_object_pool, layout_design_container=design_structure, data_container=data_container) result = layout_manager.layout_execute() return result def pptx_save(self, filepath='C://Users/user/Desktop/untitled.pptx'): self.presentation.save(filepath) print(f"INFO: presentation file is saved successfully as {filepath}") def _set_presentation_size(self, width, height): self.presentation.slide_width = width self.presentation.slide_height = height def _presentation_reset(self): self.presentation = Presentation() self._set_presentation_size(Inches(13.33), Inches(7.5))
import random from abc import ABCMeta, abstractmethod class AttackStrategy: __metaclass__ = ABCMeta @abstractmethod def select_squad(self, army): """A choice of a squad according to a strategy. Args: army: Army. """ pass class Random(AttackStrategy): """A random strategy.""" def select_squad(self, army): """A choice of a squad in a random way. Args: army: Army. Returns: It returns a random squad. """ squads = army.get_squads random_squad = random.randint(0, len(squads) - 1) return squads[random_squad] class Weakest(AttackStrategy): """Strategy of attacking the weakest squad.""" def select_squad(self, army): """A choice of the weakest squad. Args: army: Army. Returns: It returns the weakest squad. """ res = None squads = army.get_squads min_experience = min([i.get_experience for i in squads]) for i in squads: if i.get_experience == min_experience: res = i break else: res = None return res class Strongest(AttackStrategy): """Strategy of attacking the strongest squad.""" def select_squad(self, army): """A choice of the strongest squad. Args: army: Army. Returns: It returns the strongest squad. """ res = None squads = army.get_squads max_experience = max([i.get_experience for i in squads]) for i in squads: if i.get_experience == max_experience: res = i break else: res = None return res
""" ex02, task C. Bubble sort. """ def bubble_sort(data): """ Takes a list or tuple of sortable elements and sorts it by the "Bubble sort" method. :param data: list or tuple :return: sorted list """ if type(data) == tuple: data = list(data) sorted_data = data for i in range(len(sorted_data) - 1): for j in range(len(sorted_data) - 1 - i): if sorted_data[j] > sorted_data[j + 1]: sorted_data[j], sorted_data[j + 1] = sorted_data[j + 1], sorted_data[j] return sorted_data if __name__ == "__main__": for data in ((), (1,), (1, 3, 8, 12), (12, 8, 3, 1), (8, 3, 12, 1)): print("{!s:>15} --> {!s:>15}".format(data, bubble_sort(data)))
# -*- coding: utf-8 -*- """ ex04 task A: two random number generator classes. """ __author__ = 'Åshild Grøtan' __email__ = '[email protected]' class LCGRand: """ Implements a linear congruential generator (LCG) to generate random numbers. """ def __init__(self, seed): self.random = seed def rand(self): """Returns the next random number """ a = 7**5 m = 2**31-1 self.random = a * self.random % m return self.random class ListRand: """Random number generator based on a list of numbers. """ def __init__(self, list_of_numbers): self.random_list = list_of_numbers.copy() self.random = 0 def rand(self): """Returns the next random number """ if len(self.random_list) == 0: raise RuntimeError self.random = self.random_list.pop(0) return self.random if __name__ == "__main__": lcg = LCGRand(50) print(lcg.rand()) print(lcg.rand()) print(lcg.rand()) lr = ListRand([54, 2, 8, 91]) print(lr.rand()) print(lr.rand()) print(lr.rand()) print(lr.rand())
# coding=utf-8 class testcase(object): def get_add(self, a, b): return a+b class Subject(object): def __init__(self, subject): self.subject1 = subject self.subject2 = 'cpp' def __getattribute__(self, item): if item=="subject1": return "review python" else: return object.__getattribute__(self, item) def square(x): return x * x m = map(square , (1, 2, 3)) #map内置函数会根据提供的函数对指定序列做映射。 n=filter(lambda x:x%2==1,(1,2,3,4,5,6))#filter内置函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。 from functools import reduce #在 Python3 中,reduce() 函数已经被从全局名字空间里移除了,它现在被放置在 functools 模块里, # 如果想要使用它,则需要通过引入 functools 模块来调用 reduce() 函数 def add(x, y): return x+y h=reduce(add, range(1,10)) if __name__ == "__main__": t = testcase().get_add(1, 2) print(t) print("hello") s = Subject("subject") print(s.subject1) print(s.subject2) for i in n: print(i) print(h)
# фунция которая добавляет компании новый локомотив (мощность, габариты) и сохранить в pickle # создать функцию, которая читает все тепловозы этой компании в список import pickle FILE_name = 'File' def write_Train(*kwargs): lok = [] name = str(input('Vvedite nazvanie poezda')) pwr = str(input('Vvedite moshnost poezda')) size = str(input('Vvedite gabarity poezda')) lok.append((name, pwr, size)) with open (FILE_name, 'wb') as f: pickle.dump(lok, f) write_Train() write_Train() write_Train() def read_Train(): with open(FILE_name, 'rb') as f: loc_2 = pickle.load(f) print(loc_2) read_Train()
""" Calculates statistics like most wins by a franchise, most wins by a coach, most mvps by player based on Super Bowl data. """ import csv from collections import Counter from collections import namedtuple legacy_franchises = { "Indianapolis Colts": "Baltimore Colts", "Los Angeles Chargers": "San Diego Chargers", "Las Vegas Raiders": ["Los Angeles Raiders", "Oakland Raiders"], "Los Angeles Rams": "St. Louis Rams", "Washington Football Team": "Washington Redskins", } def open_csv_and_populate_dct(): dct = {} with open("super_bowls.csv") as csv_file: f_csv = csv.reader(csv_file) headings = next(f_csv) assembled_tuple = namedtuple("assembled_tuple", headings) for detail in f_csv: row = assembled_tuple(*detail) dct[row.date] = row.super_bowl, row.site, row.city, \ row.visiting_team, row.visiting_team_score, \ row.home_team, row.home_team_score, \ row.mvp, row.winningcoach, row.losingcoach, \ row.favorite, row.line return dct def build_dct_of_franchises(): dct = {} with open("franchises.csv") as csv_file: f_csv = csv.reader(csv_file) headings = next(f_csv) assembled_tuple = namedtuple("assembled_tuple", headings) for detail in f_csv: row = assembled_tuple(*detail) dct[row.team] = [row.alternate_names] return dct def build_dictionary_of_teams_and_wins_or_losses(dct2): dct1 = {} for team, number_of_wins in dct2: dct1.setdefault(team, number_of_wins) return dct1 def build_dictionary_of_upsets(): dct = {} for super_bowl_name, details in winning_teams_favorites_and_lines.items(): winning_team = details[0] winning_team_score = int(details[1]) losing_team = details[2] losing_team_score = int(details[3]) favorite = details[4] if details[5] == "Pick \'em": line = details[5] else: line = float(details[5]) if winning_team != favorite and line != "Pick 'em": dct[super_bowl_name] = [winning_team, winning_team_score, losing_team, losing_team_score, favorite, line] return dct def build_list_of_host_cities(): lst = [] for details in super_bowls.values(): host_city = details[2] lst.append(host_city) return lst def build_list_of_match_ups(): lst = [] for details in super_bowls.values(): teams = details[3], details[5] lst.append(sorted(teams)) return lst def build_list_of_match_ups_sorted(): lst = [] for match_up in match_ups: teams = f"{match_up[0]} vs {match_up[1]}" lst.append(teams) return lst def build_list_of_mvps(): lst = [] for details in super_bowls.values(): mvp = details[7] lst.append(mvp) return lst def build_lists_of_winning_and_losing_coaches(): lst1 = [] lst2 = [] for details in super_bowls.values(): winning_coach = details[8] losing_coach = details[9] lst1.append(winning_coach) lst2.append(losing_coach) return lst1, lst2 def build_list_of_unique_values(lst): return list(set(lst)) def build_lists_and_dictionary_of_winning_and_losing_teams(): lst1 = [] lst2 = [] dct = {} print("\nsuper bowl results") for details in super_bowls.values(): super_bowl_name = details[0] visiting_team = details[3] visiting_team_score = int(details[4]) home_team = details[5] home_team_score = int(details[6]) mvp = details[7] favorite = details[10] line = details[11] print(f"Super Bowl {super_bowl_name}") print(f"{visiting_team} {visiting_team_score} vs {home_team} " f"{home_team_score}") if home_team_score > visiting_team_score: print(f"winning team: {home_team}") print(f"losing team: {visiting_team}") print(f"mvp: {mvp}\n") lst1.append(home_team) lst2.append(visiting_team) dct[super_bowl_name] = [home_team, home_team_score, visiting_team, visiting_team_score, favorite, line] else: print(f"winning team: {visiting_team}") print(f"losing team: {home_team}") print(f"mvp: {mvp}\n") lst1.append(visiting_team) lst2.append(home_team) dct[super_bowl_name] = [visiting_team, visiting_team_score, home_team, home_team_score, favorite, line] return lst1, lst2, dct def build_list_of_won_and_lost(lst2, lst3): lst1 = [] for i in lst2: if i in lst3: lst1.append(i) return lst1 def calculate_combined_scores_and_score_differential_for_each_game(): dct1 = {} dct2 = {} for details in super_bowls.values(): super_bowl_name = details[0] visiting_team_score = int(details[4]) home_team_score = int(details[6]) total_score = visiting_team_score + home_team_score if visiting_team_score > home_team_score: difference = visiting_team_score - home_team_score else: difference = home_team_score - visiting_team_score dct1[super_bowl_name] = total_score dct2[super_bowl_name] = difference return dct1, dct2 def count_wins_or_losses(lst2): lst1 = Counter(lst2) return lst1.most_common() def open_csv_and_populate_list(): lst = [] with open("current_teams.csv") as csv_file: f_csv = csv.reader(csv_file) headings = next(f_csv) assembled_tuple = namedtuple("assembled_tuple", headings) for detail in f_csv: row = assembled_tuple(*detail) lst.append(row.team) return lst def output_dictionary_sorted_by_values_ascending(header, dct): print(header) for k, v in sorted(dct.items(), key=lambda x: x[1]): print(k, v) def output_dictionary_sorted_by_values_descending(header, dct): print(header) for k, v in sorted(dct.items(), key=lambda x: x[1], reverse=True): print(k, v) def output_franchises_that_have_appeared(): print("\nteams that have appeared") for team in sorted(franchises_that_have_appeared): print(team) def output_mvps_and_number_of_wins(): mvps = build_list_of_mvps() mvp_counts = Counter(mvps) mvps_counts = mvp_counts.most_common() print("\nmvps") for mvp in mvps_counts: player = mvp[0] number_of_wins = mvp[1] print(f'{player}, {number_of_wins}') def output_list(header, lst): print(header) for i in sorted(lst): print(i) def output_host_cities(): host_cities = build_list_of_host_cities() city_counts = Counter(host_cities) cities_counts = city_counts.most_common() print("\nmost common host city") for city_count in cities_counts: city = city_count[0] number_of_super_bowls_hosted = city_count[1] print(f'{city}, {number_of_super_bowls_hosted}') def output_most_common_match_ups(lst): print("\nmost common match ups") for match_ups_count in lst: print(*match_ups_count, sep=", ") def output_teams_that_have_not_won_or_appeared(header, lst): print(header) for team in sorted(current_teams): if team not in franchises_that_have_won and team not in \ list(legacy_franchises.keys()): print(team) def output_upsets(): print("\nupsets") for super_bowl_name, details in sorted(upsets.items(), key=lambda x: x[1][5]): winning_team = details[0] winning_team_score = details[1] losing_team = details[2] losing_team_score = details[3] line = details[5] print(f"Super Bowl {super_bowl_name}"), print(winning_team, winning_team_score, losing_team, losing_team_score) print(f"line: {line}\n") def output_wins_or_losses_by_coach(header, lst): print(header) for coach_results in lst: coach = coach_results[0] result = coach_results[1] print(coach, result) super_bowls = open_csv_and_populate_dct() winning_teams, losing_teams, winning_teams_favorites_and_lines = \ build_lists_and_dictionary_of_winning_and_losing_teams() franchises_that_have_won = build_list_of_unique_values(winning_teams) output_list("franchises that have won", franchises_that_have_won) franchises_that_have_lost = build_list_of_unique_values(losing_teams) output_list("\nfranchises that have lost", franchises_that_have_lost) all_appearances = build_list_of_won_and_lost(franchises_that_have_won, franchises_that_have_lost) franchises_that_have_appeared = build_list_of_unique_values(all_appearances) output_list("\nfranchises that have appeared", franchises_that_have_appeared) franchises_that_have_won_and_lost = \ build_list_of_won_and_lost(franchises_that_have_won, franchises_that_have_lost) output_list("\nfranchises that have both won and lost", franchises_that_have_won_and_lost) winning_teams_number_of_wins = \ count_wins_or_losses(winning_teams) team_number_of_wins = \ build_dictionary_of_teams_and_wins_or_losses(winning_teams_number_of_wins) output_dictionary_sorted_by_values_descending( "\nmost wins by a franchise", team_number_of_wins) losing_teams_number_of_losses = \ count_wins_or_losses(losing_teams) team_number_of_losses = \ build_dictionary_of_teams_and_wins_or_losses(losing_teams_number_of_losses) output_dictionary_sorted_by_values_descending( "\nmost losses by a franchise", team_number_of_losses) current_teams = open_csv_and_populate_list() output_teams_that_have_not_won_or_appeared( "\ncurrent teams that have not won", franchises_that_have_won) output_teams_that_have_not_won_or_appeared( "\ncurrent teams that have not appeared", franchises_that_have_appeared) combined_scores, score_differentials = \ calculate_combined_scores_and_score_differential_for_each_game() output_dictionary_sorted_by_values_descending("\ncombined scores descending", combined_scores) output_dictionary_sorted_by_values_ascending("\ncombined scores ascending", combined_scores) output_dictionary_sorted_by_values_descending("\nscore differential", score_differentials) output_host_cities() output_mvps_and_number_of_wins() match_ups = build_list_of_match_ups() match_ups_sorted = build_list_of_match_ups_sorted() match_ups_count = count_wins_or_losses(match_ups_sorted) output_most_common_match_ups(match_ups_count) winning_coaches, losing_coaches = build_lists_of_winning_and_losing_coaches() coaches_who_have_won = build_list_of_unique_values(winning_coaches) output_list("\ncoaches who have won", coaches_who_have_won) coaches_who_have_lost = build_list_of_unique_values(losing_coaches) output_list("\ncoaches who have lost", coaches_who_have_lost) coaches_who_have_won_and_lost = \ build_list_of_won_and_lost(coaches_who_have_won, coaches_who_have_lost) output_list("\ncoaches who have won and lost", coaches_who_have_won_and_lost) wins_by_coach = count_wins_or_losses(winning_coaches) output_wins_or_losses_by_coach("\nwins by coach", wins_by_coach) losses_by_coach = count_wins_or_losses(losing_coaches) output_wins_or_losses_by_coach("\nlosses by coach", losses_by_coach) upsets = build_dictionary_of_upsets() output_upsets()
print("hello world"); #숫자형 자료형 print(4096) #사칙연산 print(1 + 2) print(3 ** 4) #제곱, 몫, 나머지 연산자 print(1 ** 2) print(3 // 4) print(5 % 6) # 변수 my_int = 1 my_str = 'python' my_bool = True my_list = [1, 2, 3] print(my_bool) #복합 할당 연산자 : += -+ *= /= count = 0 count += 1 count -= 5 count *= 2 print(count); #뱐수 이름 my_int1 = 1 # 1my_int2 = 2 #syntax_error-> 변수명은 숫자로 시작할 수 없다. print(my_int1) A = 1 #대, 소문자 구분한다. print(A) a = 2 print(a) #문자열 my_str1 = 'a' my_str2 = '3.14' my_str3 = 'coding' my_str4 = "coding" print(my_str1, my_str2, my_str3, my_str4) print(type(my_str2)) #type() -> type확인 할 수 있다. #문자열 연산하기 + : 문자열끼리 연결, *: 반복할때 사용 my_str5 = 'a' + 'b' + 'c' my_str6 = 'cod' + 'ing' my_str7 = 'abc' * 4 my_str8 = '=' * 10 print(my_str5, my_str6, my_str7, my_str8) print(my_str7 + my_str6) #인덱싱 alphabet = 'abcde' print(alphabet[0], alphabet[3], alphabet[4]) #뒤에서부터 인덱싱 print(alphabet[-1], alphabet[-4], alphabet[-5]) #여러가지 문자 가져오기 - 슬라이싱(앞의 숫자부터 끝 숫자 바로 전까지) print(alphabet[1: 4]) #숫자 생략하기 print(alphabet[:3]) print(alphabet[3: ]) #문자열 분리하기 : string에서 사용하는 method .split() #메소드는 특정 자료형만 사용할 수 있는 함수를 말한다. fruit_str = 'apple banana lemon' fruits = fruit_str.split() print(fruits[0]) print(fruits[1]) #문자열 포맷팅 : .format() -> format 괄호 안에 있는 문자열이 {} 안으로 들어온다. print('Life if {}' .format('Short!')) print('{}x{}={}' .format(2, 3, 2 * 3)) #여러줄 문자열(엔터 쳐도 에러 나지 않는다.) print('''첫번째 두번째 세번째''') #출력의 끝 지정하기 print("coding", end='') #줄바꿈 없어짐 print("coding", end="-") #- 뒤에 붙는다 print("coding", end="\n") print("coding", end="\t") #이스케이프코드 \n, \t print("coding\ncoding") print("tab\ttab") print('\\n') #\n, \t 자체를 출력하고 싶을 경우 print('\\t') print('I\'m Yours') #C스타일 포맷팅 # %d(정수) %f(실수) %s(문자열) print('Life is %s' % 'Short') print('%d x %d = %d' % (2, 3, 2 * 3)) #주석 : 컴퓨터는 보지 못함. 사람이 코드를 이해하는 것을 돕기 위해 사용함. #
import matplotlib.pyplot as plt import numpy as np from common.data_handler.artificial_regression import linear_2d class linear_regression: def __init__(self): pass def fit(self,x,y): x = np.array(x) y = np.array(y) mux = np.mean(x) muy = np.mean(y) self.m = 0 for xx,yy in zip(x,y): self.m += (yy - muy)/(xx - mux) self.m /= len(x) self.b = muy-self.m*mux def predict(self,x): return np.array([self.m * xx + self.b for xx in x]) if __name__ == '__main__': data = linear_2d() x = data[:,0] y = data[:,1] lr = linear_regression() lr.fit(x,y) predicted_x = list(np.arange(0,5,0.01)) predicted_y = lr.predict(predicted_x) plt.scatter(x,y,c='red') plt.scatter(predicted_x,predicted_y,c='blue') plt.show()
from bs4 import BeautifulSoup import requests from PyDictionary import PyDictionary import random # a dictionary to get synonyms of words in the menu dictionary=PyDictionary() # a function to return the daily menu in dictionary {'lunch': ..., 'dinner': ...} form def get_menu(): site_response = requests.get("https://www.thecrimson.com/flyby/", timeout=10) site_content = BeautifulSoup(site_response.content, "html.parser") whole_list = list(site_content.find(text="Today's Menu").parent.parent.parent.descendants) result = { "lunch": [], "dinner": [] } meal = None for element in whole_list: if element.string == None or element.string == "\n" or element.string == "See full Harvard Today →": continue if element.string == "Lunch" or element.string == "Dinner": meal = element.string.lower() elif meal and element.string not in result[meal]: result[meal].append(element.string) return result def main(): menu_items = get_menu() modified = { "lunch": [], "dinner": [] } for (meal,foods) in menu_items.items(): for food in foods: result = "" for word in food.split(): meaning = dictionary.meaning(word) if not meaning: result += word + " " else: word_type = random.choice(list(meaning.keys())) try: result += meaning[word_type][0] + " " except: result += word + " " modified[meal].append(result[:-1].capitalize()+".") with open("output.txt", "w") as fout: fout.write("Lunch Menu:\n") for food in modified["lunch"]: fout.write(food + "\n") fout.write("\nDinner Menu:\n") for food in modified["dinner"]: fout.write(food + "\n") if __name__ == "__main__": main()
from datetime import datetime # Class to create tweets. class Tweet: # Method ot assign initial values. def __init__(self, name, text): self.__author = name self.__text = text self.__age = datetime.now() def get_author(self): return self.__author def get_text(self): return self.__text def get_age(self): current_time = datetime.now() time_since_tweet = current_time - self.__age return time_since_tweet
from Tweet import Tweet from datetime import datetime import math import pickle def open_old_tweets(): try: tweet_file = open("tweets.pickle", 'rb') Tweets = pickle.load(tweet_file) tweet_file.close() return Tweets except: Tweets = [] return Tweets def tweet_menu(): print("\nTweet Menu") print("- - - - - -") print("1. Make a Tweet") print("2. View Recent Tweets") print("3. Search Tweets") print("4. Quit") answer = input("\nWhat would you like to do? ") return answer def make_tweet(): name = input("What is your name? ") while True: text = input("What would you like to tweet? ") if len(text) > 140: print("\nTweets can only be 140 characters!\n") else: break Tweets.append(Tweet(name, text)) print("{}, your tweet has been saved.".format(name)) def recent_tweets(): print("\nRecent Tweets") print("- - - - - -") if len(Tweets) == 0: print("There are no recent tweets.") else: index = (len(Tweets) - 1) printed = 0 while printed < 5 and printed < (len(Tweets)): print("\n{} - {}".format(Tweets[index].get_author(), determine_time(Tweets[index].get_age()))) print("{}".format(Tweets[index].get_text())) index -= 1 printed += 1 def determine_time(time_since_tweet): time = time_since_tweet if time.seconds >= 3600: time = "{}h".format(math.floor(time.seconds/3600)) elif time.seconds > 60 and time.seconds < 3600: time = "{}m".format(math.floor(time.seconds/60)) elif time.seconds < 60: time = "{}s".format(time.seconds) return time def search_tweets(): if len(Tweets) == 0: print("\nThere are no tweets to search.") else: search_for = input("What would you like to search for? ") index = (len(Tweets) - 1) printed = 0 print("Search Results") print("- - - - - -") for tweet in Tweets: text = Tweets[index].get_text() if search_for in text: print("\n{} - {}".format(Tweets[index].get_author(), determine_time(Tweets[index].get_age()))) print("{}".format(Tweets[index].get_text())) printed += 1 index -= 1 if printed == 0: print("No tweets contained {}.".format(search_for)) def save_tweets(): tweet_file = open("tweets.pickle", 'wb') pickle.dump(Tweets, tweet_file, pickle.HIGHEST_PROTOCOL) tweet_file.close() Tweets = open_old_tweets() while True: answer = tweet_menu() if answer == "1": make_tweet() elif answer == "2": recent_tweets() elif answer == "3": search_tweets() elif answer == "4": save_tweets() print("Thank you for using the Tweet Manager!") exit() elif answer == "one" or answer == "two" or answer == "three": print("Please enter a numeric value. ") else: print("Please select a valid option.")
""" file: student_placer.py language: python3 author: [email protected] Moisés Lora Pérez class: CSCI 141-03 """ from building import * from student import * from room import * from rooms import * from floors import * def readStudents(filename): """ This function opens the filename and returns the list. :param filename: textfile inputed :return: nameList """ file = open(filename) nameList = [] for currentLine in file: nameList.append((currentLine.strip().split())) return nameList def placeStudents(list): """ This function places the students in their corresponding buildings, floor and rooms. It uses the hash functions in order to determine where the students should be placed according to the value of the corresponding hash. :param list: inputed list """ buildings = createBuilding() for line in list: name, furniture = line.split() floors = buildings.get(name) rooms = floors.get(name) room = rooms.get(name) if room.AddtoRoom(name, furniture): print("student", name, "already present in", buildings.hash_function(name),"floor", floors.hash_function(name) , "in room", rooms.hash_function(name), ". Added furniture", furniture) # They were already in the room and their furniture was added else: print('Added student', name, 'with', furniture, 'to building', buildings.hash_function(name), "floor", floors.hash_function(name), "in room", rooms.hash_function(name)) def main(): """ The main function reads in a file, converts it to a list and then proceeds to place the students. """ textfile = input("input filename: ") list = readStudents(textfile) placeStudents(list) if __name__ == "__main__": main()
""" file: olympics_simpl.py language: python3 author: [email protected] Moisés Lora Pérez class: CSCI 141-03 description: This program counts the number of gold medals in a given year and also counts the number of medals that a certain athlete has been awarded.". """ def goldMedalinYear(year, filename): """ This function counts how many gold medals there were in a specific year of the olympics. It takes the following parameters and returns: pre-conditions: year is a string postconditions: File is unmodified, the amount of gold medals won in that year is returned :param year: The year that will be used to count the amount of gold medals. :param filename: The filename that will be used :return: The amount of gold medals won in that year """ gcounter = 1 #This variable serves as a counter and it ranges from 0 to 5, which accounts to the line numbers. goldMedals = 0 #This variable counts the amount of goldMedals that have been won. isCorrectYear = False #This variable checks if the year inputed is the same as the line being read. with open(filename, 'r', encoding='utf-8') as file: for line in file: line = line.strip() if gcounter == 3: if line == str(year): isCorrectYear = True if gcounter == 4: if isCorrectYear is True and line == "1": goldMedals += 1 isCorrectYear = False if gcounter == 5: gcounter = 0 gcounter += 1 return goldMedals def countByName(lastName, firstName, filename): """ This function counts all gold, silver and bronze medals for a given athlete of the olympics. It takes the following parameters and returns: pre-conditions: firstName and lastName are strings postconditions: file is unmodified, the amount of medals won is returned :param lastName: The last name of the athlete inputed. :param firstName: The first name of the athlete inputed. :param filename: The filename that will be used :return: The amount of gold, silver and bronze medals won by that athlete. """ nameCounter = 1 #This variable serves as a counter and it ranges from 0 to 5, which accounts to the line numbers. isCorrectName = False #This variable evaluates whether the names compare to the names on the text. gmedals = 0 #Counts the amount of gold medals smedals = 0 #Counts the amount of silver medals bmedals = 0 #Counts the amount of bronze medals with open(filename, 'r', encoding='utf-8') as file: for line in file: line = line.strip().upper() if nameCounter == 1: if line == lastName.upper(): isCorrectName = True else: isCorrectName = False if nameCounter == 2 and isCorrectName is True: if line == firstName.upper(): isCorrectName = True else: isCorrectName = False if nameCounter == 4: if isCorrectName is True and line == '1': gmedals += 1 else: pass if isCorrectName is True and line == '2': smedals += 1 else: pass if isCorrectName is True and line == '3': bmedals += 1 if nameCounter == 5: nameCounter = 0 isCorrectName = False nameCounter += 1 return gmedals, smedals, bmedals """ if filename wants to be asked to the user filenameInput = str(input("Enter the filename to be looked at: ")) filename = filenameInput """ #name of filename to be looked at is below. filename = 'athletes.txt' #user is asked for year to look at yearInput = str(input("Enter year to count its winners:")) goldMedalsWon = goldMedalinYear(yearInput, filename) #values returned are printed print("In year " + str(yearInput) + " there were " + str(goldMedalsWon) + " gold medalists in total." ) print("Let’s look up the total medals won by an athlete (1896-2008)!") #last name of athlete is asked lastNameInput = str(input("Last name:")) #first name of athlete is asked firstNameInput = str(input("First name:")) #Since values of the function countByName are returned in a tuple, there values by order are assigned to a variable medalCounts = countByName(lastNameInput,firstNameInput,filename) gold = medalCounts[0] silver = medalCounts[1] bronze = medalCounts[2] """ Values returned are printed in order (strings printed are uppercased so that the letters are uniform. ie: PhElpS would be printed as PHELPS instead """ print(str.upper(firstNameInput) + " " + str.upper(lastNameInput) + " won " + str(medalCounts[0]) + " gold, " + str(medalCounts[1]) + " silver and " + str(medalCounts[2]) + " bronze medals.")
from myStack import * def read_file(filename): """ This function opens the filename and returns the list of puzzles. :param filename: textfile inputed :return: puzzleList """ file = open(filename) puzzleList = [] for currentLine in file: puzzleList += currentLine.split() return puzzleList def reverseWords(lst): wordStack = None for word in lst: wordStack = push(wordStack, word) while not emptyStack(wordStack): x = top(wordStack) wordStack = pop(wordStack) print(x,end=' ') def main(): txtFile = input("Input Filename:") list = read_file(txtFile) print(list) reverseWords(list) main()
""" file: pycount.py language: python3 author: [email protected] Sean Strout description: Word Count Program for CS 141 Lecture This version uses the built-in dict type. """ def word_count(filename): """Report on the frequency of different words in the file named by the argument. """ d = {} inFile = open(filename) for line in inFile: for word in line.split(): word = word.strip(",.\"\';:-!?").lower() if word not in d: d[word] = 1 else: d[word] += 1 inFile.close() print("Total words:", sum(d.values())) print("Unique words:", len(d)) most = list(d.values()) most.sort() for k in d: if d[k] == most[-1]: print("Most used word: ", k, " occurred", d[k], "times.") def main(): filename = input("Enter filename: ") word_count(filename) main()
""" file: vlc.py author: [email protected] Moises Lora Perez class: CSCI 141-03 """ from rit_lib import * from array_heap import * from math import * class SymbolObject( struct ): """ Represents a the symbol object. :slot name (str): The name of the symbol. :slot frequency (int): The symbol's frequency. :slot codeword (str): The codeword corresponding to the symbol. """ _slots = ((str, 'name'), (int, 'frequency'), (str, 'codeword')) class Node( struct ): """ Represents a node made of symbols. :slot cum (int): The cumulative frequency of the symbols on the node.. :slot symbols (lst): The list of symbols contained in the node. """ _slots = ((int, 'cum'),(list, 'symbols')) def createSymbolObject(symbol,frequency): """ This function takes in a symbol and frequency and returns a SymbolObject with an empty frequency. """ return SymbolObject(symbol, frequency, "") def createNode(cumfrequency, symbols): """ This function takes in a cumulative frequency and symbol object list and returns a new Node. """ return Node(cumfrequency, symbols) def createHistogram(filename): """ This function wil create a histogram that will contain each symbol and the count of each symbol in the file. :param filename: inputed filename :return: Returns a dictionary (called hist) containing the count. """ file = open(filename) hist = {} for line in file: lst = line.strip() for character in lst: if character in hist: hist[character] += 1 else: hist[character] = 1 file.close() return hist def convertToHeap(hist): """ This function takes in the histogram, creates and empty Heap and for each symbol it will create a Symbol Object, and for each SymbolObject it will create a Node and then add it to the heap. :param hist: The histogram from the createHistogram function :return: returns the Heap with the added Nodes. """ maxSize = len(hist) Heap = createEmptyHeap(maxSize,compareFunc) for symbol in hist: symbolObject = [createSymbolObject(symbol,hist[symbol])] Node = createNode(hist[symbol], symbolObject) Heap.add(Node) return Heap def compareFunc(n1,n2): """ Compares if Node 1 is smaller than Node 2. :param n1: Node 1 :param n2: Node 2 :return: True or False (Boolean) """ return n1.cum < n2.cum def combine(n1,n2): """ This function creates a combined Node with the corresponding values from Node 1 and Node 2. :param n1: inputted Node 1 :param n2: inputted Node 2 :return: The combined Node """ combinedNode = None cumulutaiveFreq = n1.cum + n2.cum symbols = [] for symbol in n1.symbols: symbol.codeword = '0' + symbol.codeword symbols.append(symbol) for symbol in n2.symbols: symbol.codeword = '1' + symbol.codeword symbols.append(symbol) CombinedNode = createNode(cumulutaiveFreq, symbols) return CombinedNode def createVLC(heap): """ This creates the codeword for the symbol. :param heap: this takes the created heap from the convertToHeap function. """ while heap.size > 1: Node1 = heap.remove() Node2 = heap.remove() CombinedNode = combine(Node1,Node2) heap.add(CombinedNode) return heap.remove() def main(): """ This function takes in a filename, creates the histogram, then the heap and finally the codeword for each symbol and creates a correct output. """ filename = input("Input Filename:") hist = createHistogram(filename) heap = convertToHeap(hist) vlc = createVLC(heap) print("Variable Length Code Output") print("------------------------------------") topeq = 0 bottomeq = 0 for symbol in vlc.symbols: print('Symbol: %2s ' % symbol.name, end='') print('Codeword: %8s ' %symbol.codeword, end = '') print('Frequency: %5d' % symbol.frequency) topeq += len(symbol.codeword) * symbol.frequency bottomeq += symbol.frequency eqres = topeq / bottomeq logres = ceil(log2(len(hist))) print("Average VLC codeword length: ", eqres, "bits per symbol") print("Average Fixed length codeword length:", logres, "bits per symbol") if __name__ == '__main__': main()
from collections import Counter def findDuplicate(nums): ldupl = [i for i, cnt in Counter(nums).items() if cnt > 1] return ldupl def main(): T=int(input()) while(T>0): n=int(input()) arr=[int(x) for x in input().strip().split()] final = findDuplicate(arr) for i in final: print(i,end=" ") T-=1 if __name__ == "__main__": main()
class Solution(object): def subtractProductAndSum(self, n): """ :type n: int :rtype: int """ sum = 0 pro=1 for digit in str(n): sum += int(digit) pro *= int(digit) return (pro-sum) if __name__ == '__main__': tc = int(input()) while tc > 0: n = int(input()) ob = Solution() ans = ob.subtractProductAndSum(n) print(ans) tc-=1
class shape: def __init__(self, breadth, length): self.b = breadth self.l = length def area(self): area = self.b * self.l print(area) class rect(shape): pass class square(shape): pass print("enter the same value if square else different ") s = rect(2, 13) s.area() s = square(2, 103) s.area()
#!/usr/bin/python """ Project Euler Problem 7 What is the 10001st prime number? Example: >>> p7(6) 13 """ from primework import euler_sieve def p7(n=10001): i = 150000 p = euler_sieve(i) while len(p) < n: i *= 2 p = euler_sieve(i) return p[n-1] if __name__ == '__main__': import doctest doctest.testmod() p7()
from pathlib import Path path = Path(__file__).resolve() path = path.parent file_path = path / "number_phone.txt" def choice(): print('Главное меню\n' '1. Зарегистрировать нового пользователя\n' '2. Вывести список новых пользователей\n' '3. Выход\n') num_c = input('Сделайте выбор: ') if num_c == '1': choice_input = 1 elif num_c == '2': choice_input = 2 elif num_c == '3': print('Выход выполнен') return exit() else: print('Выберите один из вариантов.') return choice() return choice_input def number_phone(): num_phone = input('Введте Ваш телефон для регистрации: ') phone_n = '' for i in num_phone: if i.isdigit(): phone_n += i if len(phone_n) < 8: print('Повторите ввод, Вы ввели недостаточно цифр!') return number_phone() elif len(phone_n) >= 9: phone_n = '380' + phone_n[-9:] return phone_n def check_phone(phone): with open(file_path) as f: for i in f.readlines(): tmp_num = i.count(phone, 0, 12) if tmp_num != 0: print('Пользователь с таким номером уже существует\n') return main() return def email_form(): email_f = input('Введте Ваш емейл: ') if len(email_f) < 6 or email_f.count('@') != 1: print('Введите емейл правильно') return email_form() return email_f def password(): password_i = input('Введите пароль: ') tmp_upper = tmp_lover = tmp_digit = tmp_sam = 0 if len(password_i) > 7 and password_i.count(' ') == 0: for i in password_i: if i.isupper(): tmp_upper = 1 elif i.islower(): tmp_lover = 1 elif i.isdigit(): tmp_digit = 1 elif not i.isspace(): tmp_sam = 1 if tmp_upper + tmp_lover + tmp_digit + tmp_sam == 4: print('Пароль подходит') else: print('В пароле не должно быть пробелов, минимум одна буква в нижнем регистре, ' 'одна буква в верхнем регистре и одна цыфра и спецсимвол. Введите пароль еще раз.') return password() password_i2 = input('Введите пароль еще раз для подтверждения: ') if password_i != password_i2: print('Пароли не савпадают!') return password() else: return password_i def save_user(*args): with open(file_path, 'a') as f: print(*args, file=f) def print_register(phone, email, password_): print( f'\nПоздравляем с успешной регистрацией!\n' f'Ваш номер телефона: {phone}\n' f'Ваш email: {email}\n' f'Ваш пароль: {len(password_) * "*"}\n' ) return def num_users(): list_users = [] count_user = 0 with open(file_path, 'r') as f: f.seek(0) for i in f.readlines(): list_users.append(i[:-1]) count_user += 1 print(f'\nКоличество зарегистрированых пользователей: {count_user}') return list_users def num_list_users(list_user): index_user = 1 str_phone = '' for i in list_user: i = i.split(' ') user_name = i[0] str_phone += f'{index_user}. {user_name}\n' index_user += 1 return print(str_phone) def info_user(list_user): chois_num = input('Для отображения детальной информации пользователя, выберите порядковый номер :') if chois_num.isdigit(): chois_num = int(chois_num) - 1 else: return info_user(list_user) if chois_num in range(1, len(list_user)): info_print = list_user[chois_num].split(' ') return print(f'\nНомер телефона: {info_print[0]}\n' f'Емейл: {info_print[1]}\n' f'Пароль: {info_print[2]}\n') print(f'\nВыберите число от 1 до {len(list_user)}') return info_user(list_user) def main(): choice_var = choice() if choice_var == 1: number_phone_var = number_phone() check_phone(number_phone_var) email_form_var = email_form() password_var = password() user = f'{number_phone_var} {email_form_var} {password_var}' save_user(user) print_register(number_phone_var, email_form_var, password_var) return main() elif choice_var == 2: num_users_var = num_users() yes_no = input('Отобразить всех пользователей? (да/нет): \n') if yes_no == 'да': num_list_users(num_users_var) info_user(num_users_var) elif yes_no == 'нет': return main() else: print('Нужно ввести "да" или "нет"\n') return main() if __name__ == '__main__': main()
#Recursividad # def fibo(n): # if n > 1: # return fibo(n-1) + fibo(n-2) # elif n==1 or n == 0: # return 1 # elif n < 0: # print('Valor inválido') # print(fibo(16)) #Ejemplos # Cuenta regresiva # def cuenta_regresiva(num): # num -= 1 # if num > 0: # print(f'{num}') # cuenta_regresiva(num) # else: # print('Se terminó el conteo') # #print('Fin de la función', {num}) # cuenta_regresiva(7)
# Importing specific functions from a module is possible. from math import sqrt # Entire module can be imported as well. import math # Some functions are available by default. a = [1, 2, 3] len(a) # "sqrt" function can be called upon specific to get its square root. sqrt(4) # Number "pi" can be accessed via "math" library. print(math.pi) # New functions can be defined as well. def func_1(): print("Running \"func_1\".") func_1() # Note that to "call" or "invoke" a function we need to use the "()". Calling the function without "()" will only give its memory location. # Arguments can be passed to the function. Annotations can be used to tell the function what are the expected argument types. def func_2(a: int, b: int): return a * b print(func_2(2, 3)) # Still, any argument type can still be passed to the function. print(func_2("a", 3)) # Even lists can be passed. print(func_2([1, 2], 3)) # However, strings are not supported by the "*" operator. The next line is commented because it would throw an error otherwise. # print(func_2("a", "b")) # Calling the function without the arguments will just print its definition and memory location. print(func_2) # Functions can call other functions in their execution. def func_3(): return func_4() def func_4(): return print("Running func_4") func_3() # Still, the proper order of execution is essential. The next lines are commented because they would throw an error otherwise. # def func_5(): # return func_6() # func_5() # def func_6(): # return print("Running func_5") # Lambda functions are also present in Python. fn1 = lambda x: x**2 print(fn1(2))
# Andrew Li # 1824794 print("Birthday Calculator") print("Please enter all values numerically.\n") current_day = int(input("Enter current day: ")) # asks user for date input and converts to int current_month = int(input("Enter current month: ")) current_year = int(input("Enter current year: ")) print("Current day: {1}/{0}/{2}\n".format(current_day, current_month, current_year)) # prints date more readably birth_day = int(input("Enter birth day: ")) # asks for inputs like above, but for birthday birth_month = int(input("Enter birth month: ")) birth_year = int(input("Enter birth year: ")) print("Birthday: {1}/{0}/{2}\n".format(birth_day, birth_month, birth_year)) age = 0 # initializes age if current_month <= birth_month: # checks if birthday has passed compared to current day if current_day < birth_day: # if the current month and day is before birthday, user has not aged a full year age = (current_year - birth_year) - 1 # program "rounds down" age to last fully completed year else: age = current_year - birth_year # age print("You are", age, "years old.") # prints age if current_day == birth_day and current_month == birth_month: # if month and day match, it is user's birthday print("Happy Birthday!")
"""A simple program to create a GUI to communicate with an Arduino and toggle an LED on and off. Created to demonstrate how to use Python with tkinter to create a GUI. - Colin Diehl """ from tkinter import * #import the modules for the GUI import serial #and the serial communications PORT = "COM5" ser = serial.Serial(PORT, 9600) #start the serial com w/ 9600 baudrate class Application(Frame): #create the class for the GUI to run def __init__(self, master): Frame.__init__(self, master) self.grid() # create the grid on the GUI for the part to snap onto self.create_widgets() #the function to create the GUI parts def create_widgets(self): #define all GUI parts self.label = Label(self) #create a label self.label["text"] = "Use the button to toggle the LED on and off:" #set the text of the label self.label.grid( row = 0, column = 0)#snap the label to the top left of the grid self.button = Button(self) #create a button self.button["text"] = "LED: OFF" #set the original text of the button self.button["height"] = 2 #set the height of the button to 2 characters tall self.button["width"] = 12 #set the button width to 12 characters wide self.button["command"] = self.toggle #the function the button will run when pressed self.button.grid(row = 1, column = 0) #snap the button to the second row of the grid self.button["bg"] = "green" self.text = Text(self) #create a text box self.text["height"] = 2 #set the text box height to 2 characters self.text["width"] = 20 #set the text box width to 20 characters self.text.grid(row = 2, column = 0) #snap the text box to the third row of the grid self.end = Button(self) #create another button to end the program self.end["text"] = "END" #set the text on the button self.end["height"] = 2 #set the button height to 2 characters self.end["width"] = 12 #set the button width to 12 characters self.end["bg"] = "yellow" #set the background color of the button to red self.end["command"] = self.quit #the quit function the button will run self.end.grid(row = 2, column = 1, sticky = E) #snap the button to the right side of the third row, second column( def toggle(self): #define the function from the first button index_dict={"OFF": "ON" , "ON": "OFF"} #define a sequence that switches from off to on to off index[0] = index_dict[index[0]] #progresses through the sequence, toggling the inital string in the sequence self.button["text"] = "LED: " + str(index[0]) #updates the button text with the current state of the LED if index[0] == "OFF": #when the inital string is off ser.write(bytes("a", encoding="ascii")) #writes lowercase a into the serial com, Arduino reads and sets output low self.text.delete(0.0, END) #deletes the contents of the text box self.text.insert(0.0, "The LED is OFF") #inserts the string into the text box to display OFF state of the LED self.button["bg"]="green" if index[0] == "ON": #when the inital string is on ser.write(bytes("A", encoding="ascii")) #writes uppercase A into the serial com, Arduino reads and sets output high self.text.delete(0.0, END) #clears the text box self.text.insert(0.0, "The LED is ON") #inserts the string into the text box to display ON state of the LED self.button["bg"] = "red" def quit(self): #define the function to kill the program ser.write(bytes("a", encoding="ascii")) #write lowercase a into serial com, to make sure LED goes off when program ends ser.close() #close the serial communication root.destroy() #destroy the GUI index = ["OFF"] #set the intial string in the sequence to off, LED starts off root = Tk() #these three lines start and run the GUI window in a loop root.title("Interface Demo") app = Application(root) root.mainloop()
#The rules used by Pig Latin are as follows: #If a word begins with a vowel, just as "yay" to the end. For example, "out" is translated into "outyay". #If it begins with a consonant, then we take all consonants before the first vowel and we put them on the end of the word. # For example, "which" is translated into "ichwhay". #regex pyg = "ay" vowel = ["a", "e", "i", "o", "u"] class translate: @classmethod def get_word(cls): #gets the words to be translated global original original= (input('Welcome to the Pig Latin Translator! Enter some text : ')).lower() @staticmethod def change(): #makes what the user said into a list to be iterated through global wordlist wordlist = original.split() @classmethod #this cycles the functions in this class to be repeated for every new phrase def cycle(cls): global conend global word conend = [] for word in wordlist: cls.Conword() print(' '.join(conend)) cls.again() @classmethod def again(cls): #asks the user if they want to translate something again ans = (input("Anything else to translate? (y/n) : ")).lower() if "y" not in ans: quit() cls.get_word() cls.change() cls.cycle() @classmethod #changes each individual word into its proper translation def Conword(cls): ConFirst = [] x = 0 if len(word) > 0 and word[0] not in vowel: for letter in word: #iterate through the string to find the first vowel if letter in vowel: new_org = word[x:] #This is the first vowel set the rest of the string to print first break #break to get out of the for loop to prevent adding anything else getting add else: ConFirst.append(letter)#Add letter to the ConFirst to then add to the end of Conword followed by pyg x += 1 Conword = new_org + ''.join(ConFirst) + pyg conend.append(Conword) elif len(word) > 0 and word[0] in vowel: vowel_word = word + 'yay' conend.append(vowel_word) else: print("Entry is invalid") cls.again() t = translate t.get_word() t.change() t.cycle()
import Utils def do_Jarvis(point_list): """ Jarvis March method to solve Convex Hull :param point_list: set of Utils.Points :return: hull_list: list of Utils.Points on hull """ hull_list = [Utils.get_lowest_point(point_list)] for hull_point in hull_list: next_point = point_list[0] for p in point_list: if Utils.is_left_turn(hull_point, p, next_point): next_point = p if next_point != hull_list[0]: hull_list.append(next_point) return hull_list
class Node: def __init__(self,data): self.__data=data self.__next=None def get_data(self): return self.__data def set_data(self,data): self.__data=data def get_next(self): return self.__next def set_next(self,next_node): self.__next=next_node class LinkedList: def __init__(self): self.__head=None self.__tail=None def get_head(self): return self.__head def get_tail(self): return self.__tail def add(self,data): temp1=Node(data) if(self.__head==None): self.__head=temp1 self.__tail=temp1 else: self.__tail.set_next(temp1) self.__tail=temp1 #Remove pass and copy the code you had written to add an element. def display(self): temp2=LinkedList() temp2=self.__head while(temp2 is not None): print(temp2.get_data()) temp2=temp2.get_next() #Remove pass and copy the code you had written to display the element(s). def find_node(self,data): temp=self.__head while(temp is not None): if(temp.get_data()==data): return(temp.get_data()+"found") temp=temp.get_next() return None #Remove pass and copy the code you had written to find the node containing the element. def insert(self,data,data_before): tem=Node(data) if(data_before==None): tem.set_next(self.__head) self.__head=tem if(self.__head.get_next()==None): self.__tail=tem else: temp1=self.__head while(temp1 is not None): if(data_before==temp1.get_data()): tem.set_next(temp1.get_next()) temp1.set_next(tem) if(tem.get_next()==None): self.__tail=tem temp1=temp1.get_next() return("error") #Remove pass and copy the code you had written to insert an element. def delete(self,data): temp=self.__head if(temp.get_data()==data): head=temp.get_next() del(temp) return while(temp is not None): if(temp.get_data()==data): temp1=temp temp=temp.get_next() del(temp1) return else: temp=temp.get_next() print("error") #Remove pass and write the logic to delete an element. #You can use the below __str__() to print the elements of the DS object while debugging def __str__(self): temp=self.__head msg=[] while(temp is not None): msg.append(str(temp.get_data())) temp=temp.get_next() msg=" ".join(msg) msg="Linkedlist data(Head to Tail): "+ msg return msg list1=LinkedList() #Add all the required element(s) #Delete the required element. list1.add("salt") list1.add("sugar") print(list1.find_node("milk")) list1.insert("milk","salt") list1.insert("teabags","sugar") list1.display() #list1.delete("Sugar") list1.display() ''' Created on Jan 22, 2020 @author: Admin '''
# 1. Create a dictionary called zodiac with the following inforation. # Each key is the name of the zodiac # zodiac = { # "Aries" : "The Warrior", # "Taurus" : "The Builder", # "Gemini" : "The Messenger", # "Cancer" : "The Mother", # "Leo" : "The King", # "Virgo" : "The Analyst", # "Libra" : "The Judge", # "Scorpio" : "The Magician", # "Sagittarius" : "the Gypsy", # "Capricorn" : "the Father", # "Aquarius" : "The Thinker", # "Pisces" : "TheMystic", # } # # 1a. Retrieve information about your zodiac from the zodiac dictionary # zodiac["Gemini"] # get a var by name # zodiac.get['whatever'] #checks if the item is in the dictyonary or returns None # "whatever" in zodiac #checks if it's there - returns boolean # # 2. Given the following dictionary # phonebook_dict = { # 'Alice': '703-493-1834', # 'Bob': '857-384-1234', # 'Elizabeth': '484-584-2923' # } # # 2a. Print Elizabeth's phone number # print(phonebook_dict['Elizabeth']) # # 2b. Add a entry to the dictionary: Kareem's number is 938-489-1234. # phonebook_dict["Kareem"] = "938-489-1234" # # 2c. Delete Alice's phone entry. # del phonebook_dict['Alice'] # # 2d. Change Bob's phone number to '968-345-2345'. # phonebook_dict['Bob'] = "968-345-2345" # # 2e. Print all the phone entries. # print(phonebook_dict.items()) # for key, value in phonebook_dict.items(): # print(key) # print(value) # 3. Nested dictionaries # ramit = { # 'name': 'Ramit', # 'email': '[email protected]', # 'interests': ['movies', 'tennis'], # 'friends': [ # { # 'name': 'Jasmine', # 'email': '[email protected]', # 'interests': ['photography', 'tennis'] # }, # { # 'name': 'Jan', # 'email': '[email protected]', # 'interests': ['movies', 'tv'] # } # ] # } # # 3a. Write a python expression that gets the email address of Ramit. # print(ramit['email']) # # 3b. Write a python expression that gets the first of Ramit's interests. # print(ramit['interests'][0]) # # 3c. Write a python expression that gets the email address of Jasmine. # print(ramit['friends'][0]['email']) # # 3d. Write a python expression that gets the second of Jan's two interests. # print(ramit['friends'][1]['interests'][1]) # 4. Letter Summary # Write a letter_histogram function that takes a word as its input, # and returns a dictionary containing the tally of how many times # each letter in the alphabet was used in the word. For example: # def histogram(word): # count = {} # for i in word: # if i not in count: # count[i] = 1 # else: # count[i] += 1 # return count # print(histogram("banana")) # >>>letter_histogram('banana') # {'a': 3, 'b': 1, 'n': 2} # Word Summary # Write a word_histogram function that takes a paragraph of text as its input, and returns a dictionary containing the tally of how many times each word in the alphabet was used in the text. For example: def histogram2(paragraph): count = {} text = paragraph.lower().split(" ") for i in text: if i not in count: count[i] = 1 else: count[i] +=1 return count v = histogram2('To be or not to be be be be') print(v) # >>> word_histogram('To be or not to be') # 3. Sorting a histogram # Given a histogram tally (one returned from either letter_histogram or word_histogram), print the top 3 words or letters. def sort(a): return sorted(a.items(), key=lambda r: r[1], reverse=True) print(sort(v)) # def histogram3(string): # freq = {} # for i in string: # freq[i] = freq.get(i,0) + 1 # return freq # print(histogram('banananana')) # dc pass: narf # 3. Sorting a histogram # Given a histogram tally (one returned from either letter_histogram or word_histogram), print the top 3 words or letters. def top3(dict): topList = [] for i in range(0, 3): max1 = (max(dict.values())) for item in dict: if dict[item] == max1: topList.append(item) break del dict[item] print(topList) top3(LetterSummary.letter_histogram("bananas ssssss"))
# Created by: Aden Rao # Created on: March 2nd, 2019 # This program you put in the diameter of a circle and it will calculate the area and circumference of the circle. # Input for the user to put the diameter in diameter = int(input( ' enter the diameter: ')) # Math calculations and formulas import math circumference = 2 * (math.pi * (diameter/2)) area = math.pi * (diameter/2) ** 2 print( "The circumference is " + str(circumference)) print( "The area is " + str(area)) # Prints than you end = input ('Thank You!')
# Automatic scheduler for CMU PreCollege Program import sys import math # Class to handle times. class TimeStamp: # Reference day in order to keep track of which day each TimeStamp is # The first day of the year 2000 was a Saturday (6 = Saturday) referenceYear = 2000 referenceDay = 6 # Dictionary of day names to their ints dayNameToInt = { "Sunday" : 0, "Monday" : 1, "Tuesday" : 2, "Wednesday": 3, "Thursday" : 4, "Friday" : 5, "Saturday" : 6 } # Dictionay of day ints to their names dayIntToName = { 0 : "Sunday", 1 : "Monday", 2 : "Tuesday", 3 : "Wednesday", 4 : "Thursday", 5 : "Friday", 6 : "Saturday" } # Time Constructor def __init__(self, year = 2018, month = 1, day = 1, hour = 0, minute = 0): self.year = year self.month = month self.day = day self.hour = hour self.minute = minute # Convert time to string def __repr__(self): # Construct the date and time part date = self.reprDate() time = self.reprTime() # Combine the two strings as the output return date + " " + time # Greater than less than comparator. def __gt__(self, timeStamp): # Is the year before or after? If equal, continue if self.year > timeStamp.year: return True if self.year < timeStamp.year: return False # Same process for month and all subsequent times if self.month > timeStamp.month: return True if self.month < timeStamp.month: return False if self.day > timeStamp.day: return True if self.day < timeStamp.day: return False if self.hour > timeStamp.hour: return True if self.hour < timeStamp.hour: return False if self.minute > timeStamp.minute: return True return False # Less than comparator def __lt__(self, timeStamp): return not self.__gt__(timeStamp) # Equal to comparator def __eq__(self, timeStamp): return self.year == timeStamp.year and self.month == timeStamp.month and self.day == timeStamp.day and self.hour == timeStamp.hour and self.minute == timeStamp.minute # Less than or equal to operator def __le__(self, timeStamp): return self.__lt__(timeStamp) or self.__eq__(timeStamp) # Greater than or equal to operator def __ge__(self, timeStamp): return self.__gt__(timeStamp) or self.__eq__(timeStamp) # Return the date part of the timestamp def reprDate(self): # Construct the strings for each part of the time monthString = str(self.month) if len(monthString) == 1: monthString = "0" + monthString dayString = str(self.day) if len(dayString) == 1: dayString = "0" + dayString yearString = str(self.year) return monthString + "/" + dayString + "/" + yearString # Return the time part of the timeStamp def reprTime(self): hourString = str(self.hour) if len(hourString) == 1: hourString = "0" + hourString minuteString = str(self.minute) if len(minuteString) == 1: minuteString = "0" + minuteString return hourString + ":" + minuteString # Return a copy of the timeStamp def duplicate(self): return TimeStamp(self.year, self.month, self.day, self.hour, self.minute) # Add operator def addTime(self, years, months, days, hours, minutes): # Add starting from minutes, up to years # Add minutes self.minute += minutes while self.minute > 60: self.minute -= 60 self.hour += 1 # Add hours self.hour += hours while self.hour > 24: self.hour -= 24 self.day += 1 # Add days self.day += days while self.day > TimeStamp.determineDaysInMonth(self.year, self.month): self.day -= TimeStamp.determineDaysInMonth(self.year, self.month) self.month += 1 # Revert back to January if too many days have been added if self.month > 12: self.month = 1 self.year += 1 # Add months self.month += months while self.month > 12: self.month -= 12 self.year += 1 # Add years self.year += years # Determine what day of the week the timeStamp is def determineDayOfWeek(self): # How many days are between the reference date and the current date totalDays = 0 # Counter for the current year we are analyzing currentYear = TimeStamp.referenceYear # Counter for the current month we are analyzing currentMonth = 1 # Determine how many days we are passed the reference day # Start by lining up the currentYear to the TimeStamp year while currentYear != self.year: totalDays += TimeStamp.determineDaysInYear(currentYear) currentYear += 1 # Then line up the months while currentMonth != self.month: totalDays += TimeStamp.determineDaysInMonth(currentYear, currentMonth) currentMonth += 1 # Then add the extra days totalDays += (self.day - 1) # Now determine what day of the week it is dayOfTheWeek = (totalDays + TimeStamp.referenceDay) % 7 return dayOfTheWeek # Returns true the the timestamps occur on the same day @staticmethod def isSameDay(timeStamp1, timeStamp2): if timeStamp1.year == timeStamp2.year and timeStamp1.month == timeStamp2.month and timeStamp1.day == timeStamp2.day: return True else: return False # Create a timestamp from a given date. Setting the time of day to midnight @staticmethod def createDayFromString(string): # Try creating the time try: month = int(string[0 : 2]) day = int(string[3 : 5]) year = int(string[6 : 10]) return TimeStamp(year, month, day, 0, 0) except: print("ERROR: Unable to parse " + string + " as a day") sys.exit() # In order to input a time, it must be in this format: MM/DD/YYYY HH:mm (Where MM, DD, HH, and mm are all two digit numbers) @staticmethod def createTimeFromString(string): # Try creating the time try: month = int(string[0 : 2]) day = int(string[3 : 5]) year = int(string[6 : 10]) hour = int(string[11 : 13]) minute = int(string[14 : 16]) return TimeStamp(year, month, day, hour, minute) except: print("ERROR: Unable to parse " + string + " as a time") sys.exit() # Determine how many days are in this month @staticmethod def determineDaysInMonth(year, month): # January if month == 1: return 31 # February if month == 2: if (year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0): return 29 return 28 # March if month == 3: return 31 # April if month == 4: return 30 # May if month == 5: return 31 # June if month == 6: return 30 # July if month == 7: return 31 # August if month == 8: return 31 # September if month == 9: return 30 # October if month == 10: return 31 # November if month == 11: return 30 # December if month == 12: return 31 # Determine how many days are in a certain year @staticmethod def determineDaysInYear(year): # Account for leap years. if (year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0): return 366 return 365
# coding: utf-8 # wallet = 5000 # computer_price = 900 # # vérifier que le prix de l'ordinateur est inférieur a 1000e # if computer_price < 1000: # print("le prix de l'ordinateur est inférieur à 1000") # else: # print("le prix de l'ordinateur est supérieur à 1000") # while wallet > computer_price: # print("Vous acheté un ordinateur, il vous reste {}e".format(wallet)) # wallet -= computer_price #SYSTÉME DE VÉRIFICATION DE MOT DE PASSE # password = '' # def is_valid(): # enter_password = input("Entré votre mot de passe pour vous connecté") # if enter_password == password: # print("Bravo vous étes connecté !") # else: # print("Votre mot de passe n'est pas bon") # def mdp(): # password = str(input("entré votre mot de passe")) # print(password) # password_confirm = str(input("confirmé votre mot de passe")) # print(password_confirm) # if password == password_confirm: # print(password) # else: # print("Votre mdp n'est pas valide") # if __name__ == "__main__": # mdp() password = input("Entrer votre mot de passe") password_lenght = len(password) if password_lenght <= 8: print("mot de passe est trop court !") else: print("Mot de passe valide !") print(password_lenght)
i=9 j=1 while j<=9: print(j*' '+i*'* ') i=i-2 j=j+2 i=3 j=7 while i<=9: print(j*' ' + i*"* ") i=i+2 j=j-2
__author__ = 'Orka' import random class MovieRandom(object): def __init__(self, movie_list): self.movie_list = movie_list def return_random_movie(self): if type(self.movie_list) is list: list_length = len(self.movie_list) random_number = random.randrange(list_length) random_movie = self.movie_list[random_number] return random_movie elif self.movie_list == 'No movie of this length.': return self.movie_list else: return 'Movie list is empty'
""" For this week's exercise I want you to write a function that accepts a sequence (a list for example) and returns a new iterable (anything you can loop over) with adjacent duplicate values removed. For example: >>> compact([1, 1, 1]) [1] >>> compact([1, 1, 2, 2, 3, 2]) [1, 2, 3, 2] >>> compact([]) [] There are two bonuses for this exercise. I recommend solving the exercise without the bonuses first and then attempting each bonus separately. For the first bonus, make sure you accept any iterable as an argument, not just a sequence (which means you can't use index look-ups in your answer). ✔️ Here's an example with a generator expression, which is a lazy iterable: >>> compact(n**2 for n in [1, 2, 2]) [1, 4] As a second bonus, make sure you return an iterator (for example a generator) from your compact function instead of a list. ✔️ This should allow your compact function to accept infinitely long iterables (or other lazy iterables). """ from typing import Iterable def compact(sequence: Iterable) -> Iterable: iterator = iter(sequence) curr = object() for n in iterator: if n != curr: yield n curr = n
def start(): print ("You are trapped in a room. ", end="") room0() def process_user_movement(description, doors): #Print description of room print(description, end=" ") #Print available doors print("There are %s doors in the room:" %len(doors)) for key in doors.keys(): print (str(key)+" door") #print(*list(doors.keys()), sep=", ") #Prompt for choice choice = 0 while choice != "exit": choice = input("Which direction would you like to go? ") #Valid input is a key to the doors dictionary if choice in doors: doors[choice]() #If invalid prompt for choice again else: print("Invalid entry.") def room0(): #Description description = "This room is large." #doors doors = {"East":room1, "South":room2} #where those doors go process_user_movement(description, doors) def room1(): #Description description = "This room is cramped." #doors doors = {"West":room0, "South":room3} #where those doors go process_user_movement(description, doors) def room2(): #Description description = "This room is musky." #doors doors = {"North":room0, "East":room3} #where those doors go process_user_movement(description, doors) def room3(): #Description description = "This room is moldy." #doors doors = {"North":room1, "East":room4, "West":room2} #where those doors go process_user_movement(description, doors) def room4(): #Description description = "Congratulations! You've made it outside!" choice = "exit" start()
def calculate_total_cost(default_tax_rate, state_abbr, cost): """ Calculate an item cost by adding tax appropriate for state. For example:: >>> calculate_total_cost(5, "CA", 20) 21.4 >>> calculate_total_cost(10, "AK", 10) 11.0 >>> calculate_total_cost("", "ME", 10) 10.5 """ if state_abbr == "CA": default_tax_rate = float(7) /100 elif default_tax_rate: default_tax_rate = float(default_tax_rate) /100 else: default_tax_rate = float(5) /100 total_cost = (default_tax_rate * cost) + cost return total_cost ##################################################################### def is_berry(fruit): """ Takes a fruit name as a string and returns a boolean if the fruit is a strawberry, cherry, or blackberry. For example:: >>> is_berry("Strawberry") True >>> is_berry("cherry") True >>> is_berry("ham") False """ berries = ["strawberry", "cherry", "blackberry"] for berry in berries: if fruit.lower() == berry: return True return False def shipping_cost(fruit): """ Calculates shipping cost. Requires fruit name to be passed and the is_berry function. For example:: >>> shipping_cost("Strawberry") '0' >>> shipping_cost("banana") '5' """ if fruit: result = is_berry(fruit) if result == True: return '0' elif result == False: return '5' else: return None def is_hometown(town_name): """ Takes a town name and tells if it is your hometown.. For example:: >>> is_hometown("San Francisco") True >>> is_hometown("Anchorage") False """ hometown = "San Francisco" if town_name == hometown: return True else: return False def full_name(first_name, last_name): """ Takes a first and last name and returns full name. For example: >>> full_name("Manisha", "Patel") 'Manisha Patel' >>> full_name("Sam", "Spade") 'Sam Spade' """ return first_name + " " + last_name def hometown_greeting(town_name, first_name, last_name): """ Prints a personalized greeting. For example: >>> hometown_greeting("San Francisco", "Manisha", "Patel") Hi Manisha Patel, we're from the same place! """ greeting = full_name(first_name, last_name) if is_hometown(town_name): msg = "Hi {}, we're from the same place!".format(greeting) else: msg = "Hi {}, where are you from?".format(greeting) print msg ##################################################################### def increment(y, x=1): """ Increment passed value by the value. For example: >>> increment(5) 6 >>> increment(15, 4) 19 """ def add(y): result = x + y return result result = add(y) #print result return result addfive = increment(0, 5) addfive = increment(20) addfive = increment(5) def join_numbers(number, list_of_numbers): """ takes in a number and a list of numbers. It should append the number to the list of numbers and return the list. For example: >>> join_numbers(2, [3, 4, 5]) [3, 4, 5, 2] """ list_of_numbers.append(number) return list_of_numbers # 3. Make a function that takes in a number and a list of numbers. It should append # the number to the list of numbers and return the list. ##################################################################### # END OF ASSESSMENT: You can ignore everything below. if __name__ == "__main__": import doctest print result = doctest.testmod() if not result.failed: print "ALL TESTS PASSED. GOOD WORK!" print
def init(_maxcount=20): #Initiate scoreboard global scoreboard global maxcount scoreboard = [] maxcount = _maxcount def addScore(name, score, descend = True): #Add score to scoreboard global scoreboard scoreboard.append((name,score)) scoreboard = sorted(scoreboard, key=lambda scoreboard: scoreboard[1], reverse = descend) if(len(scoreboard)>maxcount): #if scoreboard has more scores than its max delete the smallest score del scoreboard[len(scoreboard)-1] def clearScore(): #clear scoreboard global scoreboard scoreboard = [] def setMaxCount(_maxcount): #Set max score count global maxcount maxcount = _maxcount def getName(index): #get name of certain index global scoreboard return scoreboard[index][0]; def getScore(index): #get score of certain index global scoreboard return scoreboard[index][1]; def main(): #for testing init() print ("Press Ctrl+C to exit \n") while(True): name = raw_input("Please write your name: ") score = int(raw_input("Please write your score: ")) addScore(name, score) print("name / score\n") for i in range(len(scoreboard)): print "%s / %d" %(getName(i), getScore(i)) main()
#Made for the sole purpose of GCI 2019 import sys import os import socket ip = input("Enter IP: ") z=0 try: m1= int(input("Enter starting port:")) m2=int(input("Enter the last port:")) if m2<m1: print("Please enter a valid range") elif m2>m1: for i in range(m1,m2+1): connection=socket.socket(socket.AF_INET,socket.SOCK_STREAM) if connection.connect_ex((ip,i))==0: print("Port{",i,"}:Open") z+=1 connection.close() print("Scan Complete", z, "port(s) are open.") except: print("Host Ip can't be resloved, please try again!")
for i in range(1,10): for j in range(1,i + 1): print(i, "*", j, "=", i*j, end=" ") print(end="\n")
class ConsoleInterface: def __init__(self, quiz): self.__quiz = quiz def run(self): while self.__quiz.has_next_question(): question = self.__quiz.get_next_question() answer = input(question + ' (True/False): ') correct = self.__quiz.check_answer(answer) if correct: print('Your answer is correct!\n\n') else: print('Your answer is wrong!\n\n') print('Your score is: ' + str(self.__quiz.get_score()))
#!/usr/bin/env python3 # * # * * # * * * # * * * * # * * * * * # * * * * # * * * # * * # * count = 5 for i in range(count): for j in range(i): print("*",end = "") #end = "" disables newline print("") print("*****") for i in range(count,0,-1):#range([start,] stop [, step]) -> range object for j in range(i): print("*",end = "") #end = "" disables newline print("")
#!/usr/bin/env python3 import re #regex lib pwd = (input("Enter your pass: ")) if (len(pwd)>8 and re.search("[a-z]",pwd) and re.search("[A-Z]",pwd)): print("valid pass") else: print("Invalid pass")
# What is the difference between these two pieces of code? list1 = [1,2,3,4,5] list2 = [1,2,3,4,5] def proc(mylist): mylist = mylist + [6, 7] #return mylist #print proc(list1) def proc2(mylist): mylist.append(6) mylist.append(7) #return mylist #print proc2(list1) # Can you explain the results given by the print statements below? print "demonstrating proc" print list1 proc(list1) print list1 print print "demonstrating proc2" print list2 proc2(list2) print list2 # Python has a special assignment syntax: +=. Here is an example: list3 = [1,2,3,4,5] list3 += [6, 7] # Does this behave like list1 = list1 + [6,7] or list2.append([6,7])? Write a # procedure, proc3 similar to proc and proc2, but for +=.
''' list1 = [0, 1, 2] list1 += [3, 0.5, 9] list1.sort() list1.reverse() print list1 list1.append(10) list2 = [3, 4, 5] list1.append(list2) list3 = list1 + list2 print list1 #print list2 #print list3 ''' import random print "Random number generated: " + str(random.randint(0,10))
# Given your birthday and the current date, calculate your age # in days. Compensate for leap days. Assume that the birthday # and current date are correct dates (and no time travel). # Simply put, if you were born 1 Jan 2012 and todays date is # 2 Jan 2012 you are 1 day old. # IMPORTANT: You don't need to solve the problem yet. # Just brainstorm ways you might approach it! year = 16 leap = year % 100 #print leap #def isLeapYear(year): #print isLeapYear(2016) ## # Your code here. Return True or False # Pseudo code for this algorithm is found at # http://en.wikipedia.org/wiki/Leap_year#Algorithm ## #def daysBetweenDates(y1, m1, d1, y2, m2, d2): ## # Your code here. ## #return days ### Define a simple nextDay procedure, that assumes ### every month has 30 days. ### For example: ### nextDay(1999, 12, 30) => (2000, 1, 1) ### nextDay(2013, 1, 30) => (2013, 2, 1) ### nextDay(2012, 12, 30) => (2013, 1, 1) (even though December really has 31 days) def nextDay(year, month, day): if day < 30: return year, month, day + 1 else: if month == 12: return year +1, 1, 1 else: return year,month + 1, 1 #print nextDay(1999, 12, 32)
from random import randint def random_verb(): random_num = randint(0, 1) if random_num == 0: return "run" else: return "kayak" #print random_verb() def random_noun(): random_num = randint(0, 1) if random_num == 0: return "sofa" else: return "llama" #print random_noun() def word_transformer(word): if "NOUN" in word: return random_noun() if "VERB" in word: return random_verb() else: return word[0] test_string_1 = "This is a good NOUN to use when you VERB your food" test_string_2 = "I'm going to VERB to the store and pick up a NOUN or two." # This is the solution that has been propossed by Sean ( the guy who teaches intro to programming nanodegree). It's far more complicated than expected and it doesn't seem to work def process_madlib(madlib): processed = " " index = 0 box_frame = 4 while index < len(madlib): frame = madlib[index:index + box_frame] to_add = word_transformer("NOUN") processed += to_add if len(to_add) == 1: index += 1 else: index += 4 return processed print process_madlib(test_string_1) #print process_madlib(test_string_2)
# Wednesday, December 7, 13:16, Odense, Denmark # Define a procedure, median, that takes three # numbers as its inputs, and returns the median # of the three numbers. # Make sure your procedure has a return statement. def bigger(a,b): if a > b: return a else: return b def biggest(a,b,c): return bigger(a,bigger(b,c)) #print biggest(3,5,7) #print bigger (5,9) def median(a,b,c): higher = biggest(a,b,c) if higher==a: return bigger (b,c) if higher==b: return bigger(a,c) else: return bigger(a,b) print(median(3,1,2)) print(median(7,8,7)) print(median(9,3,6)) print(median(1,2,3)) # the line of codes bellow, are part of the figuring out process, which #unfortunately, has failed without solution. '''def smaller(a,b): if a<b: return a else: return b def smallest(a,b,c): return smaller(a, smaller(a,b))''' '''def median(a, b, c): #higher= biggest(a,b,c) #return higher #lower=smallest(a,b,c) if a<biggest and a>smallest: return a elif b<higher and b>lower: return b elif c<higher and c>lower: return c else: print ("failure")''' #print( median(1,2,3)) '''print smallest(3,1,2) print smaller (3, 5) print bigger(4, 7) print biggest(4,7,9)''' '''def median(a,b,c): if a!=smallest and a!=biggest: return a if b!=smallest and b!=biggest: return b if c!=smallest and c!=biggest: return c print (median(5, 2, 3))'''
class Ingredient(object): def __init__(self, name, weight): self.name = name self.weight = weight class Pizza(object): dough = '' sauce = '' Ingredients = [] def __init__(self, dough, sauce, price): self.dough = dough self.sauce = sauce self.price = price def __str__(self): pizza_internals = '' pizza_internals += "dough = '{}'\n".format(self.dough) pizza_internals += "sauce = '{}'\n".format(self.sauce) for ingr in self.Ingredients : pizza_internals += "{}...............{}\n".format(ingr.name, ingr.weight) pizza_internals += '-----------------------------\n' pizza_internals += "Price\t\t\t{}\n".format(self.price) return pizza_internals class Pepperoni(Pizza): Ingredients = [ Ingredient('pepperoni', 300), Ingredient('tomato', 150), Ingredient('cheese', 200) ] def __init__(self, dough, sauce, price): super().__init__(dough, sauce, price) def __str__(self): return "-----------------------------\n\tPepperoni Pizza\n{}".format(super().__str__()) class Bbq(Pizza): Ingredients = [ Ingredient('pepperoni', 300), Ingredient('tomato', 150), Ingredient('cheese', 200) ] def __init__(self, dough, sauce, price): super().__init__(dough, sauce, price) def __str__(self): return "-----------------------------\n\tBBQ Pizza\n{}".format(super().__str__()) class Order(object): _pizzas = [] pizzas = {} isApproved = False def addPizza(self, pizza): self._pizzas.append(pizza) pizzaName = type(pizza).__name__ if pizzaName in self.pizzas.keys(): self.pizzas[pizzaName] = self.pizzas[pizzaName] + 1 else: self.pizzas[pizzaName] = 1 def removePizza(self, pizza): if self.isApproved : return self._pizzas.remove(pizza) pizzaName = type(pizza).__name__ if pizzaName in self.pizzas.keys(): self.pizzas[pizzaName] = self.pizzas[pizzaName] - 1 def getTotal(self): total = 0 for pizza in self._pizzas: total += pizza.price return total def approve(self): self.isApproved = True class Terminal(object): menu = [Pepperoni('40 cm, round', 'tomato sauce', 450), Bbq('30 cm, square', 'BBQ sauce', 550)] def takeOrder(self): while True: action = input(""" Добро пожаловать! Выберите действие: 1. Сделать заказ 2. Посмотреть меню """) if action == '1': self.currentOrder = Order() print('Ваш заказ успешно создан!') while not self.currentOrder.isApproved: pizzaSelect = input(""" Какую пиццу будете заказывать? 1. Пепперони 2. Барбекю Может быть вы хотите удалить свой выбор из заказа? 3. удалить Пепперони 4. удалить Барбекю """) # print("{}".format(int(pizzaSelect)) if pizzaSelect == "1" or pizzaSelect == "2": self.currentOrder.addPizza(self.menu[int(pizzaSelect)-1]) elif pizzaSelect == '3' or pizzaSelect == '4': self.currentOrder.removePizza(self.menu[int(pizzaSelect)-3]) else: print('Не понял вас, попробуйте еще раз...') continue approve = input('Вы подтверждаете свой заказ? [Да/Нет]') if approve == 'Да': self.currentOrder.isApproved = True print('Повторю ваш заказ:') print(self.currentOrder.pizzas) print('Итого : {}'.format(self.currentOrder.getTotal())) break elif approve == 'Нет': continue if action == '2': for pizza in self.menu: print(pizza) ######################################################################################################## pizza_Pepperoni = Pepperoni('40 cm, round', 'tomato sauce', 450) pizza_BBQ = Bbq('30 cm, square', 'BBQ sauce', 550) order = Order() order.addPizza(pizza_Pepperoni) order.addPizza(pizza_Pepperoni) order.addPizza(pizza_BBQ) print(order.pizzas) print(order.getTotal()) order.removePizza(pizza_Pepperoni) print(order.pizzas) print(order.getTotal()) terminal1 = Terminal() terminal1.takeOrder() # print(pizza_Pepperoni, end='\n') # print(pizza_BBQ, end='\n')
# Составьте программу relativelyp rime . ру, получающую один аргумент командной строки n и # выводящую таблицу n х n, где • устанавливается в строке i и столбце j, если # наибольший общий делитель i и j состав­ляет 1 (i и j являются относительно простыми множителями), # и пробел в противном случае. import sys a = int(sys.argv[1]) matrix = [["" for j in range(a)] for i in range(a)] def gcd(x,y): while x!=0 and y!=0: if x > y: x = x % y else: y = y % x return x+y for i in range(a): for j in range(a): if gcd(i,j) == 1: matrix[i][j] = '*' else: matrix[i][j] = ' ' for i in range(a): for j in range(a): print(matrix[i][j],end="") print (" ",end = "") print ("\n")
# В отличие от гармонических чисел, сумма последовательности 1/12 + 1/22 + + ... + 1/п2 действительно сходится к # константе при п, стремящемся к бес­конечности. (Поскольку эта константа -тr2/6, данная формула использу­ется для вычисления # значения числа л.) Какой из следующих циклов for вычисляет эту сумму? # Подразумевается, что n -это целое число 1000000, а переменная total типа float инициализирована значением О. О. # а. for i in range( 1, n+1 ): total += 1 / (i•i) # Ь. for i in range(1, n+1 ): total += 1.0 / i•i # с. for i in range( 1, n+1 ): total += 1.0 / (i•i) # d. for i in range(1, n+1 ): total += 1.0 / (1.0•i•i) total = 0.0 n = 1000000 for i in range(1, n + 1):#это тот цикл total += 1 / (i * i) print('loop1=', total) total = 1.0 for i in range(1, n + 1): total += 1.0 / i * i print('loop2=', total) total = 1.0 for i in range(1, n + 1): total += 1.0 / (i * i) print('loop3=', total) total = 1.0 for i in range(1, n + 1): total += 1.0 / (1.0*i * i) print('loop4=', total)
# Предположим, что х и у имеют тип float и представляют координаты (х, у) точки на Декартовой плоскости. # Составьте выражение для вычисления рас­стояния ОТ ЭТОЙ ТОЧКИ ДО ИСХОДНОЙ. import math x = 3.0 y = 4.0 # т.к. точка исходная, то ее координаты (0,0) print(math.sqrt(x**2 + y**2))
# Студент-физик получил неожиданный результат при использовании кода force = G • mass1 • mass2 / radius * radius # для вычисления значения по формуле F = Gm1m2/r2• Объясните проблему и исправьте код. G = 10 mass1 = mass2 = 5 radius = 10 forceFstCase = G * mass1 * mass2 / radius**2 #1 вариант решения forceSndCase = (G * mass1 * mass2) / (radius * radius) #2 вариант решения print(forceFstCase) print(forceSndCase)
# Составьте программу, получающую два положительных целых чис­ла в аргументах командной строки # и выводящую False, если любой из них больше или равен сумме двух других, и True в противном случае. # (Примечание: этот код проверяет, могут ли эти три числа быть длинами сторон некоего треугольника.) import sys if len(sys.argv) == 4: result1 = (int(sys.argv[2]) + int(sys.argv[3])) > int(sys.argv[1]) result2= (int(sys.argv[1]) + int(sys.argv[3])) > int(sys.argv[2]) result3 = (int(sys.argv[1]) + int(sys.argv[2])) > int(sys.argv[3]) print(result1 and result2 and result3)
# Составьте программу, вычисляющую произведение # двух квадратных ма­триц логических переменных, # используя оператор оr вместо + и оператор and вместо *· import random arraySize = 4 def fillMatrixWithRandomBoolValues(array): array.clear() for i in range(0, arraySize): tmp = [] for i in range(0, arraySize): tmp.append(random.randint(0,100) % 2 == 0) array.append(tmp) def print_array(array): for row in array: for item in row: if(item): print( '*', end = ' ') else: print( '_', end = ' ') print() def checkMatrixSize(matrix): size = len(matrix) if size == 0 : return False for row in matrix: if not len(row) == size: return False return True def addMatrix(matrix1, matrix2): if not (checkMatrixSize(matrix1) and checkMatrixSize(matrix2)): raise ArithmeticError('Для корректной работы метода нужны 2 квадратные матрицы одинакового размера') resultMatrix = [] for i in range(0, len(matrix1)): tmp = [] for j in range(0, len(matrix1)): tmp.append(matrix1[i][j] or matrix2[i][j]) resultMatrix.append(tmp) return resultMatrix def multiplyMatrix(matrix1, matrix2): if not (checkMatrixSize(matrix1) and checkMatrixSize(matrix2)): raise ArithmeticError('Для корректной работы метода нужны 2 квадратные матрицы одинакового размера') resultMatrix = [] for i in range(0, len(matrix1)): tmp = [] for j in range(0, len(matrix1)): tmp.append(matrix1[i][j] and matrix2[i][j]) resultMatrix.append(tmp) return resultMatrix firstArray = [] secondArray = [] fillMatrixWithRandomBoolValues(firstArray) fillMatrixWithRandomBoolValues(secondArray) print('first array = ') print_array(firstArray) print('second array = ') print_array(secondArray) print('Addition of matrix = ') print_array(addMatrix(firstArray,secondArray)) print('Multiplication of matrix = ') print_array(multiplyMatrix(firstArray,secondArray))
# Переделайте программу tenhellos. ру, объединив ее с программой hellos.ру # так, чтобы она получала в аргументе командной строки количество выво­димых строк. # Можно считать, что аргумент меньше 1 ООО. Подсказка: чтобы решить, # когда применять st, nd, rd или th при выводе i-го # сообщения Hello, используйте выражения i % 1 О и i % 100. import sys count = int(sys.argv[1]) for i in range(0, count): remainsOf10 = i%10 remainsOf100 = i%100 if(remainsOf10 )
#!/usr/bin/python3 """ Coins module """ def makeChange(coins, total): """ Function to determine the fewest number of coins """ if total == 0: return 0 coins.sort(reverse=True) sum = 0 i = 0 c = 0 num_coins = len(coins) while sum < total and i < num_coins: while coins[i] <= total - sum: sum += coins[i] c += 1 if sum == total: return c i += 1 return -1
# Crie uma função que receba os valores do nome, # idade e e-mail de uma pessoa e guarde-os em um # dicionário com as chaves ‘nome’, ‘idade’ e ‘email’, # respectivamente. Sua função deve retornar esse dicionário. nome = input('Qual seu nome?') idade = input('Qual a sua idade?') email = input('Digite seu e-mail:') def dados(nome,idade,email): dict_dados = { 'nome': nome, 'idade': idade, 'e-mail': email } return dict_dados print(dados(nome,idade,email))
#Faça um programa que peça um número e mostre se ele é positivo ou negativo. x = input('Poderia digitar um número agora?'+ '\n * Digite 1 = SIM ou 2 = NÃO *\n') if x == '1': n = int(input('Digite um número:')) if n>=0: print ("positivo") else: print ("negativo") else: print('Fechar programa') print('Obrigado por utilizar nossa solução!')
#Faça um programa que peça um valor monetário e aumente-o em 15%. Seu programa deve imprimir a mensagem “O novo valor é [valor]”. x = float(input('Digite um valor monetário:')) y = x*0.15 resp = x + y print('O novo valor é de:', resp)
# Faça uma função que recebe o valor do raio de um círculo e # retorna o valor do comprimento de sua circunferência: C = 2*pi*r. import math raio = 10 def circunferencia(raio): circu = 2*(math.pi)*raio return circu print(circunferencia(raio))
# Faça uma função que recebe valores a, b e c, resolve a equação quadrática a*x**2 + b*x + c = 0 e retorna: # a. o valor de Δ onde Δ = b**2- 4*a*c # b. uma tupla com o valor do ponto de mínimo ou máximo: x_m = -b/(2*a) e y_m = -Δ/(4*a); # c. uma lista contendo as raízes (a lista pode ser vazia, caso Δ<0; pode conter apenas # um elemento, caso Δ = 0; ou conter duas raízes, caso Δ> 0). a = 5 b = 10 c = 3 x_m = -b/(2*a) y_m = -(100)/(4*a) print(x_m,y_m ) def delta(a,b,c): delta = (b**2) - (4*a*c) x_m = -b/(2*a) y_m = -delta/(4*a) if delta < 0: lista = [] return {"delta":delta, "x_m":[x_m], "y_m":[y_m], "raizes":lista} elif delta == 0: lista = [] x1 = (-b+ delta**(1.0/2.0)) / (2.0*a) x2 = (-b- delta**(1.0/2.0)) / (2.0*a) lista.append(x1) lista.append(x2) return {"delta":delta, "x_m":[x_m], "y_m":[y_m], "raizes":lista} else: lista = [] x1 = (-b+ delta**(1.0/2.0)) / (2.0*a) x2 = (-b- delta**(1.0/2.0)) / (2.0*a) lista.append(x1) lista.append(x2) return {"delta":delta, "x_m":[x_m], "y_m":[y_m], "raizes":lista} print(delta(a,b,c))
# Agora faça uma função que recebe uma palavra e diz se ela é um palíndromo, ou seja, se ela é igual a ela mesma ao contrário. # Dica: Use a função do exercício 6. frase = input("Qual a frase? ").upper().replace(" ", "") if frase == frase[::-1]: print("A frase é um palíndromo") else: print("A frase não é um palíndromo")
#Faça um programa em que o usuário tem que adivinhar o número escolhido pelo computador. O computador deve sortear um número inteiro de 1 a 5 e pedir para o usuário tentar descobrir qual o número sorteado. Após o usuário digitar sua resposta, o programa deve dizer se ele acertou ou não. Dica: para sortear um número, você precisará utilizar a biblioteca random. import random x = random.randint(0, 5) y = int(input('Digite um número entre 0 e 5 e veja se acertou!\n')) if x == y: print('Parabéns você acertou na mosca!') else: print('Poxa que pena, não foi dessa vez!')
# Crie uma classe Quadrado, filha da classe Retângulo do exercício 2. class Retangulo: def __init__(self, lado_a, lado_b): self.lado_a = lado_a self.lado_b = lado_b def area(self): x = self.lado_a * self.lado_b return print(f'A área do retângulo é de {x}') class Quadrado(Retangulo): def __init__(self, lado_a, lado_b, lado_a_quadrado, lado_b_quadrado): super().__init__(lado_a, lado_b) self.lado_a_quadrado = lado_a_quadrado self.lado_b_quadrado = lado_b_quadrado def area_quadrado(self): x = self.lado_a_quadrado * self.lado_b_quadrado return print(f'A área do quadrado é de {x}') retangulo = Retangulo(10, 20) retangulo = Quadrado(10, 20, 2, 6) retangulo.area() retangulo.area_quadrado()
# Crie uma classe Televisor cujos atributos são: # a. fabricante; # b. modelo; # c. canal atual; # d. lista de canais; e # e. volume. # Faça métodos para aumentar/diminuir volume, trocar o canal e sintonizar um novo canal, # que adiciona um novo canal à lista de canais (somente se esse canal não estiver nessa lista). # No atributo lista de canais, devem estar armazenados todos os canais já sintonizados dessa TV. # Obs.: O volume não pode ser menor que zero e maior que cem; só se pode trocar para um # canal que já esteja na lista de canais. class Televisor: def __init__(self, fabricante, modelo, canal_atual, lista_de_canais, volume): self.fabricante = fabricante self.modelo = modelo self.canal_atual = canal_atual self.lista_de_canais = lista_de_canais self.volume = volume def aumentar_diminuir_volume(self): vol = int(input('Qual o volume que você deseja?\n')) if vol > 0 and vol < 101: self.volume = vol return print(f'O novo volume é {self.volume}') else: print('Tente selecionar um valor entre 0 até 100 para continuar...') def trocar_canal(self): canal = input('Qual o canal que você deseja ver agora?\n').upper() if canal in self.lista_de_canais: self.canal_atual = canal return print(f'O novo canal é {self.canal_atual}') else: print(f'Sintonize esse novo canal em sua lista...') def sintonizar(self): canal = input('Qual o canal que você deseja sintonizar?\n').upper() if canal not in self.lista_de_canais: self.canal_atual = canal self.lista_de_canais.append(canal) print(f'Novo canal adicionado em sua lista: {self.lista_de_canais}...') casa1 = Televisor('TCL', 'Smart TV 4K', 'SBT', ['SBT', 'GLOBO', 'SPORTV', 'DISNEY'], 20) casa1.aumentar_diminuir_volume() casa1.trocar_canal() casa1.sintonizar()