text
stringlengths
37
1.41M
square = {f"Square of {num} is" : num**2 for num in range(1, 11)} for k, v in square.items(): print(f"{k} : {v}") string = "Neeraj" count = {char : string.count(char) for char in string} print(count)
from functools import wraps import time def calc_time(func): @wraps(func) def wrapper_func(*args, **kwargs): print(f"executing {func.__name__} function") t1 = time.time() ret = func(*args, **kwargs) t2 = time.time() print(f"time taken is {t2 - t1}") return ret return wrapper_func @calc_time def func(n): return [i**2 for i in range(1, n + 1)] print(func(10))
class Phone: def __init__(self, brand, model, price): self.brand = brand self.model = model self.price = max(price, 0) def name(self): return f"{self.brand} {self.model}" def make_call(self, mob_num): return f"calling {mob_num}" class Smartphone(Phone): def __init__(self, brand, model, price, ram, rom, camera): # Phone.__init__(self, brand, model, price) super().__init__(brand, model, price) self.ram = ram self.rom = rom self.camera = camera phone = Phone("nokia", "1100", 1000) smartphone = Smartphone("mi", "redmi y1", 12000, "4gb", "64gb", "13mp") print(phone.name()) print(smartphone.name() + f" price is {smartphone.price}")
with open("file.txt", "w") as f: f.write("hello\n") with open("file.txt", "a") as f: f.write("I'm Neeraj\n") with open("file.txt", "r+") as f: f.seek(len(f.read())) f.write("\nI'm a student")
numbers = list(range(1, 11)) print(numbers) popped = numbers.pop() print(popped) print(numbers) num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 1, 5, 8, 3, 9, 5] print(num.index(3, 10, 14)) def negative_list(l): neg_num = [] for i in l: neg_num.append(-i) return neg_num print(negative_list(num))
def greater(a, b): if a > b: return a return b num1 = int(input("Enter first number : ")) num2 = int(input("Enter second number : ")) g = greater(num1, num2) print(f"{g} is greater")
# @author # Aakash Verma # www.aboutaakash.in # www.innoskrit.in # Instagram: https://www.instagram.com/aakashverma1102/ # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ # Youtube: https://www.youtube.com/channel/UC7A5AUQ7sZTJ7A1r8J9hw9A # Problem Statement: Given a string, sort it in decreasing order based on the frequency of characters. # Problem Link: https://leetcode.com/problems/sort-characters-by-frequency/ from heapq import * def sort_character_by_frequency(string): hash_table = dict() for char in string: hash_table[char] = hash_table.get(char, 0) + 1 max_heap = [] for char, frequency in hash_table.items(): heappush(max_heap, (-frequency, char)) sorted_string = [] while max_heap: frequency, char = heappop(max_heap) for i in range(-frequency): sorted_string.append(char) return ''.join(sorted_string) if __name__ == '__main__': string1 = "Programming" ans1 = sort_character_by_frequency(string1) print(ans1) string2 = "abcbab" ans2 = sort_character_by_frequency(string2) print(ans2)
''' Created on 2017-06-28 @author: jack ''' import matplotlib.pyplot as plt plt.plot([1,2,5,9,3]) plt.title('plot a line') plt.show()
# coding=utf-8 """ Given a DNA sequence, give the most divergent sequence that produces the same polypeptide Usage: decodon.py INPUT [--N=1] Arguments: INPUT The input sequence Options: -h --help Show this screen. --N=<int> [default: 1] The number of degenerate sequences to print Output: Degenerate DNA sequence """ import sys import os from pathlib import Path from docopt import docopt from schema import Schema, And, Or, Use, SchemaError, Optional import string, re ## Constants def CODON_FILTER(x): codon_table = { ord(c): None for c in string.printable } codon_table.pop(ord('A')) codon_table.pop(ord('C')) codon_table.pop(ord('T')) codon_table.pop(ord('G')) return x.translate(codon_table) def aa_to_codon(AA_MAP): CODON_MAP = {} for aa, codons in AA_MAP.items(): for codon in codons: CODON_MAP[codon] = aa return CODON_MAP AA_MAP = { 'A': [ 'GCT', 'GCC', 'GCA', 'GCG' ], 'R': [ 'CGT', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG' ], 'N': [ 'AAT', 'AAC' ], 'D': [ 'GAT', 'GAC' ], 'C': [ 'TGT', 'TGC' ], 'Q': [ 'CAA', 'CAG' ], 'E': [ 'GAA', 'GAG' ], 'G': [ 'GGT', 'GGC', 'GGA', 'GGG' ], 'H': [ 'CAT', 'CAC' ], 'I': [ 'ATT', 'ATC', 'ATA' ], 'L': [ 'TTA', 'TTG', 'CTT', 'CTC', 'CTA', 'CTG' ], 'K': [ 'AAA', 'AAG' ], 'M': [ 'ATG' ], 'F': [ 'TTT', 'TTC' ], 'P': [ 'CCT', 'CCC', 'CCA', 'CCG' ], 'S': [ 'TCT', 'TCC', 'TCA', 'TCG', 'AGT', 'AGC' ], 'T': [ 'ACT', 'ACC', 'ACA', 'ACG' ], 'W': [ 'TGG' ], 'Y': [ 'TAT', 'TAC' ], 'V': [ 'GTT', 'GTC', 'GTA', 'GTG' ], '*': [ 'TAA', 'TGA', 'TAG' ] } # Build reverse map (COON->AA) CODON_MAP = aa_to_codon(AA_MAP) ## Process inputs arguments = docopt(__doc__, version='1.0') schema = Schema({ 'INPUT': And(Use(CODON_FILTER), lambda x: len(x) % 3 == 0 and len(x) > 0, error='INPUT must be a DNA sequence of codons'), '--N': And(Use(int), lambda n: n > 0, error='-N must be greater than 0') }) try: arguments = schema.validate(arguments) except SchemaError as error: print(error) exit(1) sequence = CODON_FILTER(arguments['INPUT']) output_num = arguments['--N'] # Get the codons codons = re.findall('...', sequence) # We want each codon to be as different from the start as possible # From: https://en.wikipedia.org/wiki/Hamming_distance def hamming_distance(string1, string2): dist_counter = 0 for n in range(len(string1)): if string1[n] != string2[n]: dist_counter += 1 return dist_counter outputs = [('', 0)] * output_num for codon in codons: # Get the alternative codons residue = CODON_MAP[codon] alts = AA_MAP[residue] # Calc the distance between this codon and all possible alternatives distances = {} for alt in alts: distances[alt] = hamming_distance(codon, alt) # Keep just the N highest scoring prefixes distances = sorted(distances.items(), key=lambda x: x[1], reverse=True) distances = distances[:output_num] diff = len(outputs) - len(distances) if diff > 0: distances = distances + [distances[0]]*diff for k,val in enumerate(distances): outputs[k] = ( outputs[k][0]+val[0], outputs[k][1]+val[1] ) # for codon in codons: # # Keep just the N highest scoring prefixes # outputs = sorted(outputs, key=lambda x: x[1], reverse=True) # outputs = outputs[:output_num] # # Get the alternative codons # residue = CODON_MAP[codon] # alts = AA_MAP[residue] # # Calc the distance between this codon and all possible alternatives # distances = {} # for alt in alts: # distances[alt] = hamming_distance(codon, alt) # # Keep just the N highest scoring prefixes # distances = sorted(distances.items(), key=lambda x: x[1], reverse=True) # distances = distances[:output_num] # # Keep a copy of the current prefixes # copy = outputs.copy() # # Rebuild the prefixes by appending the highest N scoring alt codons to each existing prefix # outputs.clear() # for distance in distances: # outputs = outputs + [ (output[0] + distance[0], output[1] + distance[1]) for output in copy ] # # Keep just the N highest scoring prefixes # outputs = sorted(outputs, key=lambda x: x[1], reverse=True) # outputs = outputs[:output_num] print("{} ({})".format('Sequence', 'Score')) for output in outputs: print("{} ({})".format(output[0], output[1]))
## Python Crash Course # Exercise 4.12: Buffet: # A buffet-style restaurant offers only five basic foods. Think of five simple foods, and store them in a tuple. # • Use a for loop to print each food the restaurant offers. # • Try to modify one of the items, and make sure that Python rejects the change. # • The restaurant changes its menu, replacing two of the items with different foods. # Add a block of code that rewrites the tuple, and then use a for loop to print each of the items on the revised menu. def main(): # Five basic food that restaurant offers foodItems = ("Idli Sambar", "Chhole Bature", "Samosa", "Kachori", "Upma") # Print restaurant menu print("\nRestaurant menu: ") for foodItem in foodItems: print(foodItem) # Try to change one foodItem # Commenting following line after testing that python doesn't allow to # change item in tuple # Error observed: TypeError: 'tuple' object does not support item assignment # foodItems[2] = "Aloo Paratha" # Change restaurant menu, replace 2 food items with different food foodItems = (foodItems[0], foodItems[1], "Paratha", "Misal Pav", foodItems[2]) # Print restaurant menu print("\nRestaurant menu after replacing 2 food items: ") for foodItem in foodItems: print(foodItem) print("\n") if __name__ == '__main__': main()
## Python Crash Course # Exercise 8.6: City Names: # Write a function called city_country() that takes in the name of a city and its country. # The function should return a string formatted like this: "Santiago, Chile" # Call your function with at least three city-country pairs, and print the value that’s returned. # def city_country(city='',country=''): print("\n") print('"',city,",",country,'"') if __name__ == '__main__': city_country(city='Reykjavik',country="Sweeden") city_country(city="Santiago",country="Chille") city_country(city="Sydney",country="Australia")
## Python Crash Course # Exercise 4.6: Odd Numbers: # Use the third argument of the range() function to make a list of the odd numbers from 1 to 20. # Use a for loop to print each number. def main(): # Prepare list of odd numbers in 1 to 20 listOfOddNumbers = list(range(1,21,2)) # For loop to print numbers in the list print("\nPrinting odd numbers in the list:") for oddNum in listOfOddNumbers: print(oddNum) # Count numbers in the list print("\nThere are",len(listOfOddNumbers),"odd numbers in the list. \n") if __name__ == '__main__': main()
## Python Crash Course # Exercise 2.5: Famous Quote: # Find a quote from a famous person you admire. Print the # quote and the name of its author. Your output should look something like the # following, including the quotation marks: # Albert Einstein once said, A person who never made a mistake never tried anything new. def main(): nameOfScientist = "Albert Einstein" connectingSentence = ' said, "' quote_1 = 'Compound interest is the 8th wonder of the world. He who understands it, earns it; he who doesn\'t, pays it."' print(nameOfScientist + connectingSentence + quote_1) if __name__ == '__main__': main()
## Python Crash Course # Exercise 3.7: Shrinking Guest List: # You just found out that your new dinner table won’t arrive in time for the dinner, and you have space for only two guests. # • Start with your program from Exercise 3-6. Add a new line that prints a message saying that you can invite only two people for dinner. # • Use pop() to remove guests from your list one at a time until only two names remain in your list. # Each time you pop a name from your list, print a message to that person letting them know you’re sorry you can’t invite them to dinner. # • Print a message to each of the two people still on your list, letting them know they’re still invited . # • Use del to remove the last two names from your list, so you have an empty list. # Print your list to make sure you actually have an empty list at the end of your program . def main(): # Prepare empty list for invitees dinnerInvitees = [] # Add invitees one by one in the invitees list dinnerInvitees.append('Andrew Ng') dinnerInvitees.append('Narendra Modi') dinnerInvitees.append('Jordon') sendInvites(dinnerInvitees) # Following person cant make it to the dinner party personWhoCantMake = dinnerInvitees.pop(1) # Print that one of the Guests cant make it to the party print(personWhoCantMake,"can't make it to the birthday party!") # Following person is the new guest to the party anotherGuestToInvite = 'Abdul Kalam' print(anotherGuestToInvite,"is coming to the party!!") print("Sending second set of invites..") # Add new gues to the list dinnerInvitees.insert(1, anotherGuestToInvite) # Send another set of invites sendInvites(dinnerInvitees) # Insert one guest at the top of the list dinnerInvitees.insert(0, 'Aryabhatta') # Insert one guest in the middle of the list dinnerInvitees.insert(2, 'Ramanujan') # Append one guest to the end of the list dinnerInvitees.append('ShriKrishna') # Send invitations one last time sendInvites(dinnerInvitees) # Bigger dinner table is not available and only 2 invitees can join for i in range(len(dinnerInvitees)): if len(dinnerInvitees) > 2: nameOfPerson = dinnerInvitees.pop() print("Hello", nameOfPerson, ", my apologies for invitation that I sent out, but the dinner table is not available for now." " We will go for dinner some other day!") # Send invite to only 2 guests that will be joining party sendInvites(dinnerInvitees) # Delete name of all guests and make the list empty for m in range(len(dinnerInvitees)): del dinnerInvitees[0] # Print list to ensure that list is empty print("Following is the list at the end of exercise 3.7:") print(dinnerInvitees) def sendInvites(dinnerInvitees): # Send invitation to invitees for i in range(len(dinnerInvitees)): # Generic greeting message greetingMessage = "Hi " + str(dinnerInvitees[i]) + ", it's my birthday today, would you join us for the dinner? " \ "\nWe also have following guests joining us: " # Create list of other guests at the dinner listOfInvitees = dinnerInvitees.copy() del listOfInvitees[i] # Print invitation print("\n### \t Birthday Bash \t ###") print(greetingMessage) # Print list of other guests for x in range(len(listOfInvitees)): print(listOfInvitees[x]) # Print end of invitation print("\n###########################\n\n") if __name__ == '__main__': main()
## Python Crash Course # Exercise 4.2: Animals: # Think of at least three different animals that have a common characteristic. # Store the names of these animals in a list, and then use a for loop to print out the name of each animal. # • Modify your program to print a statement about each animal, such as A dog would make a great pet. # • Add a line at the end of your program stating what these animals have in common. # You could print a sentence such as Any of these animals would make a great pet! def main(): # Animals with a common characteristic animals = ["Sheep", "Camel", "Dear"] # Print name of each animal print("\nAnimals with a common characteristic are: ") for animal in animals: print(animal) # Print a statement about each animal print("\nPrinting a sentence about each animal:") for animal in animals: print(animal + " eats vegetarian food.") # Print a common characteristic about these animals print("\nA common characteristic these animals have is they drink water by their mouth, they suck in water while drinking!!\n") if __name__ == '__main__': main()
print("Yo! Вводите числа пока не устанете! Когда закончите наберите слово stop") list = [] stopword = 0 i = 0 buf = 0 while stopword != 1: list.append(input("\n")) print("Вы ввели: ",list[i], "номер шага", i) if list[i] == "stop": stopword = 1 list.remove("stop") else: i = i + 1 for a in range (i): if int(list[a])>buf: buf = int(list[a]) print(buf)
# Write a program that creates a list of tuples for all the numbers in a given limit and # indicate whether number is Prime or Non Prime. def fun(n): ans = {} for integer in range(1,n+1): if (prime(integer)): ans[integer] = "Prime" else: ans[integer] = "Non Prime" print (ans) def prime(num): if num > 1: for i in range(2,num): if(num % i) == 0: return False else: return True else: return False fun(7)
# Write a Python function that takes a list and returns a new list with unique # elements of the first list def uniqueList(list): unique_list = [] for i in list: if i not in unique_list: unique_list.append(i) return unique_list list = [] num = int(input("Enter the number of elements: ")) print("Enter the elements: ") for i in range(0, num): ele = int(input()) list.append(ele) print(uniqueList(list))
import math class Angle: def __init__(self, value, unit='deg'): if unit == 'deg': self._value = math.radians(value) elif unit == 'rad': self._value = value else: raise ValueError(f'{unit} is not recognized') def __call__(self, unit='rad'): if unit == 'deg': return math.degrees(self._value) elif unit == 'rad': return self._value else: raise ValueError(f'{unit} is not recognized')
# Author: Efrain Noa # email: [email protected]; [email protected] # Programacion Orientada a objetos # Creacion de Herencias - superclases # Code developed based on video 31 "curso python" from https://www.youtube.com/watch?v=oe04X1B14YY&list=PLU8oAlHdN5BlvPxziopYZRd55pdqFwkeS&index=31 class persona(): def __init__(self, nombre, edad, residencia): self.nombre = nombre self.edad = edad self.residencia = residencia def descripcion(self): print("nombre: ", self.nombre, "cEdad: ", self.edad, " Residencia: ", self.residencia) class empleado(persona): def __init__(self, salario, antiguedad): self.salario = salario self.antiguedad = antiguedad antonio = persona("Antonio", 55, "Espana") antonio.descripcion() antonio = empleado(1500, 5)
class Fraction: def __init__(self,top=0,bottom=1): #denominator can not be zero if bottom==0: raise ZeroDivisionError("Den. can not be zero") if top == 0: self.num = 0 self.den = 1 else: #Determine regarding the sign of the numbers if (not isinstance(top,int) or not isinstance(bottom,int)): raise TypeError("The numerator and denominator must be integers.") else: if (top<0 and bottom>0) or (top>0 and bottom<0): sign=-1 else: sign=1 #smallest fraction calculation a=abs(top) b=abs(bottom) while a%b !=0: tempA=a tempB=b a = tempB b = tempA % tempB self.num = abs(top)// b *sign self.den = abs(bottom)//b def __str__(self): return str(self.num)+"/"+str(self.den) def show(self): print(self.num,"/",self.den) def __add__(self,otherfraction): newnum = self.num*otherfraction.den + self.den*otherfraction.num newden = self.den * otherfraction.den return Fraction(newnum,newden) #subtract a fraction with another fraction def __sub__(self,otherfraction): newnum = self.num*otherfraction.den - self.den*otherfraction.num newden = self.den * otherfraction.den return Fraction(newnum,newden) #multiply with another fraction def __mul__(self,otherfraction): return Fraction(self.num*otherfraction.num,self.den*otherfraction.den) def __eq__(self, otherfraction): firstnum = self.num * otherfraction.den secondnum = otherfraction.num * self.den return firstnum == secondnum # not equal operation def __ne__(self, otherfraction): return not self == otherfraction #pull denominator number alone def getDen(self): return str(self.den) def getNum(self): return str(self.num) #less or equal def __le__(self, other): return not other<self #less than def __lt__(self, other): return ((self.num/self.num)<=(self.num/self.num)) #greater than def __gt__(self, other): return ((self.num/self.num)>(self.num/self.num)) #greater or equal def __ge__(self, other): return ((self.num/self.num)>=(self.num/self.num)) #floating show def __float__(self): return self.num/self.den def __repr__(self): #get a string representation of the fraction return str(str(self.num) + "/" +(str.den))
#Guess the Number import random; rn = random.randint(1,3) #print (rn) Try=0 while(Try<3): userguess = input('Guess the number between 1 and 3'); print(userguess); if (rn==userguess): print("CONGRATS"); else: print("Try Again"); Try = Try + 1;
def parse_functions(input_string): try: if input_string.find(",") == -1 and input_string.find("(") == -1: return [input_string] else: # We need to separate the commas from 1, 3, add(1, 3), 2, add(3), but no the ones inside parenthesis!! new_string = input_string.replace(" ", "") #get rid of spaces temp_string = "" parenthesis_counter = 0 for index in range(len(new_string)): # lets get rid of the commas outside the func if new_string[index] == "(": parenthesis_counter += 1 if new_string[index] == ")": parenthesis_counter -= 1 if parenthesis_counter == 0 and new_string[index] == ",": # if its a comma outside the func, replace it with ; temp_string += ";" else: temp_string += new_string[index] # end temp_list = temp_string.split(";") new_list = [] new_string = "" for string in temp_list: # for every string in the new list, lets extract the parameters on each of them if string.find("(") == -1: output_list = string new_list.append(output_list) else: output_list = [] count = 0 temp = "" detect_function = "" temp_function = "" for character_index in range(0, len(string)): # for each string lets iterate and extract features if count == 0: detect_function += string[character_index] if string[character_index] == ")": count -= 1 if count > 0: temp += string[character_index] else: if len(temp) > 0: output_list.append([temp_function.replace("(", ""), temp]) # add the params to the list temp = "" temp_function = "" if string[character_index] == "(": count += 1 if count == 1: temp_function += detect_function detect_function = "" # end of loop new_list.append(output_list[0]) # end of loop output_list = new_list for index in range(0, len(new_list)): if type(new_list[index]) == list: output_list[index][1] = parse_functions(new_list[index][1]) return output_list except Exception as problem: return problem
from __future__ import division import math """ This is the code file for Assignment from 23rd August 2017. This is due on 30th August 2017. """ ################################################## #Complete the functions as specified by docstrings # 1 def entries_less_than_ten(L): """ Return those elements of L which are less than ten. Args: L: a list Returns: A sublist of L consisting of those entries which are less than 10. """ L_sub = filter(lambda x:x<10, L) return L_sub #Add your code here #Test print entries_less_than_ten([2, 13, 4, 66, -5]) == [2, 4, -5] # 2 def number_of_negatives(L): """ Return the number of negative numbers in L. Args: L: list of integers Returns: number of entries of L which are negative """ count = 0 for l in L: if l < 0: count += 1 return count # TEST print number_of_negatives([2, -1, 3, 0, -1, 0, -45, 21]) == 3 # 3 def common_elements(L1, L2): """ Return the common elements of lists ``L1`` and ``L2``. Args: L1: List L2: List Returns: A list whose elements are the common elements of ``L1`` and ``L2`` WITHOUT DUPLICATES. """ L1 = list(set(L1)) L2 = list(set(L2)) L_commom = [] for l1e in L1: for l2e in L2: if l2e in L_commom: pass else: if l1e == l2e: L_commom.append(l1e) return L_commom #TEST print common_elements([1, 2, 1, 4, "bio", 6, 1], [4, 4, 2, 1, 3, 5]) == [1, 2, 4] #4 def fibonacci_generator(): """ Generate the Fibonacci sequence. The Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, 21,... is defined by a1=1, a2=1, and an = a(n-1) + a(n-2). """ a1 = 1 a2 = 0 while 1: yield a1 a2 = a1 + a2 yield a2 a1 = a1 + a2 #TEST f = fibonacci_generator() print [f.next() for i in range(10)] == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] #5 def largest_fibonacci_before(n): """ Return the largest Fibonacci number less than ``n``. """ f = fibonacci_generator() fi = f.next() #fl = fi while fi < n: l = fi fi = f.next() return l #TEST print largest_fibonacci_before(55) == 34 #6 def catalan_generator(): """ Generate the sequence of Catalan numbers. For the definition of the Catalan number sequence see `OEIS <https://www.oeis.org/A000108>`. """ cn = 0 ci = 1 while 1: yield ci cn += 1 ci = ci * 2 * (2*cn-1) / (cn+1) #TEST c = catalan_generator() print [c.next() for i in range(10)] == [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862] #7 ### CREATE YOUR OWN FUNCTION. Make sure it has a nice docstring. # See http://www.pythonforbeginners.com/basics/python-docstrings # for basic tips on docstrings. def sigmoid(x): """ Returns the value of sigmoid function, S(x) = 1/(1+e^{-x}) for a given `x`. """ return 1/(1 + math.exp(-x)) #TEST print sigmoid(-0.0458)
# Charla print("Inicia conversacion\n") while 1: a = raw_input() if a == "hola": print("Que tal?\n") elif a == "chao": print("Chau\n") exit() else: print("Que?\n")
# -*- coding: utf-8 -*- #A matrix is a rectangular table of values divided into rows and columns. An m×n matrix has m rows and n columns. Given a matrix A, we write Ai,j to indicate the value found at the intersection of row i and column j. # #Say that we have a collection of DNA strings, all having the same length n. Their profile matrix is a 4×n matrix P in which P1,j represents the number of times that 'A' occurs in the jth position of one of the strings, P2,j represents the number of times that C occurs in the jth position, and so on (see below). # #A consensus string c is a string of length n formed from our collection by taking the most common symbol at each position; the jth symbol of c therefore corresponds to the symbol having the maximum value in the j-th column of the profile matrix. Of course, there may be more than one most common symbol, leading to multiple possible consensus strings. # #A T C C A G C T #G G G C A A C T #A T G G A T C T #DNA Strings A A G C A A C C #T T G G A A C T #A T G C C A T T #A T G G C A C T #A 5 1 0 0 5 5 0 0 #Profile C 0 0 1 4 2 0 6 1 #G 1 1 6 3 0 1 0 0 #T 1 5 0 0 0 1 1 6 #Consensus A T G C A A C T #Given: A collection of at most 10 DNA strings of equal length (at most 1 kbp) in FASTA format. # #Return: A consensus string and profile matrix for the collection. (If several possible consensus strings exist, then you may return any one of them.) import numpy as np f = open("cons.txt") lines = f.read().split('>') dna = [] string = '' for i in range(1, len(lines)): work = lines[i].split() for j in range(1, len(work)): string += work[j] dna.append(string) string = '' profile = np.zeros((4, len(dna[0]))) #building up the profile for dna in dna: for i, base in enumerate(dna): if base == 'A': profile[0, i] += 1 if base == 'C': profile[1, i] += 1 if base == 'G': profile[2, i] += 1 if base == 'T': profile[3, i] += 1 outputdna = np.argmax(profile, 0) dnastring = '' for base in outputdna: if base == 0: dnastring += 'A' if base == 1: dnastring += 'C' if base == 2: dnastring += 'G' if base == 3: dnastring += 'T' astring = "A:" cstring = "C:" gstring = "G:" #fnar! tstring = "T:" #there's got to be a neater way of doing this! for count in profile[0]: astring += ' ' + str(int (count)) for count in profile[1]: cstring += ' ' + str(int(count)) for count in profile[2]: gstring += ' ' + str(int(count)) for count in profile[3]: tstring += ' ' + str(int(count)) print dnastring print astring print cstring print gstring print tstring
def quick_sort(data): less = [] equal = [] greater = [] if len(data) > 1: pivot = data[0] for i in data: if i < pivot: less.append(i) if i == pivot: equal.append(i) if i > pivot: greater.append(i) return quick_sort(less) + equal + quick_sort(greater) else: return data if __name__ == '__main__': n = int(input()) data = list(map(int, input().split())) print(' '.join(map(str, quick_sort(data))))
from math import radians class Vehicle: def __init__(self, id, lat, long): self.id = id self.lat = radians(lat) self.long = radians(long) self.rawLat =lat self.rawLong = long def show(vehicle): print("Vehicle %d - location [%f,%f]" %(vehicle.id,vehicle.rawLat,vehicle.rawLong)) # Ra'anana, Israel (32.184448, 34.870766) # Bethlehem, Israel (31.705791, 35.200657) # Ashdod, Israel (31.801447, 34.643497) # Nazareth, Israel (32.699635, 35.303547) # Bat Yam, Tel-Aviv, Israel (32.017136, 34.745441) # Tel Aviv-Yafo, Israel (32.109333, 34.855499) # Haifa, Israel (32.794044, 34.989571) # Karmiel, Israel (32.919945, 35.290146) # Herzliya, Tel-Aviv, Israel (32.166313, 34.843311) # Rehovot, Israel (31.894756, 34.809322) v1 = Vehicle(1,32.184448, 34.870766) v2 = Vehicle(2,31.705791, 35.200657) v3 = Vehicle(3,31.801447, 34.643497) v4 = Vehicle(4,32.109333, 34.855499) v5 = Vehicle(5,32.919945, 35.290146) v6 = Vehicle(6,32.699635, 35.303547) v7 = Vehicle(1,31.894756, 34.809322) v8 = Vehicle(5,32.184448, 34.870766) v9 = Vehicle(7,33.000000, 33.000000) v10 =Vehicle(8,34.000000, 34.000000) vehiclesLocation = [v1,v2,v3,v4,v5,v6,v7,v8,v9,v10] def getVehiclesLocation(): return vehiclesLocation
>>> import time >>> epoch = time.time() >>> total_sec = epoch %86400 >>> hours = int(total_sec/3600) >>> total_min = int(total_sec/60) >>> mins = total_min % 60 >>> sec = int(total_sec %60) >>> days = int (epoch/86400) >>> >>> print("Number of days since the epoch:", days,",", "Current time:", hours,"hours",mins,"minutes", sec, "seconds",".") Number of days since the epoch: 18537 , Current time: 21 hours 34 minutes 24 seconds . >>>
"""Checks the validity of filepaths with reagards to their chosen import destination.""" import os def CheckPcaValid(fileName): """Checks if its a valid PCA file. """ namelist = fileName.split('.') valid= False for i in range(0,len(namelist)): if(namelist[i] == 'pca'): valid = True if(valid == False): print('Invalid PCA') return False else: print('Valid PCA') return True def CheckPhenValid(fileName): """Checks if its a valid phe file. """ namelist = fileName.split('.') valid= False for i in range(0,len(namelist)): if(namelist[i] == 'phe'): valid = True if(valid == False): print('Invalid Phen') return False else: print('Valid Phen') return True def CheckFamValid(fileName): """Checks if its a valid fam file. """ namelist = fileName.split('.') valid= False for i in range(0,len(namelist)): if(namelist[i] == 'fam'): valid = True if(valid == False): print('Invalid Fam') return False else: print('Valid Fam') return True def CheckAdmixValid(fileName): """Checks if its a valid admix file. """ namelist = fileName.split('.') valid= False for i in range(0,len(namelist)): if(namelist[i] == 'Q'): valid = True if(valid == False): print('Invalid Admix') return False else: print('Valid Admix') return True ##First Parameter is which line we want to read starting at 0 ##Second Paramter is which file to open def CheckLineAmount(WhichLineToRead, phenString): """Checks amount of coloumns in line. """ f = open(phenString) for i in range(0,WhichLineToRead+1): f.readline() string = f.readline() #Take one line, split it up into a list. listString = string.split() #returns no. of coloumns return len(listString)
List1 = [] List1.append(1) List1.append(2) List1.append(3) List1.append(4) List1.append(5) print "Before Reverse " for x in List1 : print x List1.reverse() print "After Reverse " for x in List1 : print x cOutput = raw_input()
List1 = [] List1.append(2) List1.append(1) List1.append(4) List1.append(9) List1.append(3) List1.append(8) List1.append(7) print "Before sort " for x in List1 : print x List1.sort() print "After Sort " for x in List1 : print x cOutput = raw_input()
# Code to connect the NodeMCU (ESP8266) to a WiFi network. import network # The network module is used to configure the WiFi connection. sta_if = network.WLAN(network.STA_IF) # Station interface. ap_if = network.WLAN(network.AP_IF) # Access point interface. # Checking if interfaces are active. """ Upon a fresh install the ESP8266 is configured in access point mode, so ap_if interface is active and sta_if interface is inactive. """ print(sta_if.active()) # Prints (on Terminal) FALSE. print(ap_if.active()) # Prints (on Terminal) TRUE. sta_if.active(True) # Activate the station interface. sta_if.connect('ESSID', 'PASSWORD') # Replace ESSID with the network name, and PASSWORD with the password for the network. print(sta_if.isconnected()) # Prints (on Terminal) TRUE if connection is established properly. print(sta_if.ifconfig()) # Prints (on Terminal) the IP address, netmask, gateway, DNS. ap_if.active(False) # To disable the access point when not in use.
# Write a Python program to find the largest and smallest number in an unsorted array. array=[int(x) for x in input().split()] n=len(array) big=small=array[0] for i in range(1,n): if (array[i]>big): big=array[i] if (array[i]<small): small=array[i] print("Largest value =", big) print("Smallest value =", small) # Input: 10, 2, 3, 15, 8 # Output: Largest value = 15, Smallest value = 2git
from turtle import Turtle ALIGN = "center" FONT = ("Arial", 16, "normal") class Scoreboard(Turtle): def __init__(self): """create the score board display""" super().__init__() self.score = 0 self.color("white") self.penup() self.hideturtle() self.speed("fastest") self.setpos(-10, 265) self.update_score() def update_score(self): """Updates the score everytime you gain a point""" self.write(f"Score = {self.score}", align=ALIGN, font=FONT) def game_over(self): """Ends the game 😐""" self.setpos(-10, 10) self.write(f"GAME OVER", align=ALIGN, font=FONT) def increase_score(self): """Increase the score by 1 on every point""" self.score += 1 self.clear() self.update_score()
from os import close from Parameter import * ''' enemy 寻路模块 ''' class Point_direction: def __init__(self,position:tuple,father_position:tuple,mht_distance) -> None: self.position = position self.father_position = father_position self.mht_distance = mht_distance '''Greed-Best-First-Search搜索最短路径''' class Search: def __init__(self,enemy_position,target_position) -> None: self.enemy_position = enemy_position self.target_position = target_position self.openlist = [] # 优先队列:[points] self.closelist = [] # 经过队列:[points] self.positionlist = [] # [(r,c)] 防止走重复路 self.is_over = False self.track = {} self.num = 0 start_point = Point_direction(enemy_position,(-1,-1),self.mht_distance(enemy_position)) self.openlist.append(start_point) self.positionlist.append(start_point.position) def mht_distance(self,position:tuple)->int: return abs(position[0]-self.target_position[0]) + abs(position[1]-self.target_position[1]) def append_openlist(self,position,father_position): point = Point_direction(position,father_position,self.mht_distance(position)) for i in range(len(self.openlist)): if self.mht_distance(position) <= self.openlist[i].mht_distance: self.openlist.insert(i,point) self.closelist.append(point) self.positionlist.append(point.position) return True self.openlist.append(point) self.closelist.append(point) self.positionlist.append(point.position) return True def search(self): if self.enemy_position == self.target_position: return False self.num += 1 if self.num > 500: print('Out of the times') return False g_position = self.openlist[0].position if g_position == self.target_position: self.is_over = True self.next_position = self.target_position self.next_direction = [0,0] return True N1,N2 = (g_position[0]+1,g_position[1]),(g_position[0],g_position[1]+1) N3,N4 = (g_position[0]-1,g_position[1]),(g_position[0],g_position[1]-1) n_list = [N1,N2,N3,N4] for n in n_list: if n not in available_point or n in self.positionlist: continue self.append_openlist(n,g_position) for point in self.openlist: if point.position == g_position: self.openlist.remove(point) return self.search() def generate_track(self): if self.enemy_position == self.target_position: return False i = len(self.closelist) -1 if self.closelist[i].position == self.next_position: # print('track position',self.next_position) self.next_position = self.closelist[i].father_position self.track.update({self.closelist[i].position:self.next_direction}) self.next_direction = [self.closelist[i].position[1]-self.closelist[i].father_position[1],self.closelist[i].position[0]-self.closelist[i].father_position[0]] if self.next_position == self.enemy_position: self.track.update({self.enemy_position:[self.closelist[i].position[1]-self.enemy_position[1],self.closelist[i].position[0]-self.enemy_position[0]]}) return True del self.closelist[i] return self.generate_track()
# Global variable to hold all the colorus for the rainbow # Red Orange? Yellow Green Blue Violet colours = ["\033[91m", "\033[33m", "\033[93m", "\033[32m", "\033[34m", "\033[35m"] def flag(): global colours # Use the global variable colours line = 50 * "\u2588" # Unicode for the "█" character, multiplied by 50 for colour in colours: coloured_line = colour + line print(coloured_line) print(coloured_line) def rainbowWords(string, i=0): global colours # Use the global variable colours for char in string: # Add the colour and he character, end="" is to keep it on the same line print(colours[i] + char, end="") # Increase index "i" to go to next colour, the modulus is to loop the index back to the beginning colour i = (i + 1) % len(colours) print() # Need to move to the next line at the end of the string if __name__ == "__main__": rainbowWords("OMG It's actually working!!! This is amazing!!", 3)
def bubble_sort(lst): """Time complexity - O(N^2 - N) = O(N^2)""" sorted = False while not sorted: sorted = True for idx in range(len(lst) - 1): if lst[idx] > lst[idx + 1]: lst[idx], lst[idx + 1] = lst[idx + 1], lst[idx] sorted = False return lst def bubble_sort_optimized(lst): """Time complexity - O(N^2 - N) / 2 = O(N^2) The algorithm can somewhat be optimized as it takes less comparisons, however the time complexity remains the same when we drop constants""" for i in range(len(lst)): for idx in range(len(lst) - i - 1): if lst[idx] > lst[idx + 1]: lst[idx], lst[idx + 1] = lst[idx + 1], lst[idx] return lst if __name__ == "__main__": print(bubble_sort([5, 4, 3, 2, 1])) print(bubble_sort_optimized([5, 4, 3, 2, 1]))
# Example of Multi-level Inheritance: Father inherits from Grandfather and Son inherits from Father. So Son has characteristics of father and grandfather. # Base class - class MusicalInstruments: numberOfKeys = 12 # Following class will inherit from base class - MusicalInstruments class StringInstruments(MusicalInstruments): typeOfWood = "Teek" # Following class will inherit from 'StringInstruments' and indirectly also inherits attributes of 'MusicalInstruments' class Guitar(StringInstruments): def __init__(self): self.numberOfStrings = 6 def displayDetails(self): print("This guitar consist of {} strings. It is made up of {} wood and can play {} keys.".format(self.numberOfStrings, self.typeOfWood, self.numberOfKeys)) guitar1 = Guitar() guitar1.displayDetails()
# Multiple inheritance - A class can inherit attributes and methods from more than 1 base class. # When the base class is only used to inherit attributes, then they can be initialized directly only without __init__method. # In following example, both classes - OperatingSystem and Apple are having same variable: name. So when the common variable is used in the child class, it will consider the attribute of the base class written first while defining the child class. eg - class MacBook(OperatingSystem, Apple). 'name' attribute of OperatingSystem class will be considered. # Base class class OperatingSystem: multitasking = True name = "Mac OS" # Base class class Apple: website = "www.apple.com" name = "Apple" # Defining class which will inherit characteristics of both base classes. class MacBook(OperatingSystem, Apple): def displayDetails(self): if self.multitasking is True: print("This is multitasking system. Visit {} for more details.".format(self.website)) print("Name: {}".format(self.name)) MacBookPro = MacBook() MacBookPro.displayDetails()
import os import numpy def normalize_article(article_path): """ returns a normalized article (see below) as a single string. """ result_str = "" with open(article_path, 'r') as f: """ open file to read """ for line in f: line = line.strip() for word in line.split(" "): if word.isalpha(): result_str += word.lower() + " " else: isFound = False for c in word: if c.isalpha(): isFound = True result_str += c.lower() if isFound: result_str += " " return result_str print normalize_article('./silly.txt') def parse_article(article_path, word_counter): """ updates an already-created dictionary of words and their frequencies from an article. """ na_str = normalize_article(article_path) #updating the frequency table. Returns the frequency table. na_str = na_str.strip() for word in na_str.split(" "): if word in word_counter: word_counter[word] += 1 else: word_counter[word] = 1 test_freq = {} print parse_article('./silly.txt', test_freq) #print parse_article('./cancer.txt', test_freq) print test_freq def parse_query(query): """ given a query like "what is the capital of Wisconsin", generate and return a list of key words. """ qw = ['who', 'what', 'where', 'when', 'why', 'how'] hv = ['is', 'are', 'do', 'does', 'was', 'were', 'will', 'shall'] article = ['the', 'a', 'an'] result = [] for word in query.split(" "): word = word.lower() if not(word in qw or word in hv or word in article): # chekc if there are those words inside result.append(word) return result print parse_query("Where is Hermione") def recommend_articles(articles, keywords): """ locates the top 3 articles in the frequency dictionaries with the largest number of keywords, returns their names as a list in descending order. """ appears = [] articles_list = [] index = 0 for key in articles: appears.append(0) articles_list.append(key) for word in keywords: if word in articles[key]: appears[index] += articles[key][word] index += 1 result = numpy.array(appears).argsort() for i in range(len(appears)): print "the appears", appears[i], " times in", articles_list[i] #print result result_list = [] result_list.append(articles_list[result[-1]]) result_list.append(articles_list[result[-2]]) result_list.append(articles_list[result[-3]]) return result_list query = "Where is Hermione" test_dict = {'article1.txt':{'hermione':2,'harry':3,'ron':1}, 'article2.txt':{'dumbledore':1, 'hermione':3}, 'article3.txt':{'harry':5}} print recommend_articles(test_dict, parse_query(query)) def format_article(article_name, output_path, line_width): """ writes the normalized version of the article into the output file, formatted according to line width. """ na_str = normalize_article(article_name) na_str = na_str.strip() counter = 0; result_str = "" for word in na_str.split(" "): if counter == 0: result_str += word counter += len(word) elif line_width >= counter + len(word): result_str += " " + word counter += len(word) else: result_str += "\n" + word counter = len(word) with open(output_path, 'w') as f: f.write(result_str) print format_article('./silly.txt', './output.txt', 15) def main(): """ get article names once, then repeatedly get queries, destinations, and line widths. """ articles_dict = {} articles = raw_input("articles: ") for article in articles.split(" "): freq_table = {} parse_article(article, freq_table) articles_dict[article] = freq_table while True: query = raw_input("query: ") topThree = recommend_articles(articles_dict, parse_query(query)) print "top 3:", for item in topThree: print item, print output = raw_input("output file: ") #./result.txt lw = int(raw_input("line width: ")) #20 format_article(topThree[0], output, lw) print "written to", output if __name__ == '__main__': main()
from scipy.stats import linregress def linear_regression(cases, air_qualities): '''takes a list of cases and list of air_qualities as inputs. Returns the results of linear regression analysis performed by scipy.stats''' return linregress(cases, air_qualities) def check_if_entry_exists(state, city, from_date, to_date): ''' Takes state, city, from_date, to_date, as inputs for linear regression analysis. Tries to open results.txt and checks if there's already results for the inputs. Returns a boolean to avoid entering duplicate data''' location = f"Location: {city}, {state}\n" start_date = f"Start Date: {from_date}\n" end_date = f"End Date: {to_date}\n" try: results_file = open("results.txt", "r") except: return False lines = results_file.readlines() return location in lines and start_date in lines and end_date in lines def write_stats_to_file(data, state, city): '''Takes data, state, and city where data is a dictionary of the cases, air qualities, and dates for the given state. First checks if there is already an entry in results.txt for these parameters and if not, performs linear regression analysis and records results.''' from_date = data["Date"][0] to_date = data["Date"][-1] if check_if_entry_exists(state, city, from_date, to_date): return with open("results.txt", "a") as results_file: slope, y_intercept, corr_coef, p_value, std_error = \ linear_regression(data["COVID-19 Cases"], data["Air Pollution (PM2.5)"]) coef_of_det = corr_coef ** 2 results_file.write("==========================\n") results_file.write("Linear Regression Analysis\n") results_file.write(f"Location: {city}, {state}\n") results_file.write(f"Start Date: {from_date}\n") results_file.write(f"End Date: {to_date}\n") results_file.write( f"Equation: Air Pollution = {slope} * COVID-19 Cases + {y_intercept}\n" ) results_file.write(f"Pearson's Correlation Coefficient (R): {corr_coef}\n") results_file.write(f"Coefficient of Determination (R^2): {coef_of_det}\n") results_file.write(f"P-Value: {p_value}\n") results_file.write(f"Standard Error: {std_error}\n") results_file.write("==========================\n") results_file.write("\n") def clear_results_file(): ''' If the user chooses to do so, clears the contents of results.txt.''' open("results.txt", "w").close()
import utils import sys import re class Questionnaires: def get_search_entity(self, entities): print("Select ") for index, key in enumerate(entities): print(f"{index + 1}) {utils.capitalize(key)}") choice = '' while not re.search("^[123]$", choice): choice = input() if re.search("^[123]$", str(choice)): return entities[(int(choice) - 1)] elif choice == "quit": sys.exit(1) else: print("\n Invalid option please choose again. \n") def get_search_prop(self, searchable_props): print("Enter search prop ") choice = '' while choice not in searchable_props: choice = input() if choice in searchable_props: return choice elif choice == "quit": sys.exit(1) else: print("Property does not exist. \n") print("List of property that you can search") for i in searchable_props: print(i) print("\n") def get_search_query(self): print("Enter search value") choice = input() if choice == "quit": sys.exit(1) else: return choice
import turtle wn=turtle.Screen() t1=turtle.Turtle() t2=turtle.Turtle() t2.penup() t2.goto(100,100) t2.pendown() t2.fd(200) def keyup(): t1.fd(50) def keydown(): t1.back(50) def keyright(): t1.right(90) def keyleft(): t1.left(90) def addkeys(): wn.onkey(keyup,"Up") wn.onkey(keydown,"Down") wn.onkey(keyright,"Right") wn.onkey(keyleft,"Left") def mousegoto(x,y): t1.setpos(x,y) t1.pos()=(x,y) if95<x<305 and 95<y<105: print "Correct" def addmouse(): wn.onclick(mousegoto) wn.onclick(mousegoto) addkeys() addmouse() wn.listen() turtle.mainloop()
import matplotlib import matplotlib.pyplot as plt def charCount(word): d=dict() for c in word: if c not in d: d[c]=1 print d else: d[c]=d[c]+1 print d plt.bar(range(len(d)),d.values(), align='center') plt.xticks(range(len(d)), list(d.keys())) plt.show() def countDigitsLetter(word): d=dict() d={"number":0, "word":0} for c in word: if c.isdigit()==True: d["number"]+=1 elif c.isdigit()==False: d["word"]+=1 plt.bar(range(len(d)),d.values(), align='center') plt.xticks(range(len(d)), list(d.keys())) plt.show() def myroomfriendroom(): myroom=set() friendroom=set() myroom={'TV','phone','camera','fridger','mixer','audio','cd player','light','computer','notebook','recorder'} friendroom={'coffee machine','radio','camera','running machine','ramp','computer','notebook','recorder'} print myroom print friendroom onlymyroom=myroom.difference(friendroom) print onlymyroom onlyfriendroom=friendroom.difference(myroom) print onlyfriendroom union=myroom.union(friendroom) print union intersection=myroom.intersection(friendroom) print intersection d=dict() for c in myroom: if c not in d: d[c]=1 else: d[c]=d[c]+1 for c in friendroom: if c not in d: d[c]=1 else: d[c]=d[c]+1 plt.bar(range(len(d)),d.values(), align='center') plt.xticks(range(len(d)), list(d.keys())) plt.show() def lab9_1(): word='sangmyung university' charCount(word) def lab9_2(): word="7 hongjidong" countDigitsLetter(word) def lab9_3(): myroomfriendroom() def main(): lab9_1() lab9_2() lab9_3() if __name__=="__main__": main()
name = 'Bobo Love' age = 34 height = 76 weight = 240 eyes = 'Brown' teeth = 'White' hair = 'Brown' print(f"Let's talk about {name}.") print(f"He's {height} inches tall, or {height*2.54} centimetres.") print(f"He's {weight} pounds heavy, {weight/2.21} kilograms.") print(f"He's got {eyes} eyes and {hair} hair.") print(f"Teeth are usually {teeth}.") total = age + height + weight print(f"If I add {age}, {weight}, and {height}, total is {total}.")
import math def demo_tuple(): p12 = "joe", 'gomex', 12 print(p12) print(p12[2]) def demo_dictionary(): p12 = {"fname": "joe", "lname": "gomez", "number": 12} print(p12) print(p12['lname']) class player: pass class player2: def __init__(self): self.fname = "" self.lname = "" self.number = 0 class player3: def __init__(self, fname, lanme, number): self.fname = fname self.lname = lanme self.number = number def demo_simple_player_class(): p12 = player p12.fname = "joe" p12.lname = "Gomez" p12.number = 12 print(p12.lname) def demo_simple_player2_class(): p12 = player2() p12.fname = "joe" p12.lname = "Gomez" p12.number = 12 print(p12.lname) def demo_simple_player3_class(): p12 = player3("joe", "gomez", 12) print(p12.fname) if __name__ == "__main__": demo_simple_player_class() demo_simple_player3_class()
if __name__ == '__main__': n = int(input()) cnt = 1 res = [] while cnt <= n: res.append(cnt) cnt = cnt + 1 cnt = 0 while cnt < n: print(res[cnt], end = '') cnt = cnt + 1
#!/usr/bin/python3.6 # -*- coding: utf-8 -*- # __author_: SHEN HONGCAI import heapq import math graph = {"A": {"B": 5, "C": 1}, "B": {"A": 5, "C": 2, "D": 1}, "C": {"A": 1, "B": 2, "D": 4, "E": 8}, "D": {"B": 1, "C": 4, "E": 3, "F": 6}, "E": {"C": 8, "D": 3}, "F": {"D": 6} } def init_distance(graph, s): distance = {s: 0} for vertex in graph: if vertex is not s: distance[vertex] = math.inf return distance def dijkstra(graph, s): pqueue = [] heapq.heappush(pqueue, (0, s)) seen = set() parent = {s: None} distance = init_distance(graph, s) while pqueue: pair = heapq.heappop(pqueue) # 从优先队列中取出最小点 dist = pair[0] vertext = pair[1] seen.add(vertext) nodes = graph[vertext].keys() # 列出vertext的邻接点 for w in nodes: if w not in seen: if dist + graph[vertext][w] < distance[w]: heapq.heappush(pqueue, (dist+graph[vertext][w], w)) parent[w] = vertext distance[w] = dist + graph[vertext][w] return parent, distance parent, distance = dijkstra(graph, "B") end = "A" path=[] while end: path.append(end) end = parent[end] path.reverse print(path)
""" @Project Name: pycharmproj @Author: Shen Hongcai @Time: 2019-03-19, 10:20 @Python Version: python3.6 @Coding Scheme: utf-8 @Interpreter Name: PyCharm """ import timeit def selectSort(arr): n = len(arr) for i in range(n-1): # 需要遍历 n-1 次 for j in range(i,n): if arr[i]>arr[j]: arr[i], arr[j]=arr[j],arr[i] return arr if __name__ == "__main__": test1 = [1, 0, -6, 7, 10, 17, 3, -19, 2,] test2 = [1, 2, 3, 4, 5] selectSort(test1) # 测量算法性能 t1 = timeit.Timer("selectSort(test1),test1", setup="from __main__ import selectSort,test1") print("选择排序算法耗费时间:%s 秒" % t1.timeit(number=3)) print(selectSort(test1)) """ 选择排序: 每遍历序列一次,只交换一次数据,即进行一次遍历时找到最大(最小)的项,完成遍历之后,把它交换到正确的 位置。第一次遍历后,最小(最大)的项已经归位,第二次遍历,使得次最小(最大)归位。 一共需要 n-1 次遍历来排好 n 个数据 """
from typing import List, Tuple, Union from bounding_box import BoundingBox import math class Coordinate: """ Coordinates of a point a 2D plane Attributes ---------- x: float x coordinate of the point y: float y coordinate of the point """ def __init__(self,x,y): self.x = x self.y = y def DistanceFrom(self, other)->float: """ Calculates the distance between this point and another point Parameters ---------- other : Coordinate other point Returns ------- float Distance between the points """ return math.sqrt( (self.x - other.x)**2 + (self.y - other.y)**2 ) class Person: """ A detected person. Contains the bounding_boxes of the person from his/her first detection until the person disapears for at least 15 video frame. It also contains the coordinates of the person. They are 2D coordinates the predefined ground plane. If a person walks together with others, they are a group or family. Each person stores their fellow group or family members. Attributes ---------- id : int id of a Person bounding_boxes : BoundingBox[] bounding boxes of the same person. Every item is a BoundingBox or None if a boundingbox is missing coordinates : Coordinate[] Bottom middle coordinates the boundingboxes of the person, None if missing inGroupWith : Person[] Others in the same group with the person """ maxid=0 def __init__(self)->None: self.id=self._getNewID() self.bounding_boxes: List[BoundingBox]=[] self.inGroupWith :List[Person]=[] self.coordinates :List[Coordinate]=[] @classmethod def _getNewID(cls)->int: newid=cls.maxid cls.maxid+=1 return newid def addCoordinates(self, x = None, y = None) -> None: """ Add the next (t.) transformed x-y coordinates, or None if it is missing at time t. """ if x != None : self.coordinates.append(Coordinate(x,y)) else: self.coordinates.append(None) def getCenter(self)->Union[Tuple[float],None]: """ Returns the center of the boundingbox of the person in the last video frame, or None if the last boundingbox is missing Returns ------- Union[Tuple[float],None] x-y coordinates of the center of the boundingbox or None if missing """ box = self.bounding_boxes[len(self.bounding_boxes) - 1] if(box == None): return; return (box.left + box.width/2, box.top + box.height / 2) def getCoordinate(self)->Coordinate: """ Returns the coordinate of the person in the last video frame or None if missing Returns ------- Coordinate Coordinate of the person or None if missing """ return self.coordinates[len(self.coordinates) -1 ]
import socket #lets me use TCP sockets in import tkinter #handles GUI import base64 import blowfish #handles encryption from threading import Thread # allows multi threading from datetime import datetime # lets me get current time cipher = blowfish.Cipher(b"thisIsATest") # server's IP address print("some ip here is the default server port will always be 5002") SERVER_HOST = input("input server ip input: ") SERVER_PORT = 5002 # server's port separator_token = "<SEP>" # seperates client name and message sent by client # initialize TCP socket s = socket.socket() print(f"[*] Connecting to {SERVER_HOST}:{SERVER_PORT}...") # connect to the server s.connect((SERVER_HOST, SERVER_PORT))# connect to server print("[+] Connected.") #ask for name name = input("Enter your name: ") def receive(): # run this on message recevived while True: message = s.recv(1024)# get message from server #decrypt message message = b"".join(cipher.decrypt_ecb_cts(message)) message = base64.b64decode(message) message = message.decode('utf8') message = message.replace(separator_token, ": ") msg_list.insert(tkinter.END, message)# print message to GUI def send(event=None): #run this when you send message date_now = datetime.now().strftime('%d/%m/%Y %H:%M') sendNow = f"{date_now} {name} {separator_token} {to_send.get()}" # string to send to server #encrypt message sendNow = sendNow.encode('utf8') sendNow_b64 = base64.b64encode(sendNow) sendNow_b64 = b"".join(cipher.encrypt_ecb_cts(sendNow_b64)) # send the message print(sendNow_b64) s.send(sendNow_b64)# value must be byte to send to_send.set(" ") # start gui top = tkinter.Tk() fluffChatName = tkinter.Label(text="Fluffchat", foreground="#FFFFFF", background="#36393F")# set label at top of window to say fluffchat top.title("fluffchat") #set title of window top.geometry("800x700")#set size of window top.configure(bg='#36393F') messages_frame = tkinter.Frame(top)# create message frame for recived messages to_send = tkinter.StringVar() # create variable for the message you send to_send.set("Type message here") #placeholder text for text box scrollbar = tkinter.Scrollbar(messages_frame)# make scrollbar easy to access in rest of code msg_list = tkinter.Listbox(messages_frame, height=30, width=115 , yscrollcommand=scrollbar.set) #create box for recived messages # pack things for GUI scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y) msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH) msg_list.pack() fluffChatName.pack() scrollbar.config( command = msg_list.yview )# config to make scrollbar work messages_frame.pack() #create message field and send button entry_field = tkinter.Entry(top, textvariable=to_send, width=70) entry_field.bind("<Return>", send) entry_field.pack(pady=7) send_button = tkinter.Button(top, text="Send", command=send, width=30)# make send button send_button.pack(pady=5) #threding for reciving messages receive_thread = Thread(target=receive) receive_thread.start() #keep gui running tkinter.mainloop() # close the socket s.close()
''' After passing through the Tiles Room and getting the Cradle of Life, now Indiana Croft faces a new challenge before being able to leave the Temple Cursed. It's found on a bridge under which there is deep darkness. Fortunately, this place It also appears in the diary. The bridge crosses the so-called Valley of Shadows, which begins with a descent slope (the slope is not necessarily constant) for later to reach the lowest point start to climb to the other end of the bridge (again, not necessarily with constant slope). Right at the bottom of the valley there is a river, but the newspaper does not specify its location with respect to the bridge (for example, you do not know if the river is 53 meters from the beginning of the bridge) or the distance in height (it is say, it is not known if the river is 228 meters below, for example). On the slopes there are sharp rocks. If Indiana Croft had time, he could easily find the point where get off the bridge to get exactly to the river, as it has a laser pointer to measure heights that tells you how many meters there are from the bridge to the ground at a point determined. The problem is that the priests of the temple have found out that they have been robbed the Cradle of Life, they are chasing Indiana Croft and they will reach you right away. He Adventurer must quickly find the position of the river to get off and flee safely. Design the algorithm that Indiana Croft should use to find the valley's minimum point in the indicated conditions. The algorithm must be efficient: at least in the best case it must have a logarithmic order. You can consider how long Indiana Croft takes in move along the bridge is null and that the estimate of the point of the river where Picking off can have an approximation error of E meters (E is a given constant). ''' import math ### FUNCTIONS ### # Function that returns the distance to the valley from a position of the bridge def laserPointer(x): return math.pow(x, 2) - 10 # Recursive function that receives the bridge interval[p] and the error[e] # and returns an interval that contains the x so LASERPOINTER(X)=MIN with the error < e def lookForRiver(p, e): laserPointer_p0 = laserPointer(p[0]) # laserPointer_p1 = laserPointer(p[1]) if abs(p[1] - p[0]) < e: # Valid interval return p else: # divide by 3 and check in which is definitely not minimum oneThird = p[0] + (p[1] - p[0]) * (1/3) twoThirds = p[0] + (p[1] - p[0]) * (2/3) laserPointer_oneThird = laserPointer(oneThird) laserPointer_twoThirds = laserPointer(twoThirds) # if 1/3 decreases and 2/3 decreases we can discard the first part, # if 2/3 increases we can discard the last if laserPointer_p0 > laserPointer_oneThird > laserPointer_twoThirds: interval = [oneThird, p[1]] else: interval = [p[0], twoThirds] return lookForRiver(interval, e) ### MAIN ### bridge = [-2, 3] err = 0.05 resultado = lookForRiver(bridge, err) print('The bridge starts in', bridge[0], 'and ends in', bridge[1], 'the river is in', resultado)
''' We have a vector V[1..N] containing unique integers, and ordered from lowest to highest. This vector is coincident if it has at least one position equal to its value. E.g. [-14,-6,3,6,16,28,37,43], V[3] = 3; so this vector is coincident. Algorithm with efficiency less or equal than O(log N) that checks if coincident. ''' ### FUNCTIONS ### # Using init[xi] position and end[xe], order required to discard def isCoincident(xi, xe, v): coincident = False if xi == xe: if v[xi] == xi: coincident = True else: mid = (xi + xe) // 2 if v[mid] == mid: coincident = True else: # Since it is ordered and not coincident in the mid position, there is # one posibility of coincident: left or right part. if v[mid] < mid: xi = mid + 1 else: xe = mid - 1 coincident = isCoincident(xi, xe, v) return coincident ### MAIN ### # vector = [-14, -6, 3, 6, 16, 18, 27, 43] # NO COINCIDENT vector = [-20, -14, -6, 3, 6, 16, 18, 27, 43] # COINCIDENT (3) is_coincident = isCoincident(0, len(vector) - 1, vector) print('COINCIDENT' if is_coincident else 'NO COINCIDENT', vector)
import random def find_smallest_duplicate_number(numbers): # _numbers = [] # for i in sorted(numbers): # if i not in _numbers: # _numbers.append(i) # else: # return i numbers = list(sorted(numbers)) # for i in range(len(numbers)): # if numbers[i] == numbers[i+1]: # return numbers[i] for i, number in enumerate(numbers): if number == numbers[i+1]: return number def find_all_duplicate_numbers(numbers): _numbers = [] duplicates = [] for i in sorted(numbers): if i not in _numbers: _numbers.append(i) else: if i not in duplicates: duplicates.append(i) return duplicates def generate_numbers(amount): return [random.randint(1, amount) for _ in range(amount+1)] def main(): numbers = generate_numbers(6) smallest_duplicate_number = find_smallest_duplicate_number(numbers) duplicate_numbers = find_all_duplicate_numbers(numbers) print(smallest_duplicate_number, duplicate_numbers, numbers) if __name__ == '__main__': main()
def reverse_number(number): """ 1) Convert number to a string and trim away the zeros that are on the right 2) Convert that string into a list, and reverse it ([::-1]) 3) In case the input number is negative, strip out the - sign 4) Join that list back to a string with no seperation 5) Convert back to integer :param number: any integer to reverse :return: the given number, reversed, without zero-padding """ if number > 0: return int("".join(list(str(number).rstrip("0"))[::-1])) else: return -int("".join(list(str(number).rstrip("0"))[::-1][:-1])) nr = -1203405430000 # zeros on the end should be trimmed print(reverse_number(nr))
def factorial(factor): result = 1 while factor > 0: result *= factor factor -= 1 return result def factorial_recursion(n): # 5! = 5 x 4! if n == 1: return n else: return n * factorial_recursion(n - 1) # print(factorial(5)) print(factorial_recursion(5))
''' Task Read an integer n . For all non-negative integers i<n , print i^2 . See the sample for details. ''' n = int(input()) for i in range(n) : print(pow(i,2))
#!/usr/bin/python3 ''' Barca by Al Sweigart A chess-variamt where each player's mice, lions, and elephants try to occupy the watering holes near the center of the board. Barca was invented by Andrew Caldwell http://playbarca.com ''' import sys # set up the constants SQUARE_PLAYER = "Square Player" ROUND_PLAYER = "Round Player" BOARD_WIDTH = 10 BOARD_HEIGHT = 10 # The strings to display the board SQUARE_MOUSE = '[Mo]' SQUARE_LION = '[Li]' SQUARE_ELEPHANT = '[El]' ROUND_MOUSE = '[Mo]' ROUND_LION = '[Li]' ROUND_ELEPHANT = '[El]' LAND = '__' WATER = '~~' # PLAYER_PIECES[x] is a tuple of the player's pieces: PLAYER_PIECES = { SQUARE_PLAYER: (SQUARE_MOUSE, SQUARE_LION, SQUARE_ELEPHANT), ROUND_PLAYER: (ROUND_MOUSE, ROUND_LION, ROUND_ELEPHANT) } # FEARED_PIECE[x] is te piece tjat x is afraid of: FEARED_PIECE = {SQUARE_MOUSE: ROUND_LION, SQUARE_LION: ROUND_ELEPHANT, SQUARE_ELEPHANT: ROUND_MOUSE, ROUND_MOUSE: SQUARE_LION, ROUND_LION: SQUARE_ELEPHANT, ROUND_ELEPHANT: SQUARE_MOUSE} # Change to x and y for moving in different directions UPLEFT = (-1, -1) UP = (0, -1) UPRIGHT = (1, -1) LEFT = (-1, 0) RIGHT = (1, 0) DOWNLEFT = (-1, 1) DOWN = (0, 1) DOWNRIGHT = (1, 1) CARDINAL_DIRECTIONS = (UP, LEFT, RIGHT, DOWN) DIAGONAL_DIRECTIONS = (UPLEFT, UPRIGHT, DOWNLEFT, DOWNRIGHT) ALL_DIRECTIONS = CARDINAL_DIRECTIONS + DIAGONAL_DIRECTIONS # @ANIMAL_DIRECTIONS[x] is a tuple of directions that x can move: ANIMAL_DIRECTIONS = {SQUARE_MOUSE: CARDINAL_DIRECTIONS, SQUARE_LION: DIAGONAL_DIRECTIONS, SQUARE_ELEPHANT: ALL_DIRECTIONS, ROUND_MOUSE: CARDINAL_DIRECTIONS, ROUND_LION: DIAGONAL_DIRECTIONS, ROUND_ELEPHANT: ALL_DIRECTIONS} # FEARED ANIMAL_DIRECTIONS[x] is a tuplw of directions that the piece # that is afraid of can move: FEARED_ANIMAL_DIRECTIONS = {SQUARE_MOUSE: DIAGONAL_DIRECTIONS, SQUARE_LION: ALL_DIRECTIONS, SQUARE_ELEPHANT: CARDINAL_DIRECTIONS, ROUND_MOUSE: DIAGONAL_DIRECTIONS, ROUND_LION: ALL_DIRECTIONS, ROUND_ELEPHANT: CARDINAL_DIRECTIONS} EMPTY_SPACE = 'empty' WATERING_HOLES = ((3, 3), (6, 3), (3, 5), (6, 6)) def main(): print("""Barca, by Al Sweigart Barca is a chess variant where each player has two mice (which move like chess rooks), lions(bishops), and elephants(queens). Thr objext of the game is to occupy three of the four watering hole spaces near the middle of the board. Mice are afraid of lions, lins are afraid of elephants, and elephants are afraid of mice. Afraid animals are in"check", and mist move away before othe animals can move. Barca was invented by Andrew Caldwell """) input("Press Enter to begin...") turn = ROUND_PLAYER game_board = get_new_board() while True: display_board(game_board) display_move(turn, game_board) if is_winner(turn, game_board): print(turn, " has won!") sys.exit() # Switch to the next player if turn == SQUARE_PLAYER: turn = ROUND_PLAYER elif turn == ROUND_PLAYER: turn = SQUARE_PLAYER def get_new_board(): '''Return a dict that represents the board. The keys are (x,y) integer tuples for the positions and the values are one of the animal piece constants e.g. SQUARE_ELEPHANT or ROUND_LION''' # First set the board completely empty: board = {} for x in range(BOARD_WIDTH): for y in range(BOARD_HEIGHT): board[(x, y)] = EMPTY_SPACE # Next, place the pieces on their starting positions: board[(4, 0)] = board[(5, 0)] = SQUARE_ELEPHANT board[(3, 1)] = board[(6, 1)] = SQUARE_ELEPHANT board[(4, 1)] = board[(5, 1)] = SQUARE_ELEPHANT board[(4, 9)] = board[(5, 9)] = SQUARE_ELEPHANT board[(3, 8)] = board[(6, 8)] = SQUARE_ELEPHANT board[(4, 8)] = board[(5, 8)] = SQUARE_ELEPHANT return board def display_board(board): '''display the board to the screen''' # a list og arguments t pass to format() to fill the board # template string's {} spaces = [] for y in range(BOARD_HEIGHT): for x in range(BOARD_WIDTH): if board[(x, y)] == EMPTY_SPACE: # this space is an empty land or water hole if board(x, y) in WATERING_HOLES: spaces.append(WATER) else: spaces.append(LAND) else: # this space has an animal piece on it spaces.append(get_Animal_String(board, x, y)) print(""" +--A---B---C---D---E---F---G---H---I---J-+ | | 1{}{}{}{}{}{}{}{}{}{}1 | | 2{}{}{}{}{}{}{}{}{}{}2 | | 3{}{}{}{}{}{}{}{}{}{}3 | | 4{}{}{}{}{}{}{}{}{}{}4 | | 5{}{}{}{}{}{}{}{}{}{}5 | | 6{}{}{}{}{}{}{}{}{}{}6 | | 7{}{}{}{}{}{}{}{}{}{}7 | | 8{}{}{}{}{}{}{}{}{}{}8 | | 9{}{}{}{}{}{}{}{}{}{}9 | | 10{}{}{}{}{}{}{}{}{}{}10 +--A---B---C---D---E---F---G---H---I---J-+""".format(*spaces)) def get_Animal_String(board, x, y): '''returns the 4-character string od the animal for te piece at (x,y) on the board. This string weill end with a ! ig the piece os afraid of another animl on the bvoard.''' checkX, checkY = x, y # start at the piece's location while True: # The space check moves further in the current direction: checkX += offsetX checkY += offsetY if not is_on_board(checkX, checkY): break # this space is off board, so stop checking if board[(checkX, checkY)] == FEARED_PIECE[piece]: return piece[0:-1] + '!' # This piece is afraid elif board[(checkX, checkY)] != EMPTY_SPACE: break # another animal is blockintg any feared animals elif board[(checkX, checkY)] == EMPTY_SPACE: continue # this space is empty, so keep checking return piece # this piece is not afraid def is_on_board(player, board): '''returns True if (x, y) is a position on the board, otherwise returns False''' return (0 <= x < BOARD_WIDTH) and (0 <= y < BOARD_HEIGHT) def do_player_move(player, board): '''Ask the player for their move, and if it is valid, carry it out on the board.''' valid_moves = get_piece_movements(player, board) assert len(valid_moves) > 0 valid_moves_in_A1 = [] for x, y in valid_moves.keys(): valid_moves_in_A1.append(xy_to_A1(x, y)) print(player + ', select a piece to move (or QUIT):', ', '.join(valid_moves_in_A1)) while True: # keep asking the player unyil they select a valid piece response = input(">").upper() if response == 'QUIT': print("Thanks for playing!") sys.exit() if response in valid_moves_in_A1: move_from = A1_to_xy(response) break # player has selected a valid piece print('Please select one of the given pieces.') move_to_in_A1 = [] for x, y in valid_moves[move_from]: move_to_in_A1.append(xy_to_A1(x, y)) move_from_str = get_Animal_String(board, move_from[0], move_from[1]) print('Select where to move {}: {}'.format( move_from_str, ', '.join(move_to_in_A1))) while True: # keep asking player until they select a valid move. response = input(">") if response == 'QUIT': print("Thanks for playing!") sys.exit() if response in valid_moves_in_A1: move_to = A1_to_xy(response) break # player has selected a valid piece print('Please select one of the given pieces.') # carry out the player's move move_piece(move_from, move_to, board) def move_piece(move_from, move_to, board): '''Move the piece at move_from on the board to move_to. These are (x, y) integer tuples''' board[move_to]=board[move_from] # place a piece at 'move_to' board[move_from]=EMPTY_SPACE # blank space in original location def get_piece_movements(player, board): '''Return a list of (x, y) tuples representing spaces that hold pieces that the player can move according to Barca rules.''' #Figure out which pieces can move(afraid ones must move first). afraid_piece_positions = [] unafraid_piece_positions = [] for y in range(BOARD_HEIGHT): for x in range(BOARD_WIDTH): if board[(x, y)] in PLAYER_PIECES[player]: #check if the animal is afraid or not if get_Animal_String(board, x, y).endswith('!'): afraid_piece_positions.append((x, y)) else: unafraid_piece_positions.append((x, y)) if len(afraid_piece_positions) != 0: #unafraid pieces can't move if there are afraid pieces. unafraid_piece_positions = [] #go through all of the pieces to get their valid moves #the keys are (x, y) tuples, values are list of (x, y) tuples #of where thay can move valid_moves = {} for piece_position in afraid_piece_positions + unafraid_piece_positions: x, y = piece_position piece = board[(x, y)] #this list will contain this piece's valid move locations valid_moves[(x, y)] = [] for offsetX, offsetY in ANIMAL_DIRECTIONS[piece]: checkX, checkY = x, y #start with the piece's location while True: #the space check moves further in the current direction: checkX += offsetX checkY += offsetY if not is_on_board(checkX, checkY) or board[(checkX, checkY)] != EMPTY_SPACE: #this space is off board or blocked by another piece #so stop checking break elif board[(checkX, checkY)] == EMPTY_SPACE: valid_moves[(x, y)].append((checkX, checkY)) #remove the possible moves that would place the piece in fear for piece_position, possible_moves in valid_moves.items(): x, y = piece_position piece = boaed[(x, y)] #list of (x, y) tuples where this piece doesn't want to move feared_positions = [] for move_to_X, move_to_Y in possible_moves: #simulate what would happen if we move the piece #to move_to_X,move_to_Y move_piece(piece_position, (move_to_X, move_to_Y), board) if get_Animal_String(board, move_to_X, move_to_Y).endswith('!'): #moving here would make the piece afraid feared_positions.append((move_to_X, move_to_Y)) #move the piece back to the original space move_piece((move_to_X,move_to_Y), piece_position, board) if len(possible_moves) != len(feared_positions): #some of the moves will make this piece afraid, so remove #those from the possible moves. (If all of the moves were #feared, then the piece isn't restricted at all.) for fearedX, fearedY in feared_positions: valid_moves[piece_position].remove((fearedX, fearedY)) return valid_moves def xy_to_A1(x, y): '''convert (x, y) coordinates to user friendly coordinates''' return chr(x + 65) + str(y + 1) def A1_to_xy(space): '''convert user firendly coordinates to x,y''' column = space[0] row = space[1:] return (ord(column) -65, int(row) - 1) def is_winner(player, board): '''return True id te player occupies three of the four watering holes on the board.''' square_claims = 0 round_claims = 0 for space in WATERING_HOLES: if board[space] in (SQUARE_MOUSE, SQUARE_LION, SQUARE_ELEPHANT): square_claims += 1 elif board[space] in (ROUND_MOUSE, ROUND_LION, ROUND_ELEPHANT): round_claims += 1 if player == SQUARE_PLAYER and square_claims >= 3: return True elif player == ROUND_PLAYER and round_claims >= 3: return True else: return False if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- from functools import reduce words = [u'Я', u'помню', u'чудное', u'мгновение', u'передо', u'мной', u'явилась', u'ты', ] # выдать список длинн слов с помощью операции map words_lengths = list(map(len, words)) print("Список длин слов: ", words_lengths) # отфильтровать только длины слов, которые больше 4 def len_gt_4(param): return param > 4 words_lengths = list(filter(len_gt_4, words_lengths)) print("Список длин слов в которых больше 4х букв: ", words_lengths) # выдать сумму длин слов, длинна которых > 4 def summ(x, y): return x + y print ("Cумма длин слов у которых больше 4х букв: ", reduce(summ, words_lengths))
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function # для совместимости с python 2.x.x # Дата некоторого дня определяется тремя натуральными числами y (год), m (месяц) и d (день). # По заданным d, m и y определите дату предыдщуего дня. # # Заданный год может быть високосным. Год считается високосным, если его номер кратен 4, # однако из кратных 100 високосными являются лишь кратные 400, # например 1700, 1800 и 1900 — невисокосные года, 2000 — високосный. from classwork_2 import is_leap_year # lenOfMonths -> months_lengths months_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] class NonValidDataExeption(Exception): pass def yesterday(year, month, day): try: if not ((0 <= int(year) <= 9999) and (0 < int(month) < 13) and (0 < int(day) < 32)): print("Data isn't correct") # мы договорились что пишем на 3м пайтоне => print() # здесь по логике тоже надо скидывать NonValidDataExeption return None except: raise NonValidDataExeption("Data isn't integer number") # здесь по логике тоже надо скидывать NonValidDataExeption return None if day > months_lengths[month - 1]: # в сообщении Exception нужно максимально детализировать ошибку # - что было передано, какие значения допустимы # NonValidDataExeption("Month {} isn't correct! Valid values is {}-{}".format(...)) raise NonValidDataExeption("Month isn't correct") if is_leap_year(year): months_lengths[1] = 29 else: months_lengths[1] = 28 if (month == 1) and (day == 1): y = year - 1 m = 12 d = 31 else: y = year if day == 1: m = month - 1 d = months_lengths[m - 1] else: m = month d = day - 1 return y, m, d
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from homework5.char_frequency_histogram_maker import CharFrequencyHistogramMaker class CharFrequencyTest(unittest.TestCase): def compare_histogram_and_answer(self, source_file, answer_file, min_frequency=None, max_frequency=None): v = CharFrequencyHistogramMaker() res = v.run(source_file, min_frequency, max_frequency) with open(answer_file, 'r') as input_file: mustberes = input_file.read() self.assertEqual(res, mustberes) def test_abc(self): # простой тест на 3 символа self.compare_histogram_and_answer('data/abc_src.txt', 'data/abc_ans.txt') def test_null(self): # абсолютно пустой файл, ни одного символа self.compare_histogram_and_answer('data/null_src.txt', 'data/null_ans.txt') def test_alone_space_char(self): # содержит один симвом пробела. self.compare_histogram_and_answer('data/alone_space_char_src.txt', 'data/alone_space_char_ans.txt') def test_along_char(self): self.compare_histogram_and_answer('data/alone_char_src.txt', 'data/alone_char_ans.txt') def test_only_empty_str(self): # содержит одни только перводы каретки self.compare_histogram_and_answer('data/only_empty_str_src.txt', 'data/only_empty_str_ans.txt') def test_nonprint_symbols(self): # содержит непечатаемые символы (табуляции, перводы каретки) self.compare_histogram_and_answer('data/nonprint_symbols_src.txt', 'data/nonprint_symbols_ans.txt') def test_big_text(self): self.compare_histogram_and_answer('data/big_text_src.txt', 'data/big_text_ans.txt') def test_german(self): # юникод self.compare_histogram_and_answer('data/german_src.txt', 'data/german_ans.txt') def test_big_2_12_text(self): #проверяем граничные условия фильтрации частоты +1 слева и -1 справа self.compare_histogram_and_answer('data/big_text_src.txt', 'data/big_text_2_12_ans.txt', 2, 12) def test_uncorrect_filter(self): #проверяем случай когда частота min > max self.compare_histogram_and_answer('data/big_text_src.txt', 'data/null_ans.txt', 12, 2) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 import sys import time from colors import bcolors import colors """ A small program to calculate the tip amount at varying percentages """ class TipCalculator: newTotal = 0 def print_instruction(): print(f'{bcolors.YELLOW}Usage : Enter the Total Bill amount and Tip % (options are 10,15,20,25,30) as program argument as whole numbers, like,') print(f'{bcolors.BLUE}python3 tip_calculator.py 200 20') def tip10percent(total, tip): tipAmount = round(total * .10,2) TipCalculator.newTotal = total + tipAmount return tipAmount def tip15percent(total, tip): tipAmount = round(total * .15,2) TipCalculator.newTotal = total + tipAmount return tipAmount def tip20percent(total, tip): tipAmount = round(total * .20,2) TipCalculator.newTotal = total + tipAmount return tipAmount def tip25percent(total, tip): tipAmount = round(total * .25,2) TipCalculator.newTotal = total + tipAmount return tipAmount def tip30percent(total, tip): tipAmount = round(total * .30,2) TipCalculator.newTotal = total + tipAmount return tipAmount if len(sys.argv) < 2: print_instruction() else: total = int(sys.argv[1]) tip = int(sys.argv[2]) print(f'{bcolors.YELLOW}You entered, Total = {total}, Tip % = {tip}') if tip == 10: print(f'{bcolors.BLUE}Recommended tipping amount = {tip10percent(total,tip)}, New Total = {TipCalculator.newTotal}') elif tip == 15: print(f'{bcolors.BLUE}Recommended tipping amount = {tip15percent(total,tip)}, New Total = {TipCalculator.newTotal}') elif tip == 20: print(f'{bcolors.BLUE}Recommended tipping amount = {tip20percent(total,tip)}, New Total = {TipCalculator.newTotal}') elif tip == 25: print(f'{bcolors.BLUE}Recommended tipping amount = {tip25percent(total,tip)}, New Total = {TipCalculator.newTotal}') elif tip == 30: print(f'{bcolors.BLUE}Recommended tipping amount = {tip30percent(total, tip)}, New Total = {TipCalculator.newTotal}')
import os try: file = input("Masukkan Nama File : ") if os.path.exists(file): mode = "a" else: mode = "r" isiFile = open(file, mode) lanjut = True while(lanjut == True): data = input("Data yang ditambahkan : ") isiFile.write(" " + data) opsi = input("Ingin Lagi? (y / n) : ") if(opsi == "y"): lanjut = True elif(opsi == "n"): lanjut = False else: print("Input Tidak Valid") break isiFile.close() except FileNotFoundError: print("File Tidak Ditemukan")
#!/user/bin/python3 # fare=float(input("Température en degrès Farenheit ")) # celc=(fare-32)/1.8 # print("en degrès celcius cela fait : ", celc) # if celc>0: # print("ça va il ne va pas geler ") # else: # print("Tous aux abris il va faire très très froid") def CONVERSION(f): c=(f-32)/1.8 return c
import re, nltk, argparse def get_score(review): return int(re.search(r'Overall = ([1-5])', review).group(1)) def get_text(review): return re.search(r'Text = "(.*)"', review).group(1) def read_reviews(file_name): """ Dont change this function. :param file_name: :return: """ file = open(file_name, "rb") raw_data = file.read().decode("latin1") file.close() positive_texts = [] negative_texts = [] first_sent = None for review in re.split(r'\.\n', raw_data): overall_score = get_score(review) review_text = get_text(review) if overall_score > 3: positive_texts.append(review_text) elif overall_score < 3: negative_texts.append(review_text) if first_sent == None: sent = nltk.sent_tokenize(review_text) if (len(sent) > 0): first_sent = sent[0] return positive_texts, negative_texts, first_sent ######################################################################## ## Dont change the code above here ###################################################################### #extra funtion for checking a string contains a word character def is_word(word): word_pattern = r'(.*\w.*)' re_match = re.search(word_pattern, word) return re_match is not None def process_reviews(file_name): positive_texts, negative_texts, first_sent = read_reviews(file_name) stop_words = nltk.corpus.stopwords.words('english') # There are 150 positive reviews and 150 negative reviews. #print(len(positive_texts)) #print(len(negative_texts)) # Your code goes here pos_words=[] neg_words=[] i=0 for text in positive_texts: for sent in nltk.sent_tokenize(positive_texts[i]): pos_words.extend(nltk.word_tokenize(sent)) for sent in nltk.sent_tokenize(negative_texts[i]): neg_words.extend(nltk.word_tokenize(sent)) i+=1 clean_pos_words=[] clean_neg_words=[] for word in pos_words: word=word.casefold() if word not in stop_words: if is_word(word): clean_pos_words.append(word) for word in neg_words: word = word.casefold() if word not in stop_words: if is_word(word): clean_neg_words.append(word) pos_uni = nltk.FreqDist(clean_pos_words) neg_uni = nltk.FreqDist(clean_neg_words) write_unigram_freq('positive',pos_uni.most_common()) write_unigram_freq('negative',neg_uni.most_common()) pos_bg = nltk.bigrams(clean_pos_words) neg_bg = nltk.bigrams(clean_neg_words) pos_bi = nltk.FreqDist(pos_bg) neg_bi = nltk.FreqDist(neg_bg) write_bigram_freq('positive', pos_bi.most_common()) write_bigram_freq('negative', neg_bi.most_common()) print("Positive Collocations:") nltk.Text(clean_pos_words).collocations() print("Negative Collocations:") nltk.Text(clean_neg_words).collocations() # string='' # for item in pos_uni.most_common(15): # addition = item[0]+'('+str(item[1])+'), ' # string+=addition # print(string) # string='' # for item in neg_uni.most_common(15): # addition = item[0] + '(' + str(item[1]) + '), ' # string += addition # print(string) # string = '' # for item in pos_bi.most_common(15): # addition = item[0][0]+ ' '+item[0][1] + '(' + str(item[1]) + '), ' # string += addition # print(string) # string = '' # for item in neg_bi.most_common(15): # addition = item[0][0]+ ' '+item[0][1] + '(' + str(item[1]) + '), ' # string += addition # print(string) # string = '' # Write to File, this function is just for reference, because the encoding matters. def write_file(file_name, data): file = open(file_name, 'w', encoding="utf-8") # or you can say encoding="latin1" file.write(data) file.close() #extra function for writing bigram files, modeled after the function below provided def write_bigram_freq(category, bigrams): """ A function to write the unigrams and their frequencies to file. :param category: [string] :param bigrams: list of ((word,word), frequency) tuples :return: """ bi_file = open("{0}-bigram-freq.txt".format(category), 'w', encoding="utf-8") for word, count in bigrams: bi_file.write("{0:<20s}{1:<20s}{2:<d}\n".format(word[0],word[1], count)) bi_file.close() def write_unigram_freq(category, unigrams): """ A function to write the unigrams and their frequencies to file. :param category: [string] :param unigrams: list of (word, frequency) tuples :return: """ uni_file = open("{0}-unigram-freq.txt".format(category), 'w', encoding="utf-8") for word, count in unigrams: uni_file.write("{0:<20s}{1:<d}\n".format(word, count)) uni_file.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Assignment 2') parser.add_argument('-f', dest="fname", default="restaurant-training.data", help='File name.') args = parser.parse_args() fname = args.fname process_reviews(fname)
# Если выписать все натуральные числа меньше 10, кратные 3 или 5, # то получим 3, 5, 6 и 9. Сумма этих чисел равна 23. # Найдите сумму всех чисел меньше 1000, кратных 3 или 5. # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. num = 0 for x in range(1000): if x % 3 == 0 or x % 5 == 0: num += x print(num) # Answer - 233168
#!usr/bin/python3 """ This file creates a script that generates a random list and then sorts the list using a bubble sort, merge sort, and pythons built in list sort. The purpose of this is to use the cProfile module to time the different sort functions. The results of the cProfile are included as comments at the end of the file. """ import random def bubble_sort(unsortlist): listlength = len(unsortlist) slist = unsortlist[:] for i in range(listlength): for k in range(listlength - (i + 1)): if slist[k] > slist[k+1]: slist[k], slist[k+1] = slist[k+1], slist[k] return slist def merge_sort(unsortlist): if len(unsortlist) > 1: mid = int(len(unsortlist) / 2) left = merge_sort(unsortlist[:mid]) right = merge_sort(unsortlist[mid:]) templist = [] ir, il, k = 0,0,0 while k < len(unsortlist): if il >= len(left) and ir < len(right): templist.append(right[ir]) ir += 1 elif ir >= len(right) and il < len(left): templist.append(left[il]) il += 1 elif left[il] <= right[ir]: templist.append(left[il]) il += 1 elif right[ir] < left[il]: templist.append(right[ir]) ir += 1 k += 1 # print(templist[0]) return templist return unsortlist if __name__ == "__main__": randlist = [random.randint(0, 100000000) for i in range(1000)] # print(randlist) merge_list = merge_sort(randlist) randlist.sort() bubble_list = bubble_sort(randlist) # print(merge_list) # print(bubble_list) # print(randlist) """ Thu Nov 7 18:05:54 2019 hw9_results 53987 function calls (51944 primitive calls) in 0.173 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.139 0.139 0.139 0.139 hw9.py:6(bubble_sort) 1999/1 0.011 0.000 0.015 0.015 hw9.py:16(merge_sort) 6 0.006 0.001 0.006 0.001 {built-in method _imp.create_dynamic} 3 0.006 0.002 0.006 0.002 {built-in method builtins.compile} 34565 0.003 0.000 0.003 0.000 {built-in method builtins.len} 1000 0.001 0.000 0.003 0.000 /opt/python/lib/python3.6/random.py:172(randrange) 9976 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects} 1000 0.001 0.000 0.001 0.000 /opt/python/lib/python3.6/random.py:222(_randbelow) 51 0.001 0.000 0.001 0.000 {built-in method posix.stat} 1000 0.001 0.000 0.003 0.000 /opt/python/lib/python3.6/random.py:216(randint) 33 0.000 0.000 0.002 0.000 <frozen importlib._bootstrap_external>:1233(find_spec) 1 0.000 0.000 0.004 0.004 hw9.py:42(<listcomp>) 1322 0.000 0.000 0.000 0.000 {method 'getrandbits' of '_random.Random' objects} 144 0.000 0.000 0.001 0.000 <frozen importlib._bootstrap_external>:57(_path_join) 1 0.000 0.000 0.000 0.000 {built-in method builtins.print} 6 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap_external>:830(get_data) 144 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap_external>:59(<listcomp>) 3 0.000 0.000 0.000 0.000 {built-in method marshal.dumps} 18 0.000 0.000 0.000 0.000 {built-in method posix.getcwd} 294 0.000 0.000 0.000 0.000 {method 'rstrip' of 'str' objects} 1000 0.000 0.000 0.000 0.000 {method 'bit_length' of 'int' objects} 9 0.000 0.000 0.002 0.000 <frozen importlib._bootstrap>:861(_find_spec) 1 0.000 0.000 0.011 0.011 /opt/python/lib/python3.6/random.py:38(<module>) 9 0.000 0.000 0.002 0.000 <frozen importlib._bootstrap_external>:1117(_get_spec) 168 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:208(_verbose_message) """
class Empleados: conteo = 0 #variable global modificable por cada objeto, los dos guiones bajos son para privados. def __init__(self, nombre, salario): #Self es para usar atributos/variables de la misma clase. Por lo general TIENE que ir... self.nombre = nombre #"""esto es el costructor""" self.salario = salario Empleados.conteo += 1 def mostrar_conteo(self): print("Esta empresa tiene "+ str(Empleados.conteo) + " empleado.") def mostrar_empleado(self): print("Nombre: " + self.nombre) print("Salario: " + str(self.salario)) def calcular_salario_neto(self): if self.salario < 2000: return self.salario*0.93 elif self.salario > 5000: return self.salario * 0.85 else: return self.salario # return self.salario
str1=input() s=list(str1) s.append('.') s=''.join(s) print(s)
cf=input() if((ord(cf)>64 and ord(cf)<91) or (ord(cf)>96 and ord(cf)<123)): print('Alphabet') else: print('No')
# imports import streamlit as st import pandas as pd def write(): """Used to write the page in the app.py file""" st.title('Data description') st.write(""" Most of the data fields are easy to understand, but just to highlight some of the features present: *Store, Date, Sales, Customers, Open, State Holiday, School Holiday, Store Type, Assortment, Competition and Promotion.* The *Store Type, Assortment, Competition* and *Promotion* features are store tailored. The *Sales, Customers, Open, State Holiday* and *School Holiday* features vary across the stores with days. """) na_value=['',' ','nan','Nan','NaN','na', '<Na>'] train = pd.read_csv('src/data/train.csv', na_values=na_value) store = pd.read_csv('src/data/store.csv', na_values=na_value) full_train = pd.merge(left = train, right = store, how = 'inner', left_on = 'Store', right_on = 'Store') full_train = full_train.set_index('Store') st.write('---') st.write('Sample stores data') st.write(store.head(20)) st.write('---') st.write('Sample historical data including Sales and Customers') st.write(train.sample(20)) st.write('---') st.write('Sample training data containing the input features') st.write(full_train.sample(20))
# @author Huaze Shen # @date 2020-05-05 class ListNode: def __init__(self, x): self.val = x self.next = None def reverse_list(head: ListNode) -> ListNode: if head is None: return head dummy = ListNode(0) dummy.next = head cur = head while cur.next is not None: temp = cur.next cur.next = temp.next temp.next = dummy.next dummy.next = temp return dummy.next if __name__ == '__main__': head_ = ListNode(1) head_.next = ListNode(2) head_.next.next = ListNode(3) head_.next.next.next = ListNode(4) head_.next.next.next.next = ListNode(5) node = reverse_list(head_) while node: print(node.val) node = node.next
# @author Huaze Shen # @date 2020-06-25 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def is_sub_structure(A: TreeNode, B: TreeNode) -> bool: return (A is not None and B is not None) and (helper(A, B) or is_sub_structure(A.left, B) or is_sub_structure(A.right, B)) def helper(A, B): if B is None: return True if A is None or A.val != B.val: return False return helper(A.left, B.left) and helper(A.right, B.right) if __name__ == '__main__': A_ = TreeNode(3) A_.left = TreeNode(4) A_.right = TreeNode(5) A_.left.left = TreeNode(1) A_.left.right = TreeNode(2) B_ = TreeNode(4) B_.left = TreeNode(1) print(is_sub_structure(A_, B_))
#! /usr/bin/env python3 # https://www.hackerrank.com/challenges/power-of-large-numbers/problem x, y = input().split() x, y = int(x), int(y) print(pow(x, y, (10**9 + 7)))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : Apr-17-20 02:55 # @Author : Kan HUANG ([email protected]) from torch import nn from torch.nn import functional as F class LeNet5(nn.Module): """LeNet-5 implemented with PyTorch LeNet5 的结构,是 conv2d x3 和 FC x2 Args: padding: padding at the first Conv2d layer to change the input_shape of the element of the batched data. The inputs at first Conv2d layer must be (32, 32, 1) or (32, 32, 3), so set *padding* if necessary, e.g.*padding=2* for MNIST dataset. output_dim: number of top classifiers, e.g., 2, 10. References: - [1] https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html - [2] https://github.com/pytorch/examples/blob/master/mnist/main.py """ def __init__(self, padding=0, output_dim=10): super().__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5, padding=padding) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 5 * 5, 120) # 5*5 from image dimension self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, output_dim) def forward(self, x): # Max pooling over a (2, 2) window x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # conv1 pool x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2)) # conv2 pool # flatten all dimensions except the batch dimension x = x.view(-1, x.size()[1:].numel()) # x = torch.flatten(x, 1) is an alternative x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x
from abc import ABCMeta, abstractmethod from observer import Observer class Observable(metaclass=ABCMeta): observers = [] changed = False def add_observer(self, observer): if isinstance(observer, Observer): print('Add', observer, ' to observer list') self.observers.append(observer) def delete_observer(self, observer): print('Remove', observer, ' from observer list') self.observers.remove(observer) def notify_observers(self): if (self.changed): for observer in self.observers: print('To nofity observer:', observer) observer.update(self) self.changed = False def set_changed(self): self.changed = True
from abc import ABCMeta, abstractmethod class PizzaStore(metaclass=ABCMeta): def order_pizza(self, type): pizza = self.create_pizza(type) pizza.prepare() pizza.bake() pizza.cut() pizza.box() return pizza @abstractmethod def create_pizza(self, type): pass
item_list = [] for i in range(0,3): a = input("Enter a number:") item_list.append(int(a)) item_list.sort() item_list.reverse() for item in item_list: print(item,end = " ")
"""This function accepts a number and converts it to hours and minutes """ def hours_and_mins(number): hours = number // 60 # Converts number to hours mins = number % 60 # Converts number to minutes if hours <= 1 and mins <= 1: time = f"{number} is {hours} hour, {mins} minute" elif hours <= 1 and mins > 1: time = f"{number} is {hours} hour, {mins} minutes" elif hours > 1 and mins <= 1: time = f"{number} is {hours} hours, {mins} minute" else: time = f"{number} is {hours} hours, {mins} minutes" return time print(hours_and_mins(0))
par = 'parimpar' i = int(input('coloque um numero de telefone')) if 1 % 2 == 0: print("par") else: pŕint("impar")
# Python program for Plotting Fibonacci # spiral fractal using Turtle import turtle import math def fibo_plot(number): a = 0 b = 1 square_a = a square_b = b # Setting the colour of the plotting pen to blue pen.pencolor("blue") # Drawing the first square pen.forward(b * factor) pen.left(90) pen.forward(b * factor) pen.left(90) pen.forward(b * factor) pen.left(90) pen.forward(b * factor) # Proceeding in the Fibonacci Series temp = square_b square_b = square_b + square_a square_a = temp # Drawing the rest of the squares for _ in range(1, number): pen.backward(square_a * factor) pen.right(90) for _ in range(2): pen.forward(square_b * factor) pen.left(90) pen.forward(square_b * factor) # Proceeding in the Fibonacci Series temp = square_b square_b = square_b + square_a square_a = temp # Bringing the pen to starting point of the spiral plot pen.penup() pen.setposition(factor, 0) pen.seth(0) pen.pendown() # Setting the colour of the plotting pen to red pen.pencolor("red") # Fibonacci Spiral Plot pen.left(90) for _ in range(number): print(b) forward_distance_for_width = math.pi * b * factor/2 forward_distance_for_width /= 90 for _ in range(90): pen.forward(forward_distance_for_width) pen.left(1) temp = a a = b b = temp + b # Here 'factor' signifies the multiplicative # factor which expands or shrinks the scale # of the plot by a certain factor. factor = 1 # Taking Input for the number of # Iterations our Algorithm will run var = int(input('Enter the number of iterations (must be > 1): ')) # Plotting the Fibonacci Spiral Fractal # and printing the corresponding Fibonacci Number if var > 0: print("Fibonacci series for", var, "elements :") pen = turtle.Turtle() pen.speed(100) fibo_plot(var) turtle.done() else: print("Number of iterations must be > 0")
''' It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. ''' main = [] for n in range(99, 999999): if len(str(n)) == len(str(2 * n)) == len(str(3 * n)) == len(str(4 * n)) == len(str(5 * n)) == len(str(6 * n)): def func(ran): liss = [] for a in str(n): if a in str(ran * n): liss.append(1) else: liss.append(0) # print(liss) global stat stat = all(liss) func(2) if stat == True: func(3) if stat == True: func(4) if stat == True: func(5) if stat == True: func(6) if stat == True: main.append(n) print(main) # print(n, 'and ', ran * n) # main.append(str(n)) # return str(n) # for i in range(2,7): # main.append(func(2))
__author__ = 'shenyao' def power(x,n):#位置参数 s=1 while n>0: n=n-1 s=s*x return s print(power(5,2))#位置参数 print(power(5,3))#位置参数 def power(x,n=2):#默认参数(必选参数在前,默认参数在后) s=1 while n>0: n=n-1 s=s*x return s print(power(5)) print(power(5,3)) def enroll(name,gender,age=6,city='beijing'): print("name",name) print("gender",gender) print("age",age) print("city",city) enroll('Sarah','F') enroll('Bob','M',7) enroll('Sheldon','M',city="shenzhen") #演示默认参数的坑 def add_end(L=[]): L.append('END') return L print(add_end([1,2,3])) print(add_end(['x','y','z'])) #print(add_end()) #--------pitfall---------------- print(add_end()) print(add_end()) print(add_end()) #-------pitfall---------------- #-------solution--------------- #默认参数必须指向不变对象 def add_end(L=None):#利用None这个不变对象来实现 if L is None: L=[] L.append('END') return L #-------solution--------------- print(add_end()) print(add_end()) print(add_end()) def calc(numbers): sum=0 for n in numbers: sum=sum+n*n return sum #可变参数 def calc(*numbers):#把函数参数改为可变参数 sum=0 print(type(numbers)) #tuple for n in numbers:#numbers tuple sum=sum+n*n return sum # print(calc([1,2,3])) # print(calc((1,3,5,7))) print( calc(1, 2, 3)) print(calc(1,3,5,7)) print(calc()) nums=[1,2,3] print(calc(nums[0],nums[1],nums[2])) print(calc(*nums))#*num表示把这个list的所有元素作为可变参数传进去,这种写法相当有用 #关键字参数 #可变参数在函数调用的时候自动组装为一个tuple, #关键字参数内部自动组装为一个dict def person(name,age,**kw): print('name:',name,'age:',age,'other:',kw) #kw {} person('sheldon',24) person('sheldon',24,city='beijing') person('sheldon',24,gender='M',job="Engineer") extra={'gender':'M','job':'softwar'} person('sheldon','M',**extra)#kw将获得extra参数的一份拷贝 #关键字参数 def person(name,age,**kw): if 'city' in kw: pass if 'job' in kw: pass print('name:',name,"age:",age,"other:",kw) person('jack',24,city='beijing',addr='chaoyang',zipcode=12345) #命名关键字参数 #和关键字参数**kw不同,命名关键字参数需要一个特许的分隔符*,*后面的参数被视为命名关键字参数 def person(name,age,*,city,job): print(name,age,city,job) person('jack',24,city="shenzhen",job="programmer") def person(name,age,*args,city,job): print(name,age,city,job) person('jack',24,city="shenzhen",job="programmer") def person(name,age,*args,city='shenzhen',job):#命名关键字参数可以有默认值 print(name,age,city,job) person('jack',24,job="programmer") def person(name, age, city, job): # 缺少 *,city和job被视为位置参数 pass #组合参数 #5中参数的定义顺序必须是必选参数,默认参数,可变参数,命名关键字参数,关键字参数 def f1(a,b,c=0,*args,**kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a,b,c=0,*,d,**kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) args=(1,2,3,4) kw={'d':99,'x':'#'} f1(*args,**kw) args=(1,2,3) kw={'d':88,'x':'#'} f2(*args,**kw) #所以,对于任意参数,都可以通过类似func(*args,**kw)的形式调用,无论他的参数是如何定义的 #小结 #1 默认参数一定要用不可变对象,如果是可变参数,程序运行时会有逻辑错误 #2 *args是可变参数,args接收的是一个tuple #3 **kw是关键字参数,kw接收的是一个dict #4 可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple,再通过*args传入:func(*(1, 2, 3)) #5 关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict,再通过**kw传入:func(**{'a': 1, 'b': 2}) #6 命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值 #7 定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,否则定义的将是位置参数
__author__ = 'shenyao' class Hello(object): def hello(self,name="world"): print("Hello,%s" % name) h = Hello() print(type(Hello)) #type print(type(h)) h.hello() #我们说class的定义是运行时动态创建的,而创建class的方法就是type函数 def fn(self,name="world,welcome"):#先定义函数 print("Hello,%s" % name) #type方法参数解释 #1 class的名字 #2 继承的父类集合 #3 class的方法名与函数绑定,这里我们把函数fn绑定到方法名hello Hello=type("Hello",(object,),dict(hello=fn)) #创建Hello class he=Hello() he.hello() print(type(Hello)) print(type(he))
''' Created on Sep 7, 2016 @author: sheldonshen ''' #1定制类之__str__ class Student(object): def __init__(self,name): self._name=name def __str__(self): return 'Student object (name:%s)' % (self._name) __repr__=__str__ s = Student("simon") print(s) #2定制类之__iter__ class Fib(object): def __init__(self): self.a,self.b=0,1 #初始化2个计数器a,b def __iter__(self): return self #实例本身就是迭代对象,故返回自己 def __next__(self): self.a,self.b=self.b,self.a + self.b #计算下一个值 if self.a > 1000: #出口 raise StopIteration() return self.a #返回下一个值 def __getitem__(self,n):#要表现得像list那样按照下标取出元素,需要实现__getitem__()方法 if isinstance(n,int):#n是索引 a,b=1,1 for x in range(n): a,b=b,a+b return a if isinstance(n,slice):#n是切片 start = n.start stop = n.stop if start is None: start = 0 a,b=1,1 L=[] for x in range(stop): if x >= start: L.append(a) a,b=b,a+b return L for n in Fib(): print(n) #3定制类之__getitem__ print(Fib()[5]) print(Fib()[5:10]) print(Fib()[5:10:2]) #4定制类之__getattr__ class People(object): def __init__(self): self.name="micheal" def __getattr__(self,attr):#动态返回一个属性值 if attr=='age': #return 250 return lambda:25 return AttributeError("'People' object has no attribute '%s'" % attr) p = People() print(p.name) #print(p.age) print(p.age()) print(p.abc) #None #链式调用 class Chain(object): def __init__(self,path=''): self._path=path def __getattr__(self,path): return Chain('%s/%s' %(self._path,path)) def __str__(self): return self._path print(Chain().status.user.timeline.list) #定制类之__call__ class Kid(object): def __init__(self,name): self.name=name def __call__(self): print("my name is %s" % (self.name)) k = Kid("simin") k()#在实例本身上进行调用 #我们需要判断一个对象是否能被调用 print(callable(Kid('amy'))) print(callable(max)) print(callable([1,2,3])) print(callable(None)) print(callable("str")) #通过callable()函数,我们就可以判断一个对象是否是“可调用”对象。
''' Created on Sep 7, 2016 @author: sheldonshen ''' class Animal(object): pass #大类 class Mammal(Animal): pass class Bird(Animal): pass class RunnableMixIn(object): def run(self): print("Running....") class FlyableMixIn(object): def fly(self): print("Flying....") #各种动物 class Dog(Mammal,RunnableMixIn):#通过多重继承,一个子类就可以同时获得多个父类的所有功能 pass class Bat(Mammal,FlyableMixIn):#通过多重继承,一个子类就可以同时获得多个父类的所有功能 pass class Parrot(Bird): pass class Ostrich(Bird,RunnableMixIn): pass #让Ostrich除了继承自Bird外,再同时继承Runnable。这种设计通常称之为MixIn(混入)
''' Created on Sep 6, 2016 @author: sheldonshen ''' #1函数作为返回值 def calc_sum(*args): ax = 0 for n in args: ax = ax + n return ax def lazy_sum(*args): def mysum(): ax = 0 for n in args: ax=ax+n return ax return mysum; print(calc_sum(1,2,3,4)) f = lazy_sum(1,2,3,4) print(f) print(f()) f1 = lazy_sum(1,2,3,4) f2 = lazy_sum(1,2,3,4) print(f1 == f2) #False #2闭包 #我们在函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量, #当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中, #这种称为“闭包(Closure)”的程序结构拥有极大的威力 def count(): fs=[] for i in range(1,4): def f(): return i * i fs.append(f) return fs f1,f2,f3=count() print(f1())#9 print(f2())#9 print(f3())#9 #返回闭包时牢记的一点是:返回函数不要引用任何循环变量后者后续会发生变化的变量 def count_refactor(): def f(j): def g(): return j * j return g fs=[] for i in range(1,4): fs.append(f(i))#f(i)立刻被执行,因此i的当前值被传入f() return fs f1,f2,f3=count_refactor() print(f1())#1 print(f2())#4 print(f3())#9 #返回一个函数时,牢记该函数并未执行,返回函数中不要引用任何可能会变化的变量
# def writetextfilesusingwith(self): # with open(order_text, "w+") as file, open(writer_text, "w+") as file2: # try: # file_input = (input("Enter your file input:")) # if len(file_input) == 0: # raise Exception("sorry we dont take empty names") # except Exception: # print("you did not enter anything") # self.writetextfilesusingwith() # else: # file.write(file_input) # file.seek(0) # file2.write((file.read()))
from nltk.stem import PorterStemmer from nltk.tokenize import sent_tokenize, word_tokenize ps = PorterStemmer() example_words = ["cats","animals","men","boys","children"] for word in example_words: print(ps.stem(word)) new_text = "It is important to by very pythonly while you are pythoning with python. All pythoners have pythoned poorly at least once." words = word_tokenize(new_text) for w in words: print(ps.stem(w))
import nltk from nltk.stem import WordNetLemmatizer wordnet_lemmatizer = WordNetLemmatizer() sentence = "running studying eats verification friendly chatbots" punctuations="?:!.,;" sentence_words = nltk.word_tokenize(sentence) for word in sentence_words: if word in punctuations: sentence_words.remove(word) print("{0:20}{1:20}".format("Word","Lemma")) for word in sentence_words: print ("{0:20}{1:20}".format(word,wordnet_lemmatizer.lemmatize(word, pos="v")))
temp = [1, 2, 3, 4, 5, 6] # result = [expression,for userDefKey in itarableList] result = [x * x for x in temp] print(result) # now another magic in list temp2 = [1, 2, 3, 4, 5, 6] result2 = [x for x in temp2 if x % 2 == 0] print(result2) print(type(result2) is bool) result3 = [x for x in result2 if x % 2 == 0] result4 = list(filter(lambda a: a % 3 == 0, result3)) print(result4) print(result3)
import time from datetime import datetime currentDate = datetime.now() print(currentDate) currentDay = datetime.now().day print(currentDay) print(datetime.now().minute) # current minute print(datetime.now().second) # current second print(datetime.now().time()) # current time # for get timeStamp timestamp = int(time.time()) print(timestamp)
temp = 32 # if temp == 30: # print("ok") # else: # print("No") val = temp if temp == 30 else "No" print(val)
# for variable and data types name = "Golam Kibria" age = 25 print(name, age, "Dhanmondi dhaka bangladesh")
#多线程-共享全局变量 #多线程之间共享全局变量有两种方式: #子线程函数使用global关键字来调用函数外全局变量 #列表当作实参传递到线程中 #在一个进程内所有的线程共享全局变量,很方便在多个线程间共享数据 #缺点就是,线程是对全局变量随意遂改可能造成多线程之间对全局变量的混乱(即线程非安全) # 共享全局变量-global全局变量 #例如: # from threading import Thread # from time import sleep # num=100 # def work1(): # global num # for i in range(3): # num+=1 # print('经过work1,num的值为:%d'%num) # def work2(): # global num # print('经过work2,num的值为:%d'%num) # print('线程创建之前num的值为:%d'%num) # t1=Thread(target=work1) # t1.start() # #拖延一会,保证t1线程中的事情做完 # sleep(3) # t2=Thread(target=work2) # t2.start() # 共享全局变量-列表当做实参 #例如: # from threading import Thread # from time import sleep # def work1(num): # num.append(44) # print('经过work1 num列表为:',num) # def work2(num): # #延迟一会,保证t1线程中的事情做完 # sleep(3) # print('经过work2,num列表值为:',num) # num=[11,22,33] # t1=Thread(target=work1,args=(num,)) # t1.start() # t2=Thread(target=work2,args=(num,)) # t2.start() #结论:t1=Thread(target=work1,args=(list,)) args= 应该是固定的 传过去列表名后面还要有一个逗号 # import threading,time # def a(): # global num # num+=1 # print('test1--%d'%num) # def b(): # global num # num+=1 # print('test2--%d'%num) # if __name__=='__main__': # print('开始') # num = 0 # f1 = threading.Thread(target=a) # f2 = threading.Thread(target=b) # f1.start() # f2.start() # # f1.join() # # f2.join() # print('lalalal') # print('经过test1,test2后 num的值为:%d' % num) # import threading,time # def q(): # for x in range(3): # time.sleep(2) # print('1') # def w(): # for x in range(3): # time.sleep(2) # print('2') # print('wuwuwu') # a=threading.Thread(target=q) # b=threading.Thread(target=w) # a.start() # b.start() # print('heiheiehi') # a.join() # b.join() # print('lala') # import threading,time # def a1(num): # num[0]=1 # print(num) # def a2(num): # num[1]=2 # print(num) # num=[9,9,9,9] # q1=threading.Thread(target=a1,args=(num,)) # q2=threading.Thread(target=a2,args=(num,)) # q1.start() # q2.start() # print(num) # import threading,time # def a1(num): # global add # add+=num # print(add) # def a2(num): # global add # add+=num # print(add) # add=0 # q1=threading.Thread(target=a1,args=(3,)) # q2=threading.Thread(target=a2,args=(4,)) # q1.start() # q1.join() # q2.start() # print('最终结果为:%d'%add)
class F(object): __money=1 n=333 def __init__(self,name,age): self.name=name self.age=age self.sex='男性' def classid(self): return '1809A' @classmethod def secret(cls): return cls.__money @classmethod def change(cls): cls.__money=10 class F2(F): __money = 2 def __init__(self,name,age): self.name=name self.age=age self.sex='女性' def classid(self): return '1809B' def father(self): print(self.classid()) print(super().classid()) print(self.name) F.__init__(self,'张三',18) print(self.name) @classmethod def secret(cls): return cls.__money @classmethod def change(cls): cls.__money=20 class F3(F2): __money = 3 def __init__(self,name,age): self.name=name self.age=age self.sex='中性' def classid(self): return '1811A' @classmethod def secret(cls): return cls.__money @classmethod def change(cls): cls.__money=30 f=F('张三',18) f2=F2('李四',20) f3=F3('王五',16) print(f.n) # f2.father() # print(f2.secret()) # print(F3.__mro__) # class Person(object): # def __init__(self,name,age): # self.name=name # self.age=age # def show_my_info(self): # print("我是%s,今年%d岁"%(self.name,self.age)) # def show_my_birth(self): # self.year=2018-self.age # print("我是%d年出生,今年%d岁"%(self.year,self.age)) # def show_my_life(self): # for x in range(self.age+1): # if x==0: # print("%d年出生"%(2018-self.age)) # else: # print("%d年%d岁"%((2018-self.age+x),x)) # def show_leap_year(self): # self.list=[] # for x in range(self.age+1): # self.y=2018-x # if self.y%4==0 and self.y%100!=0 or self.y%400==0: # self.list.append(self.y) # if self.list==[]: # print("没有闰年") # else: # print(self.list[::-1]) # print('\t'.join([str(x) for x in self.list])) # def can_recite(self): # for x in range(1,10): # for y in range(1,x+1): # print("%d*%d=%d"%(x,y,x*y),end=' ') # print() # name=input("请输入姓名:") # age=int(input("请输入年龄:")) # p=Person(name,age) # p.show_my_info() # p.show_my_birth() # p.show_my_life() # p.show_leap_year() # p.can_recite() # class cirlc(object): # def __init__(self,r): # self.r=r # def c(self): # print("周长为%.1f"%(2*self.r*3.14)) # def s(self): # print("面积为%.2f"%(3.14*self.r*self.r)) # # r=int(input("请输入半径:")) # c=cirlc(r) # c.c() # c.s()
#发送数据 # from socket import * # udp_socket=socket(AF_INET,SOCK_DGRAM) # socket_data=input('请输入你要发送的数据:') # s=('192.168.1.3',8080) # udp_socket.sendto(socket_data.encode('gb2312'),s) # udp_socket.close() #发送接收数据 # from socket import * # # # 1. 创建udp套接字 # udp_socket = socket(AF_INET, SOCK_DGRAM) # # 2. 准备接收方的地址 # dest_addr = ('192.168.1.3', 8080) # # 3. 从键盘获取数据 # send_data = input("请输入要发送的数据:") # # # 4. 发送数据到指定的电脑上 # udp_socket.sendto(send_data.encode('gb2312'), dest_addr) # # # 5. 等待接收对方发送的数据 # recv_data = udp_socket.recvfrom(1024) # 1024表示本次接收的最大字节数 # # # 6. 显示对方发送的数据 # # 接收到的数据recv_data是一个元组 # # 第1个元素是对方发送的数据 # 第2个元素是对方的ip和端口 # print(recv_data[0].decode('gb2312')) # print(recv_data[1]) # # # 7. 关闭套接字 # udp_socket.close() from socket import * # 创建socket tcp_client_socket = socket(AF_INET, SOCK_STREAM) # 目的信息 server_addr = ('192.168.1.254', 8080) # 链接服务器 tcp_client_socket.connect(server_addr) # 提示用户输入数据 send_data = input("请输入要发送的数据:") tcp_client_socket.send(send_data.encode("gbk")) # 接收对方发送过来的数据,最大接收1024个字节 recvData = tcp_client_socket.recv(1024) print('接收到的数据为:', recvData.decode('gbk')) # 关闭套接字 tcp_client_socket.close() # from socket import * # # # 1. 创建套接字 # udp_socket = socket(AF_INET, SOCK_DGRAM) # # # 2. 绑定本地的相关信息,如果一个网络程序不绑定,则系统会随机分配 # local_addr = ('', 7788) # ip地址和端口号,ip一般不用写,表示本机的任何一个ip # udp_socket.bind(local_addr) # # # 3. 等待接收对方发送的数据 # recv_data = udp_socket.recvfrom(1024) # 1024表示本次接收的最大字节数 # # # 4. 显示接收到的数据 # print(recv_data[0].decode('gb2312')) # # # 5. 关闭套接字 # udp_socket.close()
class Hero(object): def __init__(self,name,age): self.name=name self.age=age def moving(self): print('正在赶往战场') def attact(self): print('大保健...') if __name__ == '__main__': #程序入口 f = Hero('黄忠', 18) f2 = f # 引用计数+1 f3 = f # +1 print(id(f)) print(id(f2)) print(id(f3)) del (f2) # -1 # print(f2) del (f3) # -1 print(id(f3))
# for x in range(1001): # for y in range(1001): # for z in range(1001): # if (x+y+z==1000) and x**2+y**2==z**2: # print(x,y,z) # 执行时间会有很久 # import time # print(time.time()) # # for x in range(1001): # for y in range(1001): # c=1000-x-y # if x**2+y**2==c**2: # print(x,y,c) # class Employee: # '所有员工的基类' # empCount = 0 # # def __init__(self, name, salary): # self.name = name # self.salary = salary # Employee.empCount += 1 # # def displayCount(self): # print("Total Employee %d" % Employee.empCount) # # def displayEmployee(self): # print("Name : ", self.name, ", Salary: ", self.salary) # # # print("Employee.__doc__:", Employee.__doc__) # print("Employee.__name__:", Employee.__name__) # print("Employee.__module__:", Employee.__module__) # print("Employee.__bases__:", Employee.__bases__) # print("Employee.__dict__:", Employee.__dict__)