text
stringlengths
37
1.41M
v = int(input('Informe um número inteiro: ')) print('O doblo de {} é {}'.format(v, v*2)) print('O triplo de {} e {}'.format(v, v*3)) print('A raiz quadrade de {} e {:.2f}'.format(v, v**(1/2)))
lista = [[], [], [], []] for l in range(0, 4): for c in range(0, 4): lista[l].append(int(input(f'Digite um valor para [{l}, {c}]: '))) for l in lista: for c in l: print(f'[ {c:>3} ]', end='') print()
nota1 = float(input('Informe a 1ª nota: ')) nota2 = float(input('Informe a 2ª nota: ')) media = (nota1 + nota2) / 2 print('Média: {:.1f} - '.format(media), end='') if media < 5.0: print('Aluno REPROVADO!') elif 5.0 <= media <= 6.9: print('Aluno em RECUPERAÇÃO') else: print('Aluno APROVADO')
mt = float(input('Informe a medida (em metros): ')) print('{} metros = {:.0f} centímetros'.format(mt, mt * 100)) print('{} metros = {:.0f} milímetros'.format(mt, mt * 1000))
num1 = int(input('Digite 1º número: ')) num2 = int(input('Digite 2º número: ')) if num1 > num2: print('O 1º número é maior.') elif num1 < num2: print('O 2º número e maior') else: print('Não existe valor maior, os dois são iguais.')
print('{:=^40}'.format(' LOJA DO ZÉ ')) preco = float(input('Preço normal: (R$) ')) print('Condições de pagamento:') print('1-Á vista (dinheiro/cheque) desconto -10%') print('2-Á vista (cartão) desconto -5%') print('3-Em até 2x (cartão) preço normal ') print('4-3x ou mais (cartão) acréscimo +20%') op = int(input('Escolha: ')) valor = 0.0 if op == 1: valor = preco - (preco * 10 / 100) elif op == 2: valor = preco - (preco * 5 / 100) elif op == 3: valor = preco elif op == 4: valor = preco + (preco * 20 / 100) else: print('Opção invalida!') if valor > 0.0: print('Valor a ser pago = R$ {:.2f}'.format(valor))
import numpy as np def gini(array): """Calculate the Gini coefficient of a numpy array. https://github.com/oliviaguest/gini/blob/master/gini.py based on bottom eq: http://www.statsdirect.com/help/generatedimages/equations/equation154.svg from: http://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm """ # All values are treated equally, arrays must be 1d: array=np.array(array,dtype=np.float64) array = array.flatten() if len(array)==0: return -1 if np.amin(array) < 0: # Values cannot be negative: array -= np.amin(array) # Values cannot be 0: array += 0.0000001 # Values must be sorted: array = np.sort(array) # Index per array element: index = np.arange(1,array.shape[0]+1) # Number of array elements: n = array.shape[0] # Gini coefficient: return ((np.sum((2 * index - n - 1) * array)) / (n * np.sum(array))) def success(thresh,tot_contrib): """ Returns the value of success for one round Args: thresh: the needs tot_contrib: the sum of contributions Returns: either 1 if successful or a fraction corresponding to the needs covered """ assert(thresh>=0) return (tot_contrib/thresh) if thresh>tot_contrib else 1 def success_freq(successes): """ Returns the frequency of successes over time Args: successes: a list of success values Returns: A float representing the frequence of success """ assert(all([i<=1 for i in successes])) return np.mean(list(map(int,successes))) # convert values to integers def efficiency(thresh,tot_contrib): """ Returns the value of efficiency for one round. Similar values of needs and total contributions correspond to high efficiency Args: thresh: the needs tot_contrib: the sum of contributions Returns: either the ratio between needs and contributions if successful or 0 """ return (-1 if tot_contrib==0 else ((thresh/tot_contrib) if tot_contrib>=thresh else 0)) def efficiency_mean(efficiencies): """ Returns the mean efficiency over time Args: efficiencies: a list of efficiency values Returns: A float representing the mean efficiency (among all successful rounds) or 0 if there were no successful rounds """ assert(all(np.array(efficiencies)<=1)) vals=[i for i in efficiencies if i>0] return 0 if len(vals)==0 else np.mean(vals) def cost(costs): """ Computes the average cost for the current round Args: costs: a list of costs, one for each agent Returns: the average cost """ return np.mean(costs) def social_welfare(costs,rewards): """ Computes the social welfare for the current round Args: costs: a list of costs, one for each agent rewards: a list of rewards, one for each agent Returns: the social welfare """ assert(len(costs)==len(rewards)) return np.mean(np.array(rewards)-np.array(costs)) def contributions(decisions): """ Computes the ratio of volunteering and free riding Args: decisions: the actions of agents, 1 for volunteers, 0 for free riders Returns: The proportion of volunteers """ assert(all(np.logical_or(np.array(decisions)==1,np.array(decisions)==0))) # either 0 or 1 return np.mean(decisions) def tot_contributions(decisions): assert(all(np.logical_or(np.array(decisions)==1,np.array(decisions)==0))) # either 0 or 1 return np.sum(decisions)
# 호텔 방 배정 (https://programmers.co.kr/learn/courses/30/lessons/64063) # 시간 효율성 풀이 => (https://m.blog.naver.com/js568/221957852279) # 더 깔끔한 풀이 (https://programmers.co.kr/learn/courses/30/lessons/64063/solution_groups?language=python3) # 재귀는 모두 iterative 하게 바꿀 수 있음을 유의!! import sys sys.setrecursionlimit(10000) # 재귀 허용깊이 임의로 지정 def find_empty_room(check, rooms): # 재귀 함수 if check not in rooms.keys(): # 빈 방이면( 종료 조건 ) rooms[check] = check + 1 # rooms에 새 노드 추가 return check # 요청한 방 empty = find_empty_room(rooms[check], rooms) # 재귀함수 호출 rooms[check] = empty + 1 # (배정된 방+1)을 부모노드로 변경 return empty # 새로 찾은 빈 방 def solution(k, room_number): rooms = dict() # {방번호: 바로 다음 빈방 번호} for num in room_number: check_in = find_empty_room(num,rooms) return list(rooms.keys()) # 잘 모르는거 => # 왜 dict? -> 시간 복잡도 효율성 # 재귀함수의 응용?
# 입력 N = int(input()) market = list(map(int,input().split())) M = int(input()) needs = list(map(int, input().split())) market.sort() # 이진 트리 탐색 구현 def binary_search(arr, target, start, end): if start > end: return False mid = (start + end) // 2 if arr[mid] == target: return True elif arr[mid] > target: return binary_search(arr, target, start, mid - 1) else: return binary_search(arr, target, mid + 1, end) # needs 각 원소에 대해 이진 탐색을 수행하여 yes or no 출력 for idx in needs: res = binary_search(market, idx, 0, len(market) - 1) if res == True: print("yes", end=' ') else: print("no", end=' ')
def binary_search(arr, target, start, end): if start > end: return None mid = (end + start) // 2 if arr[mid] == target: return mid elif arr[mid] > target : return binary_search(arr, target, start, mid - 1) else: return binary_search(arr, target, mid + 1, end) n, target = list(map(int, input().split())) arr = list(map(int, input().split())) res = binary_search( arr, target, 0, n-1 ) if res == None: print("Not exist element") else: print(res + 1)
import datetime def checking_Id(check): if users_ID.get(check, "none") == "none": return False else: return True class User: def __init__(self, Id="0", credit=0): self.__Id = Id self.__password = "" self.__credit = credit self.__statement = {} def set_Id(self, Id): self.__Id = Id return self.__Id def set_password(self, password): self.__password = password return self.__password def set_credit(self, credit): self.__credit += credit return self.__credit def set_credit_withdraw(self, credit): self.__credit -= credit return self.__credit def get_password(self): return self.__password def get_credit(self): return self.__credit def get_id(self): return self.__Id def adding_process(self, amount): self.__statement[amount] = (datetime.datetime.now(), "deposit") def adding_process_withdraw(self, amount): self.__statement[amount] = (datetime.datetime.now(), "withdraw") def adding_process_transfer(self, amount): self.__statement[amount] = (datetime.datetime.now(), "Transfer") def print_account_statement(self): for child in self.__statement: print(f"Type : {self.__statement[child][1]}\tvalue : {child}\tTime : {self.__statement[child][0]} ") def sign_in(self): while True: username = input("Enter your user name : \t") password = input("Enter your password :\t") if checking_Id(username): if users_ID[username].get_password() == password: self.__Id = username return True else: print("Users or password are incorrect") else: print("there is no user with this name please sign up\n") return False @staticmethod def pick_num(): while True: try: while True: choice = int(input("1-withdraw\n2-Balance Inquiry\n3-Account statement\n4-transfer\n")) if 4 >= choice >= 1: return choice else: print("enter a valid number\n") except ValueError: print("please enter number not letter !!\n") @staticmethod def sign_up(): username = input("enter your user\t") if checking_Id(username): print("this username already taken try again\n") else: password = input("Enter your password\n\t(it should contain 6 letters al least)\n") if len(password) >= 6: tempU = User(username, 0) tempU.set_password(password) users_ID[username] = tempU print("signed up successfully\n") def withdraw(self): while True: try: amount = int(input("Enter the amount :\t")) if users_ID[self.__Id].get_credit() >= amount >= 0: users_ID[self.__Id].set_credit_withdraw(amount) users_ID[self.__Id].adding_process_withdraw(amount) break else: print("The process is rejected\n(No enough money)") except ValueError: print("please enter a valid number\n") def account_statement(self): users_ID[self.__Id].print_account_statement() def transfer(self): while True: try: id1 = self.__Id id2 = input("Enter second user id :\t") val = int(input("enter the value")) if checking_Id(id1) and checking_Id(id2): if users_ID[self.__Id].get_credit() >= val >= 0: users_ID[self.__Id].set_credit_withdraw(val) users_ID[self.__Id].adding_process_transfer(val) users_ID[id2].adding_process(val) users_ID[id2].set_credit(val) print('the amount transferred successfully\n') break else: print("The process is rejected\n(No enough money)") except ValueError: print("please enter valid value\n") def balance_enquiry(self): print(f"The {self.__Id}'s balance is {users_ID[self.__Id].get_credit()} EGP ") def Processing_func(self, num): if num == 1: self.withdraw() elif num == 2: self.balance_enquiry() elif num == 3: self.account_statement() elif num == 4: self.transfer() @staticmethod def main_user_function(): sign_choice = input("1-sign in\n2-sign up\n") if sign_choice == "1": u1 = User() if u1.sign_in(): continue_in_user = "y" while continue_in_user == "y": num = User.pick_num() u1.Processing_func(num) continue_in_user = input("Do you wanna continue ?(y/n)") elif sign_choice == "2": User.sign_up() u1 = User("1", 5000) u1.set_password("1111") u2 = User("22", 5000) u2.set_password("1234") users_ID = { "1": u1, "22": u2 }
def solve(left, right, accuracy, func, derivative): x0 = 0 if derivative(left) > derivative(right): x0 = left else: x0 = right lambd = -1 / derivative(x0) x = lambd * func(x0) iterations = 0 print('iterations x0 xi func(xi) xi-x0') while abs(func(x)) > accuracy and abs(x - x0) > accuracy: iterations += 1 x0 = x x = x0 + lambd * func(x0) print(f'{iterations} {x0} {x} {func(x)} {x - x0}') return x, iterations
import math class Circle(): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 a_circle = Circle(4) print(a_circle.area())
list1 = [8, 19, 148, 4] list2 = [9, 1, 33, 83] result = [] for i in list1: for j in list2: result.append(i * j) print(result)
import random pick_amount = int(input("How many quick picks? >> ")) i = 0 for pick_amount in range(1, pick_amount+1, 1): numbers = [] for i in range(1, 6, 1): number_generate = random.randint(1, 45) if number_generate in numbers: numbers.remove(number_generate) number_generate = random.randint(1, 45) i = i-1 else: numbers.append(number_generate) print(numbers)
def score_calc(in_score): if in_score < 0: result = "Invalid Score" elif in_score > 100: result = "Invalid Score" elif in_score > 90: result = "Excellent" elif in_score > 50: result = "Acceptable" else: result = "Bad" return result score = float(input("Enter Score: ")) grade = score_calc(score) print(grade)
def summation(current_number, accumulated_sum): # base case # return the final state if current_number == 11: return accumulated_sum # recursive case # thread the state through the recursive call else: return summation(current_number + 1, accumulated_sum + current_number) if __name__ == '__main__': # pass the initial state print(summation(1, 0))
def sum1(n): # base case if n == 0: return 2 ** 0 # recursive case return 2 ** n + sum1(n - 1) def sum2(n): # base case if n == 1: return 2 # recursive case return (n * (n + 1)) + (sum2(n - 1)) user_n = int(input("Please enter the value of n: ")) print("The value of the 1st summation is", sum1(user_n)) print("The value of the 2nd summation is", sum2(user_n))
import itertools def bin_count(size): for i in itertools.product([0, 1], repeat=size): yield i size_of = int(input("Please enter the size of S: ")) set_A = [int(char) for char in input("Please enter the elements of S: ")] N = int(input("Please enter the number N: ")) all_subsets = [] for binary in bin_count(len(set_A)): indices = [i for i, j in enumerate(binary) if j == 1] subset = [] for index in indices: subset.append(set_A[index]) all_subsets.append(subset) count = 0 for cnt, sub in enumerate(all_subsets): if sum(sub) == N: tail = "," count += 1 else: tail = " " print(sub if sum(sub) == N else "", end=tail) print("there are", count, "subsets that sum up to ", N)
#! usr/bin/env python # # -*- coding: utf-8 -*- """ Posical is a Python 3 module that models a generalized calendar reform with regularly-sized weeks and months and an intercalary period, based on August Comte's Positivist Calendar. """ import datetime,operator from calendar import isleap as std_isleap from nonzero import nz POSIMONTHS = ('Moses', 'Homer', 'Aristotle', 'Archimedes', 'Caesar', 'Saint Paul', 'Charlemagne', 'Dante', 'Gutenberg', 'Shakespeare', 'Descartes', 'Frederick', 'Bichat', 'Complementary') REGMONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'October', 'November', 'December', 'Intercalary') # Ordinal code stolen from stack overflow. def ordinal(n): return "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4]) def horicat(strings): lines = ["".join(line) for line in list(zip(*strings))] return "\n".join(lines) def design_calendar(): """ A simple interactive function that asks the user for input in creating a calendar reform. If no input is given it defaults to the settings for Comte's Positivist Calendar. """ d_i_week = int(input("How many days in a week? ") or 7) w_i_month = int(input("How many weeks in a month? ") or 4) year_1 = int(input("When is year 1? ") or 1789) name = input("What is the calendar's name? ") return AlternateCal(w_i_month, d_i_week, year_1, name) class AlternateCal(object): """ A class to generate Alternate Date objects. An AlternateDate object Represents a date (day, month, year) in an idealized calendar, extending Without disruption in both directions, with the following property: it Consists of n months, all of the same size, with 365 % n epagomenal days At the end of the year that are not days of the week and belong to no month. >>> cal = AlternateCal() >>> cal.from_gregorian(1789, 1, 1) positivist date(1, 1, 1) >>> cal.from_gregorian(1788, 1, 1) positivist date(-1, 1, 1) >>> cal.from_gregorian(1, 1, 1) positivist date(-1788, 1, 1) >>> cal.from_gregorian(1788, 12, 31) positivist date(-1, 14, 2) >>> cal.from_gregorian(1789, 12, 31) positivist date(1, 14, 1) >>> print(cal.from_gregorian(1788, 6, 1)) Saturday, 13rd of Saint Paul, -1: St. Gregory the Great >>> print(cal.from_gregorian(1789, 6, 1)) Friday, 12nd of Saint Paul, 1: St. Pulcheria >>> import datetime >>> cal.date(1, 1, 1) - datetime.timedelta(days=1) positivist date(-1, 14, 2) >>> cal.from_gregorian(1, 12, 31) + datetime.timedelta(days=1) positivist date(-1787, 1, 1) >>> print(cal.date(1800, 1, 1)) Monday, 1st of Moses, 1800: Cadmus >>> print(cal.date(1801, 1, 1)) Monday, 1st of Moses, 1801: Prometheus """ def __init__(calendar, w_i_month=4, d_i_week=7, year_1=1789, input_name=""): calendar.days_in_a_month = d_i_week * w_i_month calendar.days_in_a_week = d_i_week calendar.weeks_in_a_month = w_i_month calendar.months_in_a_year = 365 // calendar.days_in_a_month calendar.epagomenal_days = 365 % calendar.days_in_a_month name_choices = ('New Adjusted', 'Utilitarian', 'Lycurgian', 'Multi-Manifold', 'Positivist', 'Crepuscular', 'Urquhart', 'Adamantine', 'Organic Non-Repeating', 'Antediluvian', 'Re-Corresponding') if input_name: calendar.name = input_name else: calendar.name = name_choices[hash((w_i_month, d_i_week, year_1)) % 11] calendar.year_offset = year_1 - 1 calendar.MINYEAR = nz(1) - calendar.year_offset if calendar.name == 'Positivist': calendar.MONTHS = POSIMONTHS else: calendar.MONTHS = REGMONTHS calendar.DAYS = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') calendar.SAINTS = ('Prometheus', 'Hercules', 'Orpheus', 'Ulysses', 'Lycurgus', 'Romulus', 'NUMA', 'Belus', 'Sesostris', 'Menu', 'Cyrus', 'Zoroaster', 'The Druids', 'BUDDHA', 'Fo-Hi', 'Lao-Tseu', 'Meng-Tseu', 'Theocrats of Tibet', 'Theocrats of Japan', 'Mano-Capac', 'CONFUCIUS', 'Abraham', 'Samuel', 'Solomon', 'Isaiah', 'St. John the Baptist', 'Haroun-al-Raschid', 'MUHAMMAD', 'Hesiod', 'Tyrt\u00E6us', 'Anacreon', 'Pindar', 'Sophocles', 'Theocritus', '\u00C6SCHYLUS', 'Scopas', 'Zeuxis', 'Ictinus', 'Praxiteles', 'Lysippus', 'Apelles', 'PHIDIAS', '\u00C6sop', 'Plautus', 'Terence', 'Phaedrus', 'Juvenal', 'Lucian', 'ARISTOPHANES', 'Ennius', 'Lucretius', 'Horace', 'Tibullus', 'Ovid', 'Lucan', 'VIRGIL', 'Anaximander', 'Anaximenes', 'Heraclitus', 'Anaxagoras', 'Democritus', 'Herodotus', 'THALES', 'Solon', 'Xenophanes', 'Empedocles', 'Thucydides', 'Archytas', 'Apollonius of Tyana', 'PYTHAGORAS', 'Aristippus', 'Antisthenes', 'Zeno', 'Cicero', 'Epictetus', 'Tacitus', 'SOCRATES', 'Xenocrates', 'Philo of Alexandria', 'St. John the Evangelist', 'St. Justin', 'St.Clement of Alexandria', 'Origen', 'PLATO', 'Theophrastus', 'Herophilus', 'Erasistratus', 'Celsus', 'Galen', 'Avicenna', 'HIPPOCRATES', 'Euclid', 'Aristeus', 'Theodisius of Bithynia', 'Hero', 'Pappus', 'Diophantus', 'APOLLONIUS', 'Eudoxus', 'Pytheas', 'Aristarchus', 'Eratosthenes', 'Ptolemy', 'Albategnius', 'HIPPARCHUS', 'Varro', 'Columella', 'Vitruvius', 'Strabo', 'Frontinus', 'Plutarch', 'PLINY THE ELDER', 'Miltiades', 'Leonidas', 'Aristides', 'Cimon', 'Xenophon', 'Phocion', 'THEMISTOCLES', 'Pericles', 'Philip', 'Demosthenes', 'Ptolemy Lagus', 'Philopoemen', 'Polybius', 'ALEXANDER', 'Junius Brutus', 'Camillus', 'Fabricius', 'Hannibal', 'Paulus Aemilius', 'Marius', 'SCIPIO', 'Augustus', 'Vespasian', 'Hadrian', 'Antonius', 'Papinian', 'Alexander Severus', 'TRAJAN', 'St. Luke', 'St. Cyprian', ' St.Athanasius', 'St. Jerome', 'St. Ambrose', 'St. Monica', ' St.AUGUSTINE', 'Constantine', 'Theodosius', 'St. Chrysostom', ' St.Genevieve of Paris', 'St. Pulcheria', 'St. Gregory the Great', 'HILDEBRAND', 'St. Benedict', 'St. Boniface', 'St. Isidore of Seville', 'Lanfranc', 'Heloise', "Architects of Middle Ages", ' St.BERNARD', 'St. Francis Xavier', 'St. Charles Borromeo', 'St. Theresa', 'St. Vincent de Paul', 'Bourdaloue', 'William Penn', 'BOSSUET', 'Theodoric the Great', 'Pelayo', 'Otho the Great', 'St. Henry', 'Villers', 'Don John of Austria', 'ALFRED', 'Charles Martel', 'The Cid', 'Richard I', 'Joan of Arc', 'Albuquerque', 'Bayard', 'GODFREY', 'St. Leo the Great', 'Gerbert', 'Peter the Hermit', 'Suger', 'Alexander III', 'St. Francis of Assisi', 'INNOCENT III', 'St. Clotilde', 'St. Bathilda', 'St. Stephen of Hungary', 'St. Elizabeth of Hungary', 'Blanche of Castille', 'St. Ferdinand III', 'ST. LOUIS', 'The Troubadours', 'Boccaccio', 'Rabelais', 'Cervantes', 'La Fontain', 'De Foe', 'ARISTO', 'Leonardo da Vinci', 'Michael Angelo', 'Holbein', 'Poussin', 'Velásquez', 'Teniers', 'RAPHAEL', 'Froissart', 'Camoens', 'The Spanish Romancers', 'Chateaubriand', 'Walter Scott', 'Manzoni', 'TASSO', 'Petrarca', 'Thomas \u00E0 Kempis', 'Mme. de Lafayette', 'F\u00E9n\u00E9lon', 'Klopstock', 'Byron', 'MILTON', 'Marco Polo', 'Jacques Coeur', 'Vasco de Gama', 'Napier', 'Lacaille', 'Cook', 'COLUMBUS', 'Benvenuto Cellini', 'Amontons', 'Harrison', 'Dollond', 'Arkwright', 'Cont\u00e9', 'VAUCANSON', 'Stevin', 'Mariotte', 'Papin', 'Black', 'Jouffroy', 'Dalton', 'WATT', 'Bernard de Palissy', 'Guglielmini', 'Duhamel (du Monceau)', 'Saussure', 'Coulomb', 'Carnot', 'MONTGOLFIER', 'Lope de Vega', 'Moreto', 'Rojas', 'Otway', 'Lessing', 'Goethe', 'CALDERON', 'Tirso', 'Vondel', 'Racine', 'Voltaire', 'Metastasio', 'Schiller', 'CORNEILLE', 'Almarcon', 'Mme. de Motteville', 'Mme. de S\u00E9vign\u00E9', 'Lesage', 'Mme. de Staal', 'Fielding', 'MOLIERE', 'Pergolese', 'Sacchini', 'Gluck', 'Beethoven', 'Rossini', 'Bellini', 'MOZART', 'Albertus Magnus', 'Roger Bacon', 'St. Bonaventura', 'Ramus', 'Montaigne', 'Campanella', 'ST. THOMAS AQUINAS', 'Hobbes', 'Pascal', 'Locke', 'Vauvenargues', 'Diderot', 'Cabanis', 'LORD BACON', 'Grotius', 'Fontenelle', 'Vico', 'Fr\u00E9ret', 'Montesquieu', 'Buffon', 'LEIBNITZ', 'Robertson', 'Adam Smith', 'Kant', 'Condercet', 'Joseph de Maistre', 'Hegel', 'HUME', 'Marie de Molina', 'Cosmo de Medici the Elder', 'Philippe de Comines', 'Isabella of Castille', 'Charles V', 'Henry IV', 'LOUIS XI', "L'H\u0244pital", 'Barneveldt', 'Gustavus Adolphus', 'De Witt', 'Ruyter', 'William III', 'WILLIAM THE SILENT', 'Ximenes', 'Sully', 'Mazarin', 'Colbert', "D'Aranda", 'Turgot', 'RICHELIEU', 'Sidney', 'Franklin', 'Washington', 'Jefferson', 'Bolivar', 'Francia', 'CROMWELL', 'Copernicus', 'Kepler', 'Huyghens', 'James Bernouilli', 'Bradley', 'Volta', 'GALILEO', 'Vieta', 'Wallis', 'Clairaut', 'Euler', "D'Alembert", 'Lagrange', 'NEWTON', 'Bergmann', 'Priestley', 'Cavendish', 'Guyton Morveau', 'Berthollet', 'Berzelius', 'LAVOISIER', 'Harvey', 'Bo\u0235rhaave', 'Linn\u0230us', 'Haller', 'Lamarck', 'Broussais', 'GALL', 'Festival of All the Dead', 'Festival of Holy Women') calendar.LEAPSAINTS = ('Cadmus', 'Theseus', 'Tiresias', '', '', '', '', 'Semiramus', '', '', '', '', 'Ossian', '', '', '', '', '', '', 'Tamehameha', '', 'Joseph', '', 'David', '', '', 'Abderrahman', '', '', 'Sappho', '', '', 'Euripides', 'Longus', '', '', '', '', '', '', '', '', 'Pilpay', '', 'Menander', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'Leucippus', '', '', '', '', '', '', 'Philolaus', '', '', '', '', '', 'Pliny the Younger', 'Arrian', '', '', '', '', '', 'St. Irenaeus', '', 'Tertullian', '', '', '', '', '', '', 'Averrhoes', '', '', '', '', 'Ctesibius', '', '', '', 'Aratus', 'Nearchus', 'Berosus', 'Sosigenes', '', 'Nasir-Eddin', '', '', '', '', '', '', '', '', '', '', '', '', '', 'Epaminondas', '', '', '', '', '', '', '', '', '', 'Cincinnatus', 'Regulus', '', '', 'The Gracchi', '', 'M&#230cenas', 'Titus', 'Nerva', 'Marcus Aurelius', 'Ulpian', 'Aetius', '', 'St. James', '', '', '', '', '', '', '', '', 'St. Basil', '', 'Marcian', '', '', 'St. Anthony', 'St. Austin', 'St. Bruno', 'St. Anselm', 'Beatrice', 'St. Benezet', '', 'Ignatius Loyola', 'Fredrick Borromeo', 'St.Catharine of Siena', "Abb\u00E9 de l'Ep\u00E9e", 'ClaudeFleury', 'George Fox', '', '', '', 'Henry the Fowler', '', 'La Valette', 'John Sobieski', '', '', 'Tancred', 'Saladin', 'Marina', 'Sir Walter Raleigh', '', '', 'Leo IV', 'PeterDamian', '', 'St. Eligius', 'Becket', 'St. Dominic', '', '', 'St. Mathilda of Tuscany', 'Mathias Corvinus', '', '', 'Alfonso X', '', '', 'Chaucer', 'Swift', '', 'Burns', 'Goldsmith', '', 'Titian', 'Paul Veronese', 'Rembrandt', 'Lesueuer', 'Murillo', 'Rubens', '', 'Joinville', 'Spenser', '', '', 'James Fenimore Cooper', '', '', '', 'L. of Granada & Bunyan', 'Mme. de Sta\u00EBl', 'St. Francis of Sales', 'Gessner', '\u00E9. Mercoeur & Shelly', '', 'Chardin', 'Gresham', 'Magellan', 'Briggs', 'Delambre', 'Tasman', '', '', 'Wheatstone', 'Pierre Leroy', 'Graham', 'Jacquard', '', '', 'Torricelli', 'Boyle', 'Worcester', '', 'Fulton', 'Thilorier', '', '', 'Riquet', 'Bourgelat', 'Bouguer', 'Borda', 'Vauban', '', 'Montalvan', 'Guillem de Castro', 'Guevara', '', '', '', '', '', '', '', '', 'Alfieri', '', '', '', 'Mme. Roland', 'Lady Montagu', 'Sterne', 'Miss Edgeworth', 'Richardson', '', 'Palestrina', 'Gr\u00E9try', 'Lully', 'Handel', 'Weber', 'Donizeti', '', 'John of Salisbury', 'Raymond Lully', 'Joachim', 'The Cardinal of Cusa', 'Erasmus', 'Sir Thomas More', '', 'Spinoza', 'Giordano Bruno', 'Malebranche', 'Mme. de Lambert', 'Duclos', 'George Leroy', '', 'Cujas', 'Maupertuis', 'Herder', 'Winckle-mann', "D'Aguesseau", 'Oken', '', 'Gibbon', 'Dunoyer', 'Fichte', 'Ferguson', 'Bonald', 'Sophie Germain', '', '', '', 'Guicciardini', '', 'Sixtus V', '', '', '', '', '', '', '', '', '', '', 'Oxenstiern', 'Walpole', 'Louis XIV', 'Pombal', 'Campomanes', '', 'Lambert', 'Hampden', 'Kosciusko', 'Madison', "Toussaint L'Ouverture", '', '', 'Tycho Brah\u00E9', 'Halley', 'Varignon', 'John Bernouilli', 'R\u00F5mer', 'Sauveur', '', 'Harriot', 'Fermat', 'Poinsot', 'Monge', 'Daniel Bernouilli', 'Joseph Fourier', '', 'Scheele', 'Davy', '', 'Geoffroy', '', 'Ritter', '', 'Charles Bell', 'Stahl & Barthez', 'Bernard de Jussieu', "Vicq-d'Azyr", 'Blainville', 'Morgagni', '', '', 'Festival of Holy Women') class AlternateDate(object): """ A date object that's designed to behave analagously to the standard library's datetime date objects. To begin creating date objects, first create an AlternateCal object. That can then generate objects using the today() or the from_gregorian() methods. """ def __init__(self, year, month, day, altcal): self.year = nz(year) self.month = nz(month) self.day = nz(day) self.day_of_year = nz((month - 1) * altcal.weeks_in_a_month * altcal.days_in_a_week + day) self.gregorian = altcal.to_gregorian(self.total_days()) if self.day_of_year > 366: raise ValueError("Date exceeds days in year") if self.year < altcal.MINYEAR: raise ValueError("Year is earlier than minimum of {}".format(altcal.MINYEAR)) self.is_leap = std_isleap(self.gregorian.year) self.weekday = nz(altcal.get_weekday(self.day)) self.month_name = altcal.get_month_name(self.month) self.day_name = altcal.get_day_name(self.day_of_year, self.is_leap) self.weekday_name = altcal.get_weekday_name(self.weekday) def total_days(self): """ Return the total number of days since year 1. """ year = self.year + calendar.year_offset d_o_year_offset = int(self.day_of_year) - 1 return datetime.date(year, 1, 1).toordinal() + d_o_year_offset def replace(self, year=None, month=None, day=None): new_year = nz(year) or self.year new_month = nz(month) or self.month new_day = nz(day) or self.day return calendar.date(new_year, new_month, new_day) def timetuple(self): return self.gregorian.timetuple() def toordinal(self): return self.gregorian.toordinal() def weekday(self): """ Following the datetime.date weekday() model, returns 0-indexed weekday int """ return int(self.weekday) - 1 def isoweekday(self): return self.weekday def isocalendar(self): return self.gregorian.isocalendar() def isoformat(self): return "{}-{:02}-{:02}".format(self.year, self.month, self.day) def __str__(self): if self.month is calendar.months_in_a_year + 1: return "{}, {}".format(self.day_name, self.year) else: return "{}, {} of {}, {}: {}".format(self.weekday_name, ordinal(self.day), self.month_name, self.year, self.day_name) def __repr__(self): return '%s date(%d, %d, %d)' % (calendar.name.lower(), self.year, self.month, self.day) def __add__(self, arg): return self.calendar.from_gregorian(arg + self.gregorian) __radd__ = __add__ def __sub__(self, arg): return self.calendar.from_gregorian(self.gregorian - arg) def __rsub__(self, arg): return self.calendar.from_gregorian(arg - self.gregorian) def __eq__(self, other_date): return other_date == self.gregorian def __gt__(self, other_date): return self.gregorian > other_date def __lt__(self, other_date): return self.gregorian < other_date def __ge__(self, other_date): return self.gregorian >= other_date def __le__(self, other_date): return self.gregorian <= other_date AlternateDate.calendar = calendar calendar.date_class = AlternateDate calendar.min = calendar.date(calendar.MINYEAR, 1, 1) calendar.max = calendar.from_gregorian(datetime.date.max) def from_gregorian(self, *args): """ Create an alternate date given one of three formats: 1. Three integers in Gregorian Y, M, D format. 2. A datetime date object. """ if not args: raise ValueError("No Gregorian date provided") if len(args) == 3: year, month, day = args gregorian = datetime.date(year, month, day) elif len(args) == 1 and isinstance(args[0], datetime.date): gregorian = args[0] else: raise ValueError("Please provide a datetime object or 3 ints in Y-M-D format") year = nz(gregorian.year) - self.year_offset day_of_year = gregorian.timetuple().tm_yday month = ((day_of_year - 1) // self.days_in_a_month) + 1 day = day_of_year % self.days_in_a_month or self.days_in_a_month return self.date_class(year, month, day, self) def to_gregorian(self, days): return datetime.date.fromordinal(days) def date(self, *args): """ Create an alternate date given a 'native' input: Three integers in Y, M, D format of the alternate calendar. """ if not args: raise ValueError("Please provide values in Y, M, D format") year, month, day = args return self.date_class(year, month, day, self) def today(self): return self.from_gregorian(datetime.date.today()) def fromtimestamp(t): return self.from_gregorian(datetime.date.fromtimestamp(t)) def fromordinal(o): return self.from_gregorian(datetime.date.fromordinal(o)) def get_weekday(self, day): return day % self.days_in_a_week or self.days_in_a_week def get_weekday_name(self, weekday): weekday = int(weekday) if weekday > len(self.DAYS): return ordinal(weekday) + " Weekday" else: return self.DAYS[weekday - 1] def get_month_name(self, month): month = int(month) if month > len(self.MONTHS): return ordinal(month) + " Month" else: return self.MONTHS[(month - 1)] def get_day_name(self, day, is_leap): day = int(day) if day > len(self.SAINTS): return "" elif is_leap and self.LEAPSAINTS[day - 1]: return self.LEAPSAINTS[day - 1] else: return self.SAINTS[day - 1] def is_leap(self, year): return std_isleap(year + self.year_offset) def print_month(self, year=None, month=None): """ Print out a formatted one-page calendar for the specified year/month. """ page = [] maxwidth = max(len(saint) for saint in self.SAINTS + self.LEAPSAINTS) if not year or not month: today = self.today() year = today.year month = today.month if month == self.months_in_a_year + 1: intercal = True page.append("THE {} EPAGOMENAL DAYS OF THE YEAR {}".format( self.name.upper(), year)) else: intercal = False page.append("THE {} MONTH OF {}, {}".format( self.name.upper(), self.get_month_name(month).upper(), year)) month_offset = (month - 1) * self.weeks_in_a_month * self.days_in_a_week for week in range(self.weeks_in_a_month): calbox = [] week_offset = (week * self.days_in_a_week) for date in range(1 + week_offset, week_offset + self.days_in_a_week + 1): day_of_year = month_offset + date if day_of_year > len(self.SAINTS): break if not intercal: weekday = self.get_weekday(date) wkd_name = self.get_weekday_name(weekday) datestr = str(date) else: weekday = 0 wkd_name = "" datestr = "" saint = self.get_day_name(day_of_year, self.is_leap(year)) if day_of_year == self.today().day_of_year: saint = "*" + saint + "*" height = 4 box = [] cap = "|" if day_of_year % self.days_in_a_week == 0 else "" box.append("+".ljust(maxwidth + 1, '-') + cap) if wkd_name: box.append("|" + wkd_name.ljust(maxwidth - len(datestr)) + datestr + cap) else: box.append("|".ljust(maxwidth + 1) + cap) for i in range(height): box.append("|".ljust(maxwidth + 1) + cap) box.append("|" + saint.rjust(maxwidth) + cap) calbox.append(box) cal_layout = horicat(calbox) page.append(cal_layout) return "\n".join(page) def __str__(self): return "The {} calendar, consisting of {}-day weeks, {}-week months, and {}-month years, with {} epagomenal day(s).".format( self.name, self.days_in_a_week, self.weeks_in_a_month, self.months_in_a_year, self.epagomenal_days) if __name__ == "__main__": import doctest doctest.testmod()
import regex as re import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def find_hashtags(tweet): """This function will extract hashtags""" return re.findall('(#[A-Za-z]+[A-Za-z0-9-_]+)', tweet) def hashtag_correlations(Data, republican=False, democrat=False): for i in range(len(Data)): Data['hashtags'] = Data["Tweets"].apply(find_hashtags) # take the rows from the hashtag columns where there are actually hashtags if republican: # dataframe with republican's hashtags hashtags_list = Data.loc[ (Data["Party"].apply( lambda party: party == "Republican" )) & (Data["hashtags"].apply( lambda hashtag_list: hashtag_list != [] )), ['hashtags']] elif democrat: # dataframe with democrat's hashtags hashtags_list = Data.loc[ (Data["Party"].apply( lambda party: party == "Democrat" )) & (Data["hashtags"].apply( lambda hashtag_list: hashtag_list != [] )), ['hashtags']] # create dataframe where each use of hashtag gets its own row flattened_hashtags = pd.DataFrame( [hashtag for hashtags_list in hashtags_list.hashtags for hashtag in hashtags_list], columns=['hashtag']) popular_hashtags = flattened_hashtags.groupby('hashtag').size() \ .reset_index(name='counts') \ .sort_values('counts', ascending=False) \ .reset_index(drop=True) # take hashtags which appear at least this amount of times min_appearance = 40 # find popular hashtags - make into python set for efficiency popular_hashtags_set = set(popular_hashtags[ popular_hashtags.counts >= min_appearance ]['hashtag']) # make a new column with only the popular hashtags hashtags_list['popular_hashtags'] = hashtags_list.hashtags.apply( lambda hashtag_list: [hashtag for hashtag in hashtag_list if hashtag in popular_hashtags_set]) # drop rows without popular hashtag popular_hashtags_list = hashtags_list.loc[ hashtags_list.popular_hashtags.apply(lambda hashtag_list: hashtag_list != [])] # make new dataframe hashtag_vector = popular_hashtags_list.loc[:, ['popular_hashtags']] for hashtag in popular_hashtags_set: # make columns to encode presence of hashtags hashtag_vector['{}'.format(hashtag)] = hashtag_vector.popular_hashtags.apply( lambda hashtag_list: int(hashtag in hashtag_list)) hashtag_matrix = hashtag_vector.drop('popular_hashtags', axis=1) # calculate the correlation matrix correlations = hashtag_matrix.corr() # plot the correlation matrix plt.figure(figsize=(30, 20)) sns.heatmap(correlations, cmap='RdBu', vmin=-1, vmax=1, square=True, cbar_kws={'label': 'correlation'}) if republican: plt.savefig("./images/hashtag_republican.png", format="PNG") elif democrat: plt.savefig("./images/hashtag_democrat.png", format="PNG")
# coding:utf-8 """ @Author : Cong @Time : 2021/6/17 14:13 """ class Kid: def __init__(self, gid): self.gid = gid self.left = None self.right = None class Cycle: def __init__(self, count): self.head = None self.tail = None for i in range(count): self.add(Kid(i+1)) def add(self, kid): if self.head is None and self.tail is None: self.head = kid self.tail = kid kid.left = kid kid.right = kid else: kid.left = self.head kid.right = self.tail self.head.right = kid self.tail.left = kid self.tail = kid def remove(self, kid): if kid is self.head: self.head = kid.left if kid is self.tail: self.tail = kid.right kid.left.right = kid.right kid.right.left = kid.left kid.left = None kid.right = None cycle = Cycle(500) cur = cycle.head step = 1 while cycle.head is not cycle.tail: cur = cur.left if step % 3 == 0: cycle.remove(cur.right) step += 1 print(cycle.head.gid)
##MTH TO LAST ELEMENT ##SPONSORING COMPANY: ## ##CHALLENGE DESCRIPTION: ## ##Write a program which determines the Mth to the last element in a list. ## ##INPUT SAMPLE: ## ##The first argument is a path to a file. The file contains the series of ##space delimited characters followed by an integer. The integer represents ##an index in the list (1-based), one per line. ## ##For example: ## ##a b c d 4 ##e f g h 2 ## ## ##OUTPUT SAMPLE: ## ##Print to stdout the Mth element from the end of the list, one per line. ##If the index is larger than the number of elements in the list, ignore ##that input. ## ##For example: ## ##a ##g import sys; import argparse; def main(argv=None): with open(sys.argv[1]) as f: lines = [line.rstrip('\n') for line in f] for line in lines: if len(line)>1: items=line.split(' ') pos=len(items)-int(items[len(items)-1])-1 if pos>=0: print(items[pos]) main()
##DISTINCT SUBSEQUENCES ##CHALLENGE DESCRIPTION: ## ##A subsequence of a given sequence S consists of S with zero or ##more elements deleted. Formally, a sequence Z = z1z2..zk is a ##subsequence of X = x1x2...xm, if there exists a strictly increasing ##sequence of indicies of X such that for all j=1,2,...k we have ##Xij = Zj. E.g. Z=bcdb is a subsequence of X=abcbdab with corresponding ##index sequence <2,3,5,7> ## ##INPUT SAMPLE: ## ##Your program should accept as its first argument a path to a filename. ##Each line in this file contains two comma separated strings. The first ##is the sequence X and the second is the subsequence Z. E.g. ## ## ## ##babgbag,bag ##rabbbit,rabbit ##OUTPUT SAMPLE: ## ##Print out the number of distinct occurrences of Z in X as a subsequence ##E.g. ## ## ##5 ##3 import sys; import argparse; def numDistinct(word1, word2): a=len(word1) b=len(word2) dp = [[0 for x in range(b+1)] for x in range(a+1)] for i in range(a+1): dp[i][0]=1 for i in range(1,a+1,1): for j in range(1,b+1,1): dp[i][j]=dp[i-1][j] if word1[i-1]==word2[j-1]: dp[i][j]+=dp[i-1][j-1] return dp[a][b] def main(argv=None): with open(sys.argv[1]) as f: lines = [line.rstrip('\n') for line in f] for line in lines: if len(line)>1: words=line.split(',') letPositions=dict() print(numDistinct(words[0],words[1])) main()
""" Class notes for Lucille Brown Mondays - Intro to Computer Science """ # 10/2 # General Introductions: name, age, coding experience, techem # What is computer science, computers, programming/coding # terminal: # mkdir student_name # geany helloworld.py print "Hello World!" print "anything you want" -- strings print 22 + 42 # Variables a = "hello" b = "world" print a + b print a + " " + b --string concatenation # DATA Types FLOAT STRING BOOL INT # found in all programming languages a = 10 b = 5 print a + b # input a = raw_input("give me a number") b = raw_input("give me another number") print a + b # Integers a = int(raw_input("give me a number")) b = int(raw_input("give me another number")) print a + b # 10/4 # Had students from Monday's class as well as new ones # quick review of monday's content # each created new folders # Started to create simple interactive calculator python program # ended with code blocks: 1st condition statment (if user enetered "+") # 10/16 # finished calculator (started last week --ended with first condition block) # implemented the turtle module # 10/18 # Turtle Graphics Intro # make a right angle # for and while loops # 10/23 # Binary number review # focus on 0 and 1 meaning # Gates intro # AND, OR, NOT # how to represent: diagram, truth table, boolean # Simple calculator with turtle # 10/30 # pygame: pacman # 11/1 # simple command response program # create additional commands, handle the new command(s) with new condition(s) # more multi-way decision patterns # pacman.py contest # 11/8 # Simple conditional program (rollercoaster.py) # Binary Search Tree # how computer search through sorted lists efficiently # introduced with 'unplugged' random number game: pick number between 1 and 100 # class guessed randomly # ask: what if first guessed a number in the middle of the range? Then again, and so on until guess is correct. # put binary search tree on whiteboard (range: 1 - 15), explaining how it works; nodes, parents, # less than, search left side of parent branch; greater than, search right side of parent branch # put random number game into a py program # have class figure out on their own how to structure the conditional statements
#!/usr/bin/env python3 import socket import os import threading import socketserver SERVER_HOST = 'localhost' SERVER_PORT = 0 BUF_SIZE = 1024 ECHO_MSG = 'Hello echo server!' class ThreadedClient(): """ A client to test a multithreaded server """ def __init__(self, ip, port): # Create a socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to the server self.sock.connect((ip, port)) def run(self): """ Client playing with the server """ # Send the data to the server current_thread_id = threading.current_thread() print("Thread ID %s sending echo message to the server: %s" % (str(current_thread_id), ECHO_MSG)) sent_data_length = self.sock.send(ECHO_MSG.encode("utf-8")) print("Sent: %d characters so far..." % sent_data_length) # Display the server response response = self.sock.recv(BUF_SIZE) current_thread = threading.current_thread() print("TID %s received: %s" % (current_thread.name, response.decode("utf-8")[5:])) def shutdown(self): # Clean up self.sock.close() class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): def handle(self): # Return the echo data = self.request.recv(BUF_SIZE) current_thread = threading.current_thread() response = ("%s: %s" % (current_thread.name, data)) self.request.sendall(response.encode("utf-8")) return class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): # Nothing to add here, we have inherited what we need from the parent classes pass def main(): # Run the server server = ThreadedTCPServer((SERVER_HOST,SERVER_PORT), ThreadedTCPRequestHandler) ip, port = server.server_address # Start a thread with the server -- one thread per request server_thread = threading.Thread(target=server.serve_forever) # Exit the server thread when the main thread exits server_thread.daemon = True server_thread.start() print("Server loop running on thread: %s" % server_thread.name) # Run the clients client1 = ThreadedClient(ip, port) client2 = ThreadedClient(ip, port) client3 = ThreadedClient(ip, port) client1.run() client2.run() client3.run() # It's the Final Cleanup! server.shutdown() client1.shutdown() client2.shutdown() client3.shutdown() server.socket.close() if __name__ == '__main__': main()
def get_anagram_diff_report(a, b): a_hashmap = get_frequency_hashmap(a) b_hashmap = get_frequency_hashmap(b) chars_to_remove_from_a = get_char_difference(a_hashmap, b_hashmap) chars_to_remove_from_b = get_char_difference(b_hashmap, a_hashmap) return "remove {cnt_a} characters from '{a}' and {cnt_b} characters from '{b}'".format( a = a, cnt_a = chars_to_remove_from_a, b = b, cnt_b = chars_to_remove_from_b ) def get_char_difference(subject_hashmap, target_hashmap): chars_to_remove_from_subject = 0 for char in subject_hashmap: if (char not in target_hashmap) or (subject_hashmap[char] > target_hashmap[char]): chars_to_remove_from_subject += 1 return chars_to_remove_from_subject def get_frequency_hashmap(s): hashmap = {} for char in s: if char in hashmap: hashmap[char] += 1 else: hashmap[char] = 1 return hashmap def check_anagram(a, b): return a == b def anagram_example_result(a, b): sorted_a = sorted(a) sorted_b = sorted(b) if check_anagram(sorted_a, sorted_b): return "they are anagrams" else: return get_anagram_diff_report(a, b) def main(): a = input("a:") b = input("b:") print(anagram_example_result(a, b)) if __name__ == '__main__': main()
#!/bin/python3 import sys """ Bubble sort method """ n = int("3".strip()) a = list(map(int, "3 2 1".strip().split(' '))) #a = list(map(int, "1 2 3".strip().split(' '))) iSwaps = 0 for _ in range(n): for j in range(n-1): if a[j]>a[j+1]: iTemp=a[j+1] a[j+1]=a[j] a[j]=iTemp iSwaps+=1 print("Array is sorted in %s swaps." % iSwaps) print("First Element: %s" % a[0]) print("Last Element: %s" % a[len(a)-1])
"""Reaction file.""" import json import random class Reactions: """Check if there is expected word in "reactions" dict to generate phrases from GrandPyBot. In : reactions (dict) Act : compare words in "reactions" list, with expected words, like 'HELLO' create a string with messages concatanated. messages are from "bot_answers.json" Out : bonus_message (list). """ def __init__(self, reactions): """Open and load bot_answers.json, and launch functions.""" with open( "grandPyApp/static/ressources/bot_answers.json", "r", encoding="utf-8" ) as data: self.bot_answers = json.load(data) self.reactions = reactions self.bonus_message = [] self.courtesy() self.hello() self.how_are() self.time() self.random_tchat() def courtesy(self): """Create message reaction from 'COURTESY' words detected.""" if self.reactions["COURTESY"] != "True": self.bonus_message.append(self.bot_answers["COURTESY"]) def hello(self): """Create message reaction from 'HELLO' words detected.""" if self.reactions["HELLO"] == "True": self.bonus_message.append(self.bot_answers["HELLO"]) def how_are(self): """Create message reaction from 'HOW_ARE' words detected.""" if self.reactions["HOW_ARE"] == "True": self.bonus_message.append(self.bot_answers["HOW_ARE"]) def time(self): """Create message reaction from 'TIME' words detected.""" if self.reactions["TIME"] == "True": self.bonus_message.append(self.bot_answers["TIME"]) def random_tchat(self): """Create a random message reaction.""" self.bonus_message.append(random.choice(self.bot_answers["TCHAT"]))
#FALTA HACER METODO DE IMPRESION DE LA TABLA DE HASH class entry: def __init__(self, nombreID,blockID,tipo,mundoId,tareaId): self.nombreID = nombreID self.blockID = blockID self.tipo = tipo self.mundoId = mundoId self.tareaId = tareaId class leblancCook: def __init__(self): self.dict = {} self.stack = [] def find(self,id): x = self.dict[id] return x #revisa si el id se encuentra ya dentro de la tabla de hash # Devuelve False si no se puede agregar debido a que ya existe # Devuelve True en caso de agregarlo de manera satisfactoria # ver cuando crecer la pila def insert(self,id,entries): if id in self.dict: #verificamos que no esten en el mismo scope x = self.dict[id] for elem in x: if entries.blockID == elem.blockID: msg = "No puede haber renombramiento de variable dentro del mismo scope. "+"\n" self.error(id,msg) #si no estan en el mismo scope que alguno de los de la lista con el mismo id x.insert(0,entries) d1 = {id:x} self.dict.update(d1) return True else: if isinstance(entries, entry): d1 = {id:[entries]} self.dict.update(d1) return True # Si se consigue un nuevo marco de pila def push(self,blockID): self.stack.append(blockID) def pop(self): self.stack.pop() def isEmpty(self): if (len(self.stack) == 0): return True else: return False def error(self,id,msg): print("Error: "+ msg + " Problema con el ID : '" + str(id) + "'\n") raise SystemExit #Pruebas de los metodos symbolTable = leblancCook() print(symbolTable.isEmpty()) entrada = entry("mundo1",0,"bool","mundo1","t1") entrada1 = entry("mundo1",1,"bool","mundo1","t1") entrada2 = entry("mundo1",1,"bool","mundo1","t1") symbolTable.insert("mundo1",entrada) symbolTable.insert("mundo1",entrada1) #symbolTable.insert("mundo1",entrada2) print(symbolTable.dict) l = symbolTable.find("mundo1") #l = symbolTable.dict["mundo1"] print("Tamanio de la lista "+ str(len(l)) + "\n") '''d = {} d1 = {"a":"1"} d2 = {"a":"2"} d.update(d1) d.update(d2) print(d)'''
from reinforcement_learning.Tic_tac_toe.GameBoardState import GameBoardState import numpy as np import re class Human_player_interface: def __init__(self, player_mark : int): self.player_mark: int = player_mark assert player_mark in [1, 2] def choose_next_action_play(self, in_gameboard: GameBoardState) -> GameBoardState: action_taken = False while not action_taken: print('Please enter the move that you want to make.\n') print('Enter the \'(row, column)\' number of where you want to place your mark.\n') user_input = input('Example top left is (0,0).\n') pattern = r'\b(?:\({0,1}([0-2][ ,][0-2])\){0,1})\b' numbers = re.findall(pattern, user_input) if numbers: numbers = numbers[0] if ',' in numbers: numbers = [int(x) for x in numbers.split(',')] else: numbers = [int(x) for x in numbers.split(' ')] if in_gameboard.board_matrix[numbers[0], numbers[1]] != 0: print('Please enter location which is empty. Invalid entry! Please try again.\n') in_gameboard.draw_game_board() continue in_gameboard.board_matrix[numbers[0], numbers[1]] = self.player_mark action_taken = True return in_gameboard else: print('Please enter valid location. Invalid entry! Please try again.\n') in_gameboard.draw_game_board()
def binary_search(arr,x): low = 0 high = len(arr) - 1 mid = 0 while low <= high : mid = (low + high) // 2 if arr[mid] < x : # ignoring left half low = mid + 1 elif arr[mid] > x : # ignoring right half high = mid - 1 else : # X is present at mid return mid # x is not present return -1 #enter sorted array here arr = [-1,1,3,5,8,10,12,15,18,19,25,29,35,38,39,40,44,48,49] # reading x x = int(input('Enter X ')) # getting the index of x in sorted array result = binary_search(arr,x) if result != -1 : print('the item',x,'is present at the index ', str(result)) else: print('the item',x,' is not present')
import json import random #CAMINHOS MINIMOS #carrega o grafo atraves do arquivo Json g = json.load(open('data5.json')) #retorna os vizinhos do vertice solicitado no grafo def vizinhos(grafo,v): v = str(v) vizinhos = [] arestas = grafo["arestas"] for par in arestas: #par percorre as arestas if(par.count(v) > 0): #se contem o vertice v em alguma das arestas for x in par : #x percorre par if(x != v): #se x e diferente de v significa que ele e vizinho de v vizinhos.append(str(x)) #insere x return vizinhos def CaminhoMinimo(grafo, s): #Funcao criada utilizando o algoritmo Dijkstra w = [] #lista de peso das arestas rd = 0 #valor do radom linha = [] #linha vazia para preencher a lista de peso das arestas #preenchendo a matriz de pesos com valores nulos for i in range (len(grafo["vertices"])): for j in range (len(grafo["vertices"])): linha.append(None) w.append(linha) linha = [] for vw in grafo["arestas"]:#preenchendo a listas de pesos com pesos aleatorios para as arestas existentes rd = random.random() * 100 #gerando numero aleatorio entre 0 e 100 w[int(vw[0]) - 1][int(vw[1]) - 1] = rd #insere numero aleatorio w[int(vw[1]) - 1][int(vw[0]) - 1] = rd #insere numero aleatorio d = [float('inf')]*len(grafo["vertices"]) #distancia entre o start e o v T = [False]*len(grafo["vertices"]) #caminho minimo entre v e start P = [None]*len(grafo["vertices"]) #menor caminho entre v e start d[s-1] = 0 for i in grafo["vertices"]: #percorre vertices do grafo if not T[int(i)-1]: #n�o T[v] u = int(i)-1 T[u] = True #T[u] = V for v in vizinhos(grafo, (u+1)): #percorre os vizinhos de v if d[int(v) - 1] > (w[int(v) - 1][u]+d[u]): #se distancia entre s e v e maior que w(xy)+d(y,s) d[int(v) - 1] = (w[int(v) - 1][u]+d[u]) #d[v] recebe w[vu]+d[u] P[int(v) - 1] = (u+1) return d, P #Marcando Tempos import time inicio = time.time() CaminhoMinimo(g, 1) #Iniciando do vertice 1 fim = time.time() print ('duracao: %0.9f' % (fim - inicio))
import random # generate account number for new user import time # show time to user upon login import validation import database from getpass import getpass localtime = time.asctime(time.localtime(time.time())) print("Current local time is :", localtime) # register # - first name, last name , email # - generate user account # login # - account number and and password def init(): #isValidOptionSelected = False print("Welcome of Bank of QueenB!") #while isValidOptionSelected == False: haveAccount = int(input("Do you have an account with us: 1 (yes) or 2 (no)? \n")) if (haveAccount == 1): isValidOptionSelected = True login() elif (haveAccount == 2): isValidOptionSelected = True register() else: print("You have entered an invalid selection!") def login(): print("Please login to your account.") account_number_from_user = input("What is your account number? \n") is_valid_account_number = validation.account_number_validation(account_number_from_user) if is_valid_account_number: password = getpass("What is your password \n") user = database.authenticated_user(account_number_from_user, password) if user: bank_operation(user) print("Invalid account or password, please try again!") # didnt check for validation login() else: print("Account number is invalid: check that you have up to 10 digits and only integers") init() def register(): print("******** Register now! ********* ") email = input("What is your email address? \n") first_name = input("What is your first name? \n") last_name = input("What is your last name? \n") password = getpass("Create a password for yourself \n") account_number = generation_account_number() is_user_created = database.create(account_number, first_name, last_name, email, password) if is_user_created: print("Your Account Has been created") print(" == ==== ====== ===== ===") print("Your account number is: %d" % account_number) print("Make sure you keep it safe") print(" == ==== ====== ===== ===") login() else: print("Something went wrong, please try again") register() def bank_operation(user): print("Welcome %s %s " % (user[0], user[1])) selected_option = int(input("What would you like to do? (1) deposit (2) withdrawl (3) Logout (4) Report Issue (5) Exit).\n")) if (selected_option == 1): deposit_operation(user) elif (selected_option == 2): withdrawal_operation(user) elif (selected_option == 3): login() elif (selected_option == 4):#Added new selection for user from previous assignment report_complaint() elif (selected_option == 5): exit() # to leave the program else: print("Invalid Option selected, please try again!") bank_operation(user) ##set up new functions from each operation: withdrawl, deposit and complaint def withdrawal_operation(user): withdrawal_amount = int(input("How much would you like to withdraw? \n")) print("You withdrew $%s" % withdrawal_amount + "!\n") balance = int((user[4])) new_balance = str(balance - int(withdrawal_amount)) print("Your current balance is $ %s!" % new_balance) database.withdrawal(user, withdrawal_amount) init() pass #Improvement def deposit_operation(user): deposit_amount = int(input("How much would you like to deposit? \n")) print("You have deposited $ %s"% deposit_amount + "! \n") current_balance = int((user[4])) updated_balance = str(current_balance + int(deposit_amount)) print("Your current balance is now $ %s" % updated_balance) database.deposit(user, deposit_amount) init() pass def generation_account_number(): # print("Generating Account Number") ## dont need to show this to user return random.randrange(1111111111, 9999999999) #Improvement def report_complaint(): # print("You selected option %s" % selectedOption) complaint = input("What issue will you like to report? \n") print("Thank you for contacting us! \n") pass #4/16 Improvement def set_current_balance(user_details, balance): user_details[4] = balance #4/16 Improvement def get_current_balance(user_details): return user_details[4] # 4 is the position of balance def logout(): login() ###Actual Banking System ### ### print(generateAccountNumber()) init()
# liste = [1, 2, 3, 4, 5, 6, 7, 8] # liste[:round(len(liste)/2)], liste[round(len(liste)/2):] = liste[round(len(liste)/2):], liste[:round(len(liste)/2)] # print(liste) ########### n = int(input("Please, enter a single digit integer")) if 0 <= n < 10: for i in range(n): if i%2==0: print(i)
def find_Words(text, mot):#prend une liste de string et un mot taille = len(text) #on calcule la taille du texte mot= ' ' + mot + ' '#on rajoute des espaces avant et apres le mot taille3=len(mot) #on calcule la taille du mot dico=dict() #on initialise un dico pour faire toutes les parties for k in range(0,taille): #on parcourt toutes les parties compte=text[k].count(mot) #on calcule le nombre de fois que le mot apparait dans la partie liste=list() #On initialise une liste ou il y aura les indices pour une partie i=1 #permet de se deplacer dans la liste j=1 if compte>0: #si il y a au moins une occurence taille2=len(text[k]) #on calcule la taille de la partie qu'on analyse liste.append(text[k].find(mot)+1) #on rajoute l'indice de la premiere lettre de la premiere #occurence du mot liste.append(liste[0]+taille3-3) #On rajoute l'indice de la derniere lettre de la premiere #occurence du mot while (i< compte) : #on continue tant qu'il existe encore des occurences du mot liste.append(text[k].find(mot,liste[j]+2,taille2)+1) #on ajoute l'indice de la premiere lettre de l'occurence suivante du mot j=j+1 #on incremente j liste.append(liste[j]+taille3-3) #on ajoute l'indice de la derniere lettre du mot i=i+1 j=j+1 if len(liste)>0 : dico[k]=liste #on ajoute la liste avec tous les indices pour la partie dans le dico return dico #retourne une clef du dico qui est le numero de la partie (paragraphe, page, proportion,...) # associe a une liste d'indice (debut et fin)
% python >>> string1 = 'Wakanda' >>> string2 = 'Forever' >>> string1 + string2 'WakandaForever' >>> string1 + " Pride " + string2 ' Wakanda Pride Forever ' >>> string3 = string1 + string2 + "Strength" >>> string3 'WakandaForeverStrength' >>> string3[2:10] #string 3 from index 2 (0-based) to 10
# http://codeforces.com/problemset/problem/112/A s1 = input() s2 = input() s1 = s1.lower() s2 = s2.lower() if s1<s2: print("-1") elif s2<s1: print("1") else: print("0")
# http://codeforces.com/problemset/problem/131/A s = input() if s[0].islower() and s[1:].isupper(): print(s.capitalize()) elif s.isupper(): print(s.lower()) elif len(s)==1 and s.islower(): print(s.upper()) else: print(s)
# http://codeforces.com/problemset/problem/405/A input() li = list(map(int, input().split())) li.sort() for l in li: print(l, end=' ')
# http://codeforces.com/problemset/problem/486/A n = int(input()) _sum = int(n/2) if n%2 == 0: print(_sum) else: print("-"+str(_sum+1))
#Method 2 - Bubble Sort def bubble_sort(list2): # Traverse (travel across) through every element on the list for i in range(0, len(list2) - 1): # Compare each item in list 1 by 1. Comparison in each iteration # will shorten as the last elements become sorted for j in range(0, len(list2) - 1 - i): # traverse the list from 0 to n-i-1 # if the element found is greater than the next element, swap if list2[j] > list2[j + 1]: list2[j], list2[j + 1] = list2[j + 1], list2[j] return list2 list2 = [2, 3, 7, 1, 9, 5] bubble_sort(list2) print(list2) #When the above code is executed, it produces the following result − #[1, 2, 3, 5, 7, 9]
import numpy as np # input list a = [[1,2,3],[4,5,6]] # convert to numpy array b = np.array(a, float) # number of dimensions => 2 print(b.ndim) # number of rows and columns => (2,3) print(b.shape) #data type => float64 print(b.dtype) # Slicing operations # : in first argument means do this on all dimensions => [1,2],[4,5] print(b[:, 0:2]) # slicing along specific direction => [4,5] print(b[1,0:2]) # reshape => total size (m*n) should not change. So 2*3 in the above example can be 3*2 or 6*1. c = b.reshape((3,2)) print(c) #transpose print(c.transpose()) #flatten multi dimensional array to 1d print(c.flatten()) #concatenate. Join 2 or more arrays # if one of the arrays is multi dimensional, we can specifiy the axis along which the concatentaion should happen array1 = np.array([[1,2],[3,4]], float) array2 = np.array([[5,6],[7,8]], float) array3 = np.concatenate((array1, array2)) print(array3) array3 = np.concatenate((array1,array2),axis=1) print(array3)
''' Created on Jul 24, 2018 @author: Anil.Kale ''' # printing 0 to 5, default increment is 1 for x in range(6): print(x) print() # printing 2 to 5 for x in range(2,6): print(x) print() # printing from 2 to 15 with 3 as increment for x in range(2, 15, 3): print(x)
''' Created on Jul 26, 2018 @author: Anil.Kale ''' class MyClass: x = 5 print (x) #create an object of class and access the variable obj = MyClass() print (obj.x)
import math, copy class Board(object): def __init__(self, board): self._board = board self._size = int(math.sqrt(len(board))) """ Returns: -100 - winner is X player 100 - winner is O player 0 - it is tie None - game is still active """ def winner(self): board_str = ''.join(self._board) board_rvr = copy.deepcopy(self._board) # Columns for i in xrange(self._size): if board_str[i::self._size].count('O') == self._size: return 100 if board_str[i::self._size].count('X') == self._size: return -100 # Rows for i in xrange(0, self._size**2, self._size): board_rvr[i:i + self._size] = reversed(board_rvr[i:i + self._size]) if (board_str[i:i + self._size]).count('O') == self._size: return 100 if (board_str[i:i + self._size]).count('X') == self._size: return -100 # Diagonals if self._size == board_str[::self._size + 1].count('O'): return 100 if self._size == board_str[::self._size + 1].count('X'): return -100 if self._size == board_rvr[::self._size + 1].count('O'): return 100 if self._size == board_rvr[::self._size + 1].count('X'): return -100 if 0 == self._board.count('-'): return 0 return None def __str__(self): board_string = "" for i in xrange(self._size): for j in xrange(self._size): board_string += self._board[i * self._size + j] board_string += '\n' return board_string """ In this function we return features: - #X's in top left corner - #O's in top left corner - #X's in top right corner - #O's in top right corner - #X's in middle - #O's in middle - #X's in bottom left corner - #O's in bottom left corner - #X's in bottom right corner - #O's in bottom right corner """ def get_features(self): x_1 = self._board[0].count('X') x_2 = self._board[0].count('O') x_3 = self._board[2].count('X') x_4 = self._board[2].count('O') x_5 = self._board[4].count('X') x_6 = self._board[4].count('O') x_7 = self._board[6].count('X') x_8 = self._board[6].count('O') x_9 = self._board[8].count('X') x_a = self._board[8].count('O') x_b = self._board[1].count('X') x_c = self._board[1].count('O') x_d = self._board[3].count('X') x_e = self._board[3].count('O') x_f = self._board[5].count('X') x_g = self._board[5].count('O') x_h = self._board[7].count('X') x_i = self._board[7].count('O') return [1, x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_a, x_b, x_c, x_d, x_e, x_f, x_g, x_h, x_i] def get_possible_positions(self): possible_positions = [] for i in xrange(self._size**2): if '-' == self._board[i]: possible_positions.append(i) return possible_positions def calculate_utility(self, W): X = self.get_features() utility = 0 for i in xrange(len(X)): utility += X[i] * W[i] return utility def max_learner_utility(self, weights): max_utility = None learner_position = None for i in self.get_possible_positions(): self._board[i] = 'O' current_utility = self.calculate_utility(weights) if current_utility > max_utility or max_utility is None: max_utility = current_utility learner_position = i self._board[i] = '-' return learner_position
#!/usr/bin/python3 #Made by Kirill Shvedov my_name = "kirill" x = "second_half" alphabet = [1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26] #numbers of letters in the alphabet name_leters = list(my_name) #name_leters.append("k") #name_leters.append("i") #name_leters.append("r") #name_leters.append("i") #name_leters.append("l") #name_leters.append("l") name_leters[0] = alphabet[10] print(alphabet[10]) if name_leters[0] >= 14: print('''First letter of my name goes to the x of the alphabet.''') else: print('''First letter of my name goes to the 1 half of the alphabet.''')
''' ''' class Node: def __init__(self,val): self.val = val self.next = None if __name__=="__main__": elements = [1,2,3,4,5] head = Node(0) temp = head for element in elements: temp.next = Node(element) temp = temp.next head = head.next temp = head while temp: print(temp.val) temp = temp.next
def longestPeak(array): longestPeakLength = 0 i = 1 while i < len(array)-1: peak = array[i-1] < array[i] and array[i] > array[i+1] if not peak: i += 1 continue lIdx = i - 2 while lIdx >= 0 and array[lIdx] < array[lIdx+1]: lIdx -= 1 rIdx = i+2 while rIdx < len(array) and array[rIdx] < array[rIdx-1]: rIdx +=1 currentPeakLength = rIdx - lIdx-1 longestPeakLength = max(longestPeakLength, currentPeakLength) i = rIdx return longestPeakLength print(longestPeak([1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]))
def arrayOfProducts(array): products = [1 for _ in range(len(array))] for i in range(len(array)): temp = 1 for j in range(len(array)): if j != i: temp *= array[j] products[i] = temp return products print(arrayOfProducts([5, 1, 4, 2]))
import random as R count = 0 x = R.randint(0,100) while True: y = int(input("请输入一个整数:")) count += 1 if y == x: print("恭喜您猜对了!!!") break elif y < x: print("您输入的数字太小,再接再厉~") elif y > x: print("您输入的数字太大,再接再历~") print("您猜了", count, '次数字')
# 一、定义列表:list1 = ['life','is','short'], # list2 = ['you','need','python'] # 完成以下几个要求: # 1)输出python及其下标 # 2)将 'python' 改为 'python3' # 3) 将list1和list2合并构造集合 list_set2 # list1 = ['life','is','short'] # list2 = ['you','need','python'] # print(list2[2], list2.index('python')) # list2[2] = 'python3' # print(list2) # list1.extend(list2) # list_set2 = set(list1) # print(list_set2) # 二、通讯录管理 # =======通讯录管理系统======= # 1.增加姓名和手机号 # 2.删除姓名 # 3.修改手机号 # 4.查询所有用户 #输出为一个表格 # 5.根据姓名查找手机号 # 6.退出 # ============================ # import time # def menu(): # print("+----------------------+") # print("| 1.增加姓名和手机号 |") # print("| 2.删除姓名 |") # print("| 3.修改手机号 |") # print("| 4.查询所有用户 |") # print("| 5.根据姓名查找手机号 |") # print("| 6.退出 |") # print("+----------------------+") # def main(): # menu() # tip = input("输入序号:") # if tip == '1': # add_infos() # time.sleep(1) # return main() # elif tip == '2': # del_name() # time.sleep(3) # return main() # elif tip == '3': # mod_num() # time.sleep(3) # return main() # elif tip == '4': # show_infos() # time.sleep(3) # return main() # elif tip == '5': # search_num() # time.sleep(3) # return main() # elif tip == '6': # return print('退出') # def input_name(): # try: # name = input("输入姓名:") # except: # print("---名字不合法---") # return input_name # else: # if name: # return name # else: # print("---默认名字为None---") # def add_infos(): # name = input_name() # try: # ph_num = int(input("输入电话号码:")) # except ValueError: # print("---号码不合法,保存失败---") # return add_infos # else: # info = {'name': name, 'ph_num':ph_num} # LIST.append(info) # return # def del_name(): # name = input_name() # for key in LIST: # if key['name'] == name: # del LIST[LIST.index(key)] # print("---删除成功---") # return # print("---删除失败---") # def mod_num(): # name = input_name() # for key in LIST: # if key['name'] == name: # try: # ph_mun = int(input("输入新的号码:")) # except ValueError: # print("---输入的号码不合法---") # return mod_num() # else: # key['ph_num'] = ph_mun # print("---修改成功---") # return # print("---修改失败---") # def show_infos(name=None): # print("+---------+----------------+") # print("| name | ph_mun |") # print("+---------+----------------+") # if name: # for key in LIST: # if key['name'] == name: # ph_num = str(key['ph_num']) # print("|%s|%s|" %(name.center(9), # ph_num.center(16))) # else: # for key in LIST: # name = key['name'] # ph_num = str(key['ph_num']) # print("|%s|%s|" %(name.center(9), # ph_num.center(16))) # print("+---------+----------------+") # def search_num(): # name = input_name() # for key in LIST: # if key['name'] == name: # show_infos(name) # return # print("---查无此人---") # if __name__ == '__main__': # LIST = [{'name': 'tarena', 'ph_num': 123456789}, {'name': 'mike', 'ph_num': 987654321}] # main() # print(LIST) # 三、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数 d = {} string = input("请输入一段字符串:") def count(string, n=0): for i in string: if ord(i) == 32: num += 1 d["空格"] = num elif 65 <= ord(i) <= 122: num += 1 d['字母'] = num else: num += 1 d['其他'] = num print(d) count(string) # 四、给定排序数组和目标值,如果找到目标,则返回索引。如果没有,请返回索引按顺序插入的索引。 # 您可以假设数组中没有重复项。 # 输入: [1,3,5,6],5 输出: 2 # 输入: [1,3,5,6],2 输出: 1 # 输入: [1,3,5,6],7 输出: 4 # 输入: [1,3,5,6],0 输出: 0 # 五、罗马数字是由七个不同的符号来表示 I,V,X,L,C,D和M。 # 符号 值 # 我1 # V 5 # X 10 # L 50 # C 100 # D 500 # M 1000 # 例如,两个用II 罗马数字写成,只有两个加在一起。十二写为,XII简称X+ II。数字二十七写为XXVII,XX+ V+ II。 # 罗马数字通常从左到右从最大到最小。但是,四个数字不是IIII。相反,第四个被写为IV。因为一个在五个之前,我们减去四个。同样的原则适用于编号为9的数字IX。有六个使用减法的实例: # I可以在V(5)和X(10)之前放置4和9。 # X可以在L(50)和C(100)之前放置40和90。 # C可以在D(500)和M(1000)之前放置以产生400和900。 # 给定罗马数字,将其转换为整数。输入保证在1到3999的范围内。
# file_open.py # 此示例示意读取当前文件夹下myfile.txt这个记录文字信息的 # 文件 # 1.打开文件 try: myfile = open('myfile.txt') # 成功打开文件 # myfile = open('我不存在.txt') # 失败 print("文件打开成功") # 2. 读/写文件 # 3. 关闭文件 myfile.close() print("文件关闭成功") except OSError as O: # OSError表示无法进行输入输出 print('文件打开失败!', O)
#此示例示意函数可以返回另一个函数的引用关系 def get_function(): s = input("请输入你要做的操作") if s == "求最大": return max elif s == "求最大": return min elif s == "求最大": return max else: return print L = [2, 4, 6, 8, 10] f = get_function() #相当于f绑定 max(),min(),max() print(f(L))
# 写程序将这些数据读取出来,并以如下格式打印在屏幕终端上 # 小张 今年 20 岁,成绩是: 100 # 小李 今年 18 岁,成绩是: 98 # 小赵 今年 19 岁,成绩是: 80 # def read_info_from_file(): # '''此函数将从文件中读取信息 # 形成字典的列表''' # L = [] # try: # fr = open('info.txt', 'rt') # # 读取数据放在列表L中 # for line in fr: # line = '小张 20 100\n' # line = line.strip() # line = '小张 20 100' # lst = line.split() # lst=['小张', '20', '100'] # n, a, s = lst # 序列赋值 a='20' s='100' # a = int(a) # s = int(s) # 转为整数 # d = dict(name=n, age=a, score=s) # L.append(d) # 放入列表 # fr.close() # except OSError: # print("读取文件失败!") # return L # def print_info(L): # for d in L: # print(d['name'], '今年', d['age'], # '岁, 成绩是:', d['score']) # infos = read_info_from_file() # print_info(infos) try: info = open('/home/tarena/my_project/day16/info.txt') f = info.readlines() for i in range(len(f)): l = f[i].split(' ') print(l[0], "今年", l[1], "岁","成绩是:" ,l[2], end='') # for line in info: # print(line[6]) except OSError: print("文件打开失败") finally: info.close()
#try_except.py def div_apple(n): print("%d个苹果你想分给几个人?" % n) s = input('请输入人数:') count = int(s) #<---可能触发ValueError错误 result = n / count #<---可能触发ZeroDivisionError错误 print("每人分了", result, '个苹果') try: div_apple(10) print("分苹果成功") # except ValueError as VE: # print("分苹果失败,苹果被收回", VE) # except ZeroDivisionError: # print("没人分苹果,苹果被收回!") except (ValueError, ZeroDivisionError): print("错啦") else: print("此try语句内未发生任何异常") #div_apple无任何异常时执行 print("程序正常结束") # except ValueError: # print() # except: # print()
# 1. 写一个程序,输入您的出生日期(年月日) # 1) 算出你已经出生多少天? # 2) 算出你出生那天是星期几? import time y = int(input("请输入出生的年: ")) m = int(input("请输入出生的月: ")) d = int(input("请输入出生的日: ")) # 第一步算出出生时的计算机元年的秒数 birth_tuple = (y, m, d, 0, 0, 0, 0, 0, 0) birth_second = time.mktime(birth_tuple) # 得到当前时间的秒数 cur_second = time.time() # 算出出生的秒数 life_scond = cur_second - birth_second life_days = life_scond / 60 / 60 // 24 # 地板除取整 print("您已出生:", life_days, '天') # 2. 得到出生那天的时间元组,根据元组来获取数据 t = time.localtime(birth_second) weeks = { 0:'星期一', 1:'星期二', 2:'星期三', 3:'星期四', 4:'星期五', 5:'星期六', 6:'星期日', } print("您出生那里是:", weeks[t[6]])
# Blueprint: class Car: wheels = 4 #Class Variable - all objects have this by default def __init__(self, size, brand, year, color): self.size = size # Instance Variable: can change for each object self.brand = brand # Instance Variable self.year = year # Instance Variable self.color = color # Instance Variable car_1 = Car("Large", "Ford", 2021, "Red") car_2 = Car("Small", "Honda", 2022, "Blue") # Both cars have the same default "wheels" value print("Before changes, Car_1 has " + str(car_1.wheels) + " wheels") print("Before changes, Car_2 has " + str(car_2.wheels) + " wheels") Car.wheels = 2 # Changing this Class Variable affects both instances print("After changes, Car_1 has " + str(car_1.wheels) + " wheels") print("After changes, Car_2 has " + str(car_2.wheels) + " wheels")
# is_pair함수는 문자열 s를 매개변수로 입력받습니다. # s에 괄호가 알맞게 짝지어져 있으면 True를 아니면 False를 리턴하는 함수를 완성하세요. # 예를들어 s가 (hello)()면 True이고, )(이면 False입니다. # s가 빈 문자열("")인 경우는 없습니다. def is_pair(s): ch_stack = [] for ch in s: if ch == '(': ch_stack.append(ch) elif ch == ')': try: ch_stack.pop() except IndexError: return False return len(ch_stack) == 0 print( is_pair("(hello)()")) print( is_pair(")(")) print( is_pair("(())")) print( is_pair(")())"))
# 앞뒤를 뒤집어도 똑같은 문자열을 palindrome이라고 합니다. # longest_palindrom함수는 문자열 s를 매개변수로 입력받습니다. # s의 부분문자열중 가장 긴 palindrom의 길이를 리턴하는 함수를 완성하세요. # 예를들어 s가 토마토맛토마토이면 7을 리턴하고 토마토맛있어이면 3을 리턴합니다. def is_palindrom(s): return s == s[::-1] assert (is_palindrom('토마토')) assert (not is_palindrom('토마토마')) def longest_palindrom(s): if not s: # 매개변수가 ""일 때? return 0 if is_palindrom(s): return len(s) longest_val = 1 for st_idx in range(0, len(s)): for end_idx in range(st_idx + 1, len(s)+1): word = s[st_idx: end_idx] if is_palindrom(word): longest_val = max(longest_val, len(word)) return longest_val print(longest_palindrom('토마토맛토마토')) print(longest_palindrom('토마토맛있어')) print(longest_palindrom("맛있어토마토"))
#coding: utf-8 #文字列の連結 a = 'python' b = '2.7' c = a + b print c #文字列配列の結合 strings = ['dog','cat','penguin'] print ','.join(strings) #文字列の繰り返し s = 'dog?' print s * 3 #値の埋め込み #sprintf a = "python" b = "a programming language" print "%s is %s" % (a,b) #拡張sprintf v = dict(first = "Michael", family = "Jackson") print "He is %(first)s, %(first)s %(family)s." % v #formatメソッド print"{0},{1}".format("Hello", "World") #置換 s = "Today is Monday" print s print s.replace("Monday","Sunday") s2 = "Hello Hello" print s2.replace("Hello", "Bye") s3 = "World World" print s3.replace("World", "Hello", 1) print s3.replace("World", "Hello", 2) s4 = "World World World" print s4.replace("World", "Hello", 1) import re s = "Hello World" print re.sub(r"[a-z]","A",s) #N文字目の文字の取得 s = "abc" n = 1 print s[n-1] s2 = "xyz" print s2[-1] #部分文字列の取得(N文字目から、M文字取り出す) s = "This is a pen." n = 1 m = 4 print s[n-1:n-1+m] print s[0:4] print s[-4:-1] #-4 <= s < -1 #検索 s = "abcabcabc" index = s.find('b') print index index = s.find("b",2) print index target = "b" index = -1 while True: index = s.find(target,index + 1) if index == -1: #見つからなかったら-1を返す break print "start = %d" % index #1文字ずつ処理 for c in "aiueo": print c print list("hoge") s = "aiueo" for i in range(len(s)): c = s[i] print c #strip s = " x " print "A" + s.strip() + "B" print "A" + s.lstrip() + "B" print "A" + s.rstrip() + "B" #改行削除 line = "hoge\n" msg = line.rstrip() + "moge" print msg ''' with open("./test.txt") as fh: for line in fh: no_line_break_line = line.rstrip() ''' #全部大文字にする print "hello".upper() #全部小文字にする print "BIG".lower() #ある文字列が部分文字列として含まれるかどうか調べる s = "abc" print "b" in s print "x" in s #ある文字列が部分文字列として登場する回数を数える s = "aaabbc" print s.count("b") #intを文字列に変換する v = 1 print str(v) print "%d" % v #floatを文字列に変換する f = 1.234 print str(f) print "%f" %f #listを文字列に変換する、tupleを文字列に変換する v = [1,2,3] print str(v) print "%s" % v v = (1,2,3) print str(v) #print "%s" % v print "%s" % (v,) print "<" + ("/".join([str(item) for item in v])) + ">"
#coding: utf-8 class MyClass: """A sample class""" PI = 3.14 def __init__(self): self.name = "" def getName(self): return self.name def setName(self,name): self.name = name a = MyClass() a.setName("Tanaka") print a.getName() print MyClass.PI class MyClass: def __init__(self): self.name = "" a1 = MyClass() a1.name = "Sato" a2 = MyClass() a2.name = "Suzuki" print a1.name print a2.name class MyClass: count = 0 def __init__(self): MyClass.count += 1 a1 = MyClass() a2 = MyClass() print MyClass.count class MyClass: pass a1 = MyClass() a1.name2 = "Takahashi" MyClass.PI2 = 3.141 print a1.name2 print MyClass.PI2 class MyClass: PI = 3.14 a1 = MyClass() a2 = MyClass() print a1.PI a1.PI = 3.141593 print a1.PI print a2.PI class MyClass: name = "Yamada" def setName(self,name): self.name = name a = MyClass() b = MyClass() a.setName("Ito") print a.name print b.name class MyClass: def __init__(self): self.name = "tanaka" self._name = "yamada" self.__name = "suzuki" def hello(self): print "hello" def _hello(self): print "hello" def __hello(self): print "hello" a = MyClass() print a.name print a._name # print a.__name 参照できない a.hello() a._hello() #a.__hello() print a._MyClass__name a._MyClass__hello() class MyClass: def __init__(self): print "INIT!" def __del__(self): print "DEL!" a = MyClass() del a class MyClass: def __init__(self,name): self.name = name def __str__(self): return "My name is " + self.name a = MyClass("Yamada") print a class MyClass: def hello(self): print "Hello" class MyClass2(MyClass): def world(self): print "World" a = MyClass2() a.hello() a.world() class MyClass3(MyClass): def hello(self): print "HELLO" a = MyClass3() a.hello() class MyClass1(object): def __init__(self): self.val1 = 123 class MyClass2(MyClass1): def __init__(self): super(MyClass2,self).__init__() self.val2 = 456 a = MyClass2() print a.val1 print a.val2 class MyClassA: def funcA(self): print "MyClassA:funcA" class MyClassB: def funcB(self): print "MyClassB:funcB" class MyClassC(MyClassA,MyClassB): def funcC(self): print "MyClassC:funcC" a = MyClassC() a.funcA() a.funcB() a.funcC()
import math def i2arr(n): # write Fibonacci series up to n "Print array" result=[] while n>9: b=n%10 result.append(b) n=int(n/10) result.append(n) return result def check_palindrom(array): # write Fibonacci series up to n flag=1 n=len(array) #for i in range(n/2): # print array[i], i if (len(array)%2==0): for i in range(n/2): if (array[i]!=array[n-i-1]): flag=0 break else: for i in range((n-1)/2): if (array[i]!=array[n-i-1]): flag=0 return flag max_palindrom=0 for i in range(999,2,-1): for j in range(999,2,-1): nos=i * j array=i2arr(nos) flag=check_palindrom(array) ## print nos, i, j if (flag==1): ##print nos, i, j if (nos>max_palindrom): max_palindrom=nos print max_palindrom
def fib(n): # write Fibonacci series up to n "Print a Fibonacci series up to n" result=[] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result f1000=fib(2000) print f1000
print(type(42)) #python提供了内建函数。 #函数int接受任何值,并在其能做到的情况下,将该值转换成一个整型数,否则会报错。 print(int('32')) #print(int('Hello')) #int能将浮点数转换为整型数,但是他并不进行舍入;这是截掉了小数点部分。 print(int(3.99999)) print(int(-2.3)) #float可以将整型数和字符串转换为浮点数。 print(float(32)) print(float('3.14159')) #string可以将实参转换成字符串。 print(str(32)) print(str(3.14159)) import math print(math) #点标记法 #ratio=signal_power/noise_power #decibels=10*math.log10(ratio) radians=0.7; height=math.sin(radians) degrees=45 radians=degrees/180.0*math.pi print(math.sin(radians)) x=math.sin(degrees/360.0*2*math.pi) x=math.exp(math.log(x+1)) #minutes=hours*60 #hours*60=minutes #函数定义的第一行被称作函数头(header); 其余部分被称作函数体(body)。 函数头必须以冒号结尾,而函数体必须缩进。 按照惯例,缩进总是4个空格。 函数体能包含任意条语句。 def repeat_lyrics(): print_lyrics() print_lyrics() def print_lyrics(): print("I'm a lumberjack,and I'm okay.") print("I sleep all night and I work all day") #print(print_lyrics()) #print(type(print_lyrics())) repeat_lyrics() def print_twice(bruce): print(bruce) print(bruce) print_twice('Spam') print_twice(42) print_twice(math.pi) print_twice('Sapm'*4) print_twice(math.cos(math.pi)) michael='Eric,the half a bee.' print_twice(michael) def cat_twice(part1,part2): cat=part1+part2 print_twice(cat) line1='Bing tiddle' line2='tiddle bang.' cat_twice(line1,line2) #print(cat) x=math.cos(radians) golden=(math.sqrt(5)+1)/2 print(math.sqrt(5)) math.sqrt(5) result=print_twice('Bing') print(result) print(type(None))
def any_lowercase1(s): for c in s: if c.islower(): return True else: return False def rotate_word(word,a): if word.islower(): for letter in word: b = ord(letter) b = b + a print(chr(b), end='') elif not word.islower(): for letter in word: b = ord(letter) def make_word_dict(): d= dict() fin = open('words.txt') for line in fin: word = line.strip() d[word] = None return d def rotate_pairs(word, word_dict): """Prints all words that can be generated by rotating word. word: string word_dict: dictionary with words as keys """ for i in range(1, 14): rotated = rotate_word(word, i) if rotated in word_dict: print(word, i, rotated) word_dict = make_word_dict() for word in word_dict: rotate_pairs(word,word_dict)
def make_dict(): fin = open('words.txt') s = dict() for letter in fin: word = letter.strip() s[word] = None return s print(make_dict()) print('aahe' in make_dict())
def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d def most_frequent(string): t = list(string) d = histogram(t) max = 1 for key in d : if d[key]>max: max = d[key] i = max while i >=1: for key in d: if d[key] == i: print(key) i = i-1 most_frequent('risist')
def nested_sum(t): total = 0 for x in t: total +=sum(x) return total t = [[1, 2], [3], [4, 5, 6]] print(nested_sum(t))
import math class Point: """Represents a point in 2-D space.""" print(Point) blank = Point() print(blank) blank.x = 3.0 blank.y = 4.0 print(blank.y) x = blank.x print(x) print('(%g, %g)' % (blank.x, blank.y)) distance = math.sqrt(blank.x**2 + blank.y**2) print(distance) def print_point(p): print('(%g, %g)' % (p.x, p.y)) print_point(blank) def distance_between_points(p1,p2): distance= math.sqrt((p1.x-p2.x)**2+(p1.y-p2.y)**2) return distance print(distance_between_points(blank,blank)) class Rectangle: """ Represents a rectangle. attributes: width, height, corner. """ box = Rectangle() box.width = 100.0 box.height = 200.0 box.corner = Point() box.corner.x = 0.0 box.corner.y = 0.0 def find_center(rect): p = Point() p.x = rect.corner.x + rect.width/2 p.y = rect.corner.y + rect.height/2 return p center = find_center(box) print_point(center) box.width = box.width + 50 box.height = box.height + 100 def grow_rectangle(rect, dwidth, dheight): rect.width += dwidth rect.height += dheight print(box.width,box.height) grow_rectangle(box, 50, 100) print(box.width, box.height) def move_rectangle(rect, dx, dy): rect.corner.x += dx rect.corner.y += dy p1 = Point() p1.x = 3.0 p1.y = 4.0 import copy p2 = copy.copy(p1) print_point(p1) print_point(p2) print(p1 is p2) print(p1 == p2) box2 = copy.copy(box) print(box2 is box) print(box2.corner is box.corner) box3 = copy.deepcopy(box) print(box3 is box) print(box3.corner is box.corner) def move_rectangle_new(rect,dx,dy): rect1 = copy.deepcopy(rect) rect1.corner.x += dx rect1.corner.y += dy p = Point() p.x = 3 p.y = 4 #print(p.z) print(type(p)) print(isinstance(p,Point)) print(hasattr(p, 'x')) print(hasattr(p, 'z')) try: x = p.x except AttributeError: x = 0
def cumsum(t): s = [] for i in range(len(t)): s.append(sum(t[:i+1])) return s t = [1, 2, 4,5] print(cumsum(t))
fin = open('words.txt') def has_no_e1(word): for letter in word: if letter == 'e': return False return True print(has_no_e1('wired')) def has_no_e2(): a = 0 b = 0 for line in fin: a = a+1 if has_no_e1(line): print(line) b = b+1 print(b/a) has_no_e2()
"""Module convert angle""" from typing import Union import numpy as np __all__ = ['degrees_to_rad', 'minutes_to_rad', 'seconds_to_rad', 'angle_to_rad'] def degrees_to_rad(degrees: Union[float, np.ndarray]) -> Union[float, np.ndarray]: """ Convert angles in degrees to radians :param degrees: angle in degrees :return: angle in radians """ return degrees / 180 * np.pi degrees_to_rad_multi = degrees_to_rad # pylint: disable=invalid-name def minutes_to_rad(amin: Union[float, np.ndarray]) -> Union[float, np.ndarray]: """ Convert minutes to radians :param amin: angle in minutes :return: angle in radians """ return amin / 60 / 180 * np.pi def seconds_to_rad(asec: Union[float, np.ndarray]) -> Union[float, np.ndarray]: """ Convert seconds to radians :param asec: angle in seconds :return: angle in radians """ return asec / 3600 / 180 * np.pi def angle_to_rad( degrees: Union[float, np.ndarray] = 0, amin: Union[float, np.ndarray] = 0, asec: Union[float, np.ndarray] = 0 ) -> Union[float, np.ndarray]: """ Convert angles in degrees, minutes and seconds to radians :param degrees: angle in degrees :param amin: angle in minutes :param asec: angle in seconds :return: angle in radians """ return (degrees + amin / 60 + asec / 3600) / 180 * np.pi
import threading # 继承方式创建线程的类, 再改写,添加方法 class ra(threading.Thread): def __init__(self,name,data): threading.Thread.__init__(self) self.name = name self.data = data # run方法是唯一要调用的方法,也是最重要的方法 def run(self): print(self.name+'sing'+self.data) # 更多的方法必须由run()函数二次调用才能被写进创建的线程 self.login() self.riger() def login(self): print('dengru') def riger(self): print('zhuci') def main(): t1 = ra('liuhuan', 'song') t2 = ra('qiqing', 'songs') print(threading.enumerate()) ''' t1.start() t1.join() t2.start() t2.join()''' t1.run() print(threading.enumerate()) t1.start() print(threading.enumerate()) t1.login() print(threading.enumerate()) t1.riger() print(threading.enumerate()) t2.run() # start()方法是唯一调用线程的方法,也是最重要的方法 t2.start() if __name__ == '__main__': # 读取私有文件 main()
import tkinter # 建立一个窗口对象(容器) win = tkinter.Tk() # 实例 win.title('我是一个窗口') # 窗口名称 win.geometry('400x400+600+20') # 窗口大小 # label标签控件 # text文本, bg 背景色, fg 字体颜色 label = tkinter.Label(win, text='我是一个控件', bg='red', fg='black', width=10, height=4, justify='left') label.place(x=200, y=100) # 布局显示 win.mainloop() # mainloop()无限循环, 运行后弹出一个窗口
# generator solution def even_integers_generator(n): for i in range(n): if i % 2 == 0: yield i def main(): even_nums = even_integers_generator(20) print(list(even_nums)) if __name__ == "__main__": main()
x = "James" print('Hello World from {}'.format(x)) # f stands for format print(f'Hello World from {x}')
#Joseph Day #Project Euler #112 Bouncy Numbers def increasing(x): digits = [int(d) for d in str(x)] first = digits[0] for digit in digits: second = digit if first > second: return False first = digit return True def decreasing(x): return increasing(int(str(x)[::-1])) def bouncy(x): return not(increasing(x) or decreasing(x)) def go(bound): numerator = 0 denominator = 1 current = 1 while numerator/denominator < bound: current+=1 if bouncy(current): numerator+=1 denominator+=1 return denominator
import sqlite3 class DB: def __init__(self,dbname="bots.sqlite"): self.dbname = dbname self.conn = sqlite3.connect(dbname) def setup(self): cmd = "CREATE TABLE IF NOT EXISTS items (description text)" self.conn.execute(cmd) self.conn.commit() def add_item(self,item_name): cmd = "INSERT INTO items (description) VALUES (?)" arg = (item_name, ) self.conn.execute(cmd,arg) self.conn.commit() def delete_item(self,item_name): cmd ="DELETE FROM items WHERE description= (?)" arg = (item_name, ) self.conn.execute(cmd,arg) self.conn.commit() def delete_all(self): cmd="DELETE FROM items WHERE description > -1;" self.conn.execute(cmd) self.conn.commit() def items_list(self): cmd = "SELECT description FROM items" return [x[0] for x in self.conn.execute(cmd)]
#PDF excerpt tool #initialize the environment import os import sys import string import importlib #GUI interface class import tkinter import tkinter.messagebox from tkinter import * #import word document #pip3 install python-docx to install (python-docx is compatible to Python3.x) from docx import Document def main(): results = '/tmp/PDFresults.docx' outputs = '/tmp/PDFexcerption.docx' PDFfile_loc = PDFfile_input('PDF file location:') #parse PDF to word document parsePDF(PDFfile_loc, results) #Excerpt WORD with specified pattern, e.g. RL. RC. for this example ExcerptPDF(results, outputs) #Excerpt WORD with specified pattern. def ExcerptPDF(para_results,para_outputs): word_doc = Document(para_results) #create an empty WORD document outputs_doc = Document() #count the # of rules RL_counter = 0 RC_counter = 0 for paragraph in word_doc.paragraphs: if 'RL.' in paragraph.text: RL_counter += 1 outputs_doc.add_paragraph(paragraph.text) else: if 'RC.' in paragraph.text: RC_counter += 1 outputs_doc.add_paragraph(paragraph.text) outputs_doc.add_paragraph('RL Count:' + str(RL_counter)) outputs_doc.add_paragraph('RC Count:' + str(RC_counter)) outputs_doc.save(para_outputs) #code to store into TXT format counter = [0,0,0,0,0,0] RL_textstringShall = '' RL_textstringMust = '' RL_textstringOther = '' RC_textstringShould = '' RC_textstringShouldNot = '' RC_textstringOther = '' for paragraph in word_doc.paragraphs: if 'RL.' in paragraph.text: if 'shall be ' in paragraph.text: # counting RL-> 'shall be' items counter[0] += 1 RL_textstringShall = RL_textstringShall + '\n' + paragraph.text else: if 'must not be' in paragraph.text: # counting RL -> 'must not be downrated' items counter[1] += 1 RL_textstringMust = RL_textstringMust + '\n' + paragraph.text else: # counting RL -> other items counter[2] += 1 RL_textstringOther = RL_textstringOther + '\n' + paragraph.text if 'RC.' in paragraph.text: if 'should be' in paragraph.text: # counting RC -> 'should be' items counter[3] += 1 RC_textstringShould = RC_textstringShould + '\n' + paragraph.text else: if 'should not be' in paragraph.text: # counting RC -> 'should not be' items counter[4] += 1 RC_textstringShouldNot = RC_textstringShouldNot + '\n' + paragraph.text else: # counting RC -> 'should not be' items counter[5] += 1 RC_textstringOther = RC_textstringOther + '\n' + paragraph.text #store the results into a TxT file with open(para_outputs[:-5]+'.txt', 'a+') as fw: fw.write(RL_textstringMust) fw.write(RL_textstringShall) fw.write(RL_textstringOther) fw.write(RC_textstringShould) fw.write(RC_textstringShouldNot) fw.write(RC_textstringOther) fw.write('\nRL-shall counting:' + str(counter[0]) + '\n') fw.write('RL-must not counting:' + str(counter[1]) + '\n') fw.write('RL-other counting:' + str(counter[2]) + '\n') fw.write('RC-should counting:' + str(counter[3]) + '\n') fw.write('RC-should not counting:' + str(counter[4]) + '\n') fw.write('RC-other counting:' + str(counter[5]) + '\n') fw.close() #Interpret PDF file and store into Text file def parsePDF(para_PDFfile_loc, para_results): import pdfminer from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfparser import PDFParser from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import PDFPageAggregator from pdfminer.layout import LTTextBoxHorizontal, LAParams from pdfminer.pdfpage import PDFTextExtractionNotAllowed, PDFPage fp = open(para_PDFfile_loc, 'rb') # PDF parser instance parser = PDFParser(fp) doc = PDFDocument(parser) # not judget whether PDF is extractable or not since doc.is_extractable is justing checking that special tag # instead of checking the actual extractable status # if not doc.is_extractable: # raise PDFTextExtractionNotAllowed # PDF resource manager resmgr = PDFResourceManager() # PDF Device laparams = LAParams() device = PDFPageAggregator(resmgr, laparams=laparams) # PDF page interpreter interpreter = PDFPageInterpreter(resmgr, device) #create an empty word document structure word_doc = Document() # go throu all pages # doc.get_pages() to pages for page in PDFPage.create_pages(doc): interpreter.process_page(page) layout = device.get_result() # 这里layout是一个LTPage对象 里面存放着 这个page解析出的各种对象 # 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等 # 想要获取文本就获得对象的text属性, for x in layout: if (isinstance(x, LTTextBoxHorizontal)): TXTinfo = x.get_text() word_doc.add_paragraph(TXTinfo) word_doc.save(para_results) # GUI input to get the file to be interpreted def PDFfile_input(para_promptinfo): # Define termination function def return_callback(event): topwindow.quit() # Define close function for no input def close_callback(): tkinter.messagebox.showinfo('message', 'No Input') # Terminate process topwindow.destroy() sys.exit() topwindow = tkinter.Tk() topwindow.title("PDF File Location") input_label = tkinter.Label(topwindow, text = para_promptinfo) input_label.pack(side = LEFT) input_entry = tkinter.Entry(topwindow, bd=5) input_entry.pack(side = RIGHT) # Bind "Return" keyinput with Entry box input_entry.bind('<Return>', return_callback) # Define window close event topwindow.protocol("WM_DELETE_WINDOW", close_callback) topwindow.mainloop() # Get window input on URL to be grapped PDF_file = tkinter.Entry.get(input_entry) #topwindow.destroy() #hide the input window #used specially for while-loop in case wrong value input topwindow.withdraw() return PDF_file if __name__ == "__main__": main()
from turtle import * import turtle t=turtle.Turtle() def jump(distanz, winkel=0): global number t.penup() t.right(winkel) t.forward(distanz) t.left(winkel) t.pendown() t.pensize(7) rad=100 abc=19 bcd=19 number=1 for j in range(10): for i in range(abc): jump(rad) t.write(str(number),align="center") jump(-rad) t.rt(bcd) number=number+1 rad=rad-10 abc=abc-2 bcd=bcd+2 number turtle.ht()
from math import * from matplotlib import pyplot from numpy import arange ''' A sphere area in dimension D can be found by formula [\ V_{r} = K_{D}*r^{D} \] We will find the ratio between the region r = 1 and r = 1 - \epsilon [\ Ratio = (V_{1} - V{1-\epsilon} ) / V_{1} \] -----> Asses for values of D and Epslon It becomes [\ Ratio = 1-(1-\epsilon)^{D} \] ''' def iterEpsilons(D): x = [] y = [] ratio = lambda e: 1-(1-e)**D for i in arange(0,1.01, 0.01 ): x.append(i) y.append(ratio(i)) pyplot.plot(x,y) def main(): for i in range(100): iterEpsilons(i) pyplot.show() main()
#2 def cube(num): return num * num * num def avg(a,b,c,d): return (a + b + c + d) / 4 def triplicate(text): return text + text + text def multiplicate(text,number): return text * number #3 def extract_root(a,b,c): a = int(str(a)) b = int(str(b)) c = int(str(c)) y1 = (- b + (b ** 2 - 4 * a * c) ** (1/2)) / (2 * a) y2 = (- b - (b ** 2 - 4 * a * c) ** (1/2)) / (2 * a) return "the solutions is" + str(y1) + "," + str(y2)
#1. class Block: """have attributes to store the coordinates of the center of the Block and for the width and height of the Block. Attributes: center(tup of num),width(num),height(num)""" #2. def __init__(self,center,width,height): """take a pair* of coordinates (for the center), along with the width and height Block,tup,num,num -> None""" self.center = center self.width = width self.height = height #3. def get_corner(self,corner): """takes a string representing which corner returns a pair* representing the coordinates of that corner. Block,str -> tup""" if corner == "SW": return (self.center[0]-self.width/2,self.center[1]-self.height/2) elif corner == "SE": return (self.center[0]-self.width/2,self.center[1]+self.height/2) elif corner == "NE": return (self.center[0]+self.width/2,self.center[1]+self.height/2) elif corner == "NW": return (self.center[0]+self.width/2,self.center[1]-self.height/2) #4. def get_width(self): """return the width of block Block -> num""" return self.width def get_height(self): """return the width of block Block -> num""" return self.height #5. def get_center(self): """return the center of Block Block -> tup""" return self.center #6. def __repr__(self): """return a string of the format "Block((SW-corner-x, SW-corner-y), (NE-corner-x, NE-corner-y))" Block -> str""" return "Block((" + repr(self.center[0]-self.width/2) + ", " +\ repr(self.center[1]-self.height/2) + "),(" + repr(self.center[0]+self.width/2) +\ ", " + repr(self.center[1]+self.height/2) + "))" #7. def move(self,move_right,move_up): """that takes two numbers representing the distance to move Block,num,num -> None""" self.center = (self.center[0]+move_right,self.center[1]+move_up) #8. def set_size(self,new_width,new_height): """takes two numbers representing a new width and a new height and resizes the Block accordingly. Block,num,num -> None""" self.width = new_width self.height = new_height print("Creating block1 with center (5,10), width 4, and height 2...") block1 = Block((5,10),4,2) print("block1 is now: " + repr(block1) + "\n") print("The lower-left corner of block1 is at " \ + str(block1.get_corner("SW"))) print("The upper-right corner of block1 is at " \ + str(block1.get_corner("NE"))) print("The width of block1 is " + str(block1.get_width())) print("The height of block1 is " + str(block1.get_height()) + "\n") print("Moving block1 5 units to the right...") block1.move(5,0) print("block1 is now: " + repr(block1)) print("block1 should still have the same height and width...") print("The width of block1 is " + str(block1.get_width())) print("The height of block1 is " + str(block1.get_height()) + "\n") print("I'm about to change the size of block1.") print("Before the change, the center is at " + str(block1.get_center())) print("Now, I'm changing the width to 10 and the height to 20.") block1.set_size(10,20) print("The width of block1 is now " + str(block1.get_width())) print("The height of block1 is now " + str(block1.get_height())) print("The center should not have changed.") print("The center of block1 is now " + str(block1.get_center()) + "\n")
print('My name is Wu Shenyuan') print("I like to playing computer games") print("""Such as Dota2, starcraft and warcraft""") print("The \nmost I"+" "+'like for this three is'+" "+"""Dota2""") print('"It is "'),print("'interesting'")
#2. def factorial(x): """takes a natural number and returns the product of all the natural numbers from 1 up to the given number. natural num -> num""" if x == 0: return 0 elif x == 1 : return 1 else: return x * factorial(x-1) #3. def power_of_two(x): """takes a natural number n and returns 2^n natural num -> num""" if x == 0: return 1 elif x == 1 : return 2 else: return 2 * power_of_two(x-1) #4. def power(b,n): """takes a natural number n and returns b^n natural num -> num""" if b == 0: return 0 else: if n == 0: return 0 elif n == 1 : return b else: return b * power(b,n-1) #5. #A Binary Number Tree (BNT) is one of: # - 1 # - ((1,(2,3)),4) #A Binary Number Tree (BNT) is one of: # - 2 # - (4,(1,(3,2))) #A Binary Number Tree (BNT) is one of: # - 3 # - (1,(2,(3,4))) #7. def add_leaves(tree): """returns the sum of the number of leaves in tree BNT -> int""" if isinstance(tree,tuple): return add_leaves(tree[0]) + add_leaves(tree[1]) else: return tree
#1. class Thing: """representing physical objects in the game Attribute: name(str),location(str)""" def __init__(self,name,location): """take the name of object and the location of object Thing,str,str -> None""" self.name = name self.location = location def __repr__(self): """repersent the string og the name and location Thing -> str""" return "Thing(" + repr(self.name) + ", " + repr(self.location) \ + ")" def description(self): """return a string that describes the object Thing -> str""" return "The " + self.name + " is " + self.location + "." #2. class Openable(Thing): """representing those physical objects that can be opened. Attribute:is_open(boolean)""" def __init__(self,name,location,is_open = False): """take the name of object and the location of object and use is_open to represents whether or not the object is open Openable,str,str,bool -> None""" super().__init__(name,location) self.is_open = is_open def description(self): """return a string that shows the name location is open or close Openable -> str""" super().description() if self.is_open == False: return "The " + self.name + " " + self.location + " is closed." elif self.is_open == True: return "The " + self.name + " " + self.location + " is open." def try_open(self): """open the thing are close and return True and let open object still be open and return False Openable -> bool""" if self.is_open == False: self.is_open = True return True elif self.is_open == True: return False #3. class Lockable(Openable): """representing physical objects that can be unlocked and opened. Attribute:key:(str),is_locked:(bool)""" def __init__(self,name,location,key,is_open=False,is_locked=False): """take the name of object and the location of object and use is_open to represents whether or not the object is open and a key, and check if the key can unlocked it Lockable,str,str,str,bool,bool""" super().__init__(name,location,is_open = False) self.key = key self.is_locked = is_locked def description(self): """return a string that shows the name location is open or close and locked or unlocked Openable -> str""" super().description() if self.is_open == False: if self.is_locked == False: return "The " + self.name + " " + self.location + \ "is closed but unlocked." elif self.is_locked == True: return "The " + self.name + " " + self.location + \ "is locked." elif self.is_open == True: return "The " + self.name + " " + self.location + " is open." def try_open(self): """unlocked the thing are close and return True and originally locked or if it was already open return False Openable -> bool""" if self.is_open == False: if self.is_locked == False: self.is_open = True return True else: return False def try_unlock_with(self,Thing_key): """checkif the key can unlocked the door is_Locked,str -> bool""" if self.is_open == True: return False elif self.is_open == False: if self.is_locked == True: if Thing_key == self.key: self.is_locked = False return True else: return False else: return False
def make_counter(): """Return a counter function. >>> c = make_counter() >>> c('a') 1 >>> c('a') 2 >>> c('b') 1 >>> c('a') 3 >>> c2 = make_counter() >>> c2('b') 1 >>> c2('b') 2 >>> c('b') + c2('b') 5 """ "*** YOUR CODE HERE ***" record={} def counter(s): if not s in record: record[s]=1 else: record[s] +=1 return record[s] return counter def make_fib(): """Returns a function that returns the next Fibonacci number every time it is called. >>> fib = make_fib() >>> fib() 0 >>> fib() 1 >>> fib() 1 >>> fib() 2 >>> fib() 3 >>> fib2 = make_fib() >>> fib() + sum([fib2() for _ in range(5)]) 12 """ "*** YOUR CODE HERE ***" prev=1 curr=0 def fib(): nonlocal prev, curr prev, curr = curr, prev+curr return prev return fib def make_withdraw(balance, password): """Return a password-protected withdraw function. >>> w = make_withdraw(100, 'hax0r') >>> w(25, 'hax0r') 75 >>> error = w(90, 'hax0r') >>> error 'Insufficient funds' >>> error = w(25, 'hwat') >>> error 'Incorrect password' >>> new_bal = w(25, 'hax0r') >>> new_bal 50 >>> w(75, 'a') 'Incorrect password' >>> w(10, 'hax0r') 40 >>> w(20, 'n00b') 'Incorrect password' >>> w(10, 'hax0r') "Your account is locked. Attempts: ['hwat', 'a', 'n00b']" >>> w(10, 'l33t') "Your account is locked. Attempts: ['hwat', 'a', 'n00b']" >>> type(w(10, 'l33t')) == str True """ "*** YOUR CODE HERE ***" # Can use str(list) record=[] def withdraw(amount, password_user): nonlocal balance, record if len(record) >= 3: return "Your account is locked. Attempts: " +str(record) elif password == password_user: if amount> balance: return "Insufficient funds" balance= balance-amount return balance else: record.append(password_user) return "Incorrect password" return withdraw def make_joint(withdraw, old_password, new_password): """Return a password-protected withdraw function that has joint access to the balance of withdraw. >>> w = make_withdraw(100, 'hax0r') >>> w(25, 'hax0r') 75 >>> make_joint(w, 'my', 'secret') 'Incorrect password' >>> j = make_joint(w, 'hax0r', 'secret') >>> w(25, 'secret') 'Incorrect password' >>> j(25, 'secret') 50 >>> j(25, 'hax0r') 25 >>> j(100, 'secret') 'Insufficient funds' >>> j2 = make_joint(j, 'secret', 'code') >>> j2(5, 'code') 20 >>> j2(5, 'secret') 15 >>> j2(5, 'hax0r') 10 >>> j2(25, 'password') 'Incorrect password' >>> j2(5, 'secret') "Your account is locked. Attempts: ['my', 'secret', 'password']" >>> j(5, 'secret') "Your account is locked. Attempts: ['my', 'secret', 'password']" >>> w(5, 'hax0r') "Your account is locked. Attempts: ['my', 'secret', 'password']" >>> make_joint(w, 'hax0r', 'hello') "Your account is locked. Attempts: ['my', 'secret', 'password']" """ "*** YOUR CODE HERE ***" #The importance of resassigning variabels when dealing with lists, excuting the same function twice would lead to repeated values in the list result=withdraw(0, old_password) if type(result)== str: return result def new_withdraw(amount, password_entered): if password_entered == old_password or password_entered ==new_password: return withdraw(amount, old_password) else: return withdraw(amount, password_entered) return new_withdraw def preorder(t): """Return a list of the entries in this tree in the order that they would be visited by a preorder traversal (see problem description). >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])]) >>> preorder(numbers) [1, 2, 3, 4, 5, 6, 7] >>> preorder(tree(2, [tree(4, [tree(6)])])) [2, 4, 6] """ "*** YOUR CODE HERE ***" result=[] result.append(label(t)) for b in branches(t): result.extend(preorder(b)) return result class Mint: """A mint creates coins by stamping on years. The update method sets the mint's stamp to Mint.current_year. >>> mint = Mint() >>> mint.year 2017 >>> dime = mint.create(Dime) >>> dime.year 2017 >>> Mint.current_year = 2100 # Time passes >>> nickel = mint.create(Nickel) >>> nickel.year # The mint has not updated its stamp yet 2017 >>> nickel.worth() # 5 cents + (83 - 50 years) 38 >>> mint.update() # The mint's year is updated to 2100 >>> Mint.current_year = 2175 # More time passes >>> mint.create(Dime).worth() # 10 cents + (75 - 50 years) 35 >>> Mint().create(Dime).worth() # A new mint has the current year 10 >>> dime.worth() # 10 cents + (160 - 50 years) 118 >>> Dime.cents = 20 # Upgrade all dimes! >>> dime.worth() # 20 cents + (160 - 50 years) 128 """ current_year = 2017 def __init__(self): self.update() def create(self, kind): "*** YOUR CODE HERE ***" return kind(self.year) def update(self): "*** YOUR CODE HERE ***" self.year= Mint.current_year class Coin: def __init__(self, year): self.year = year def worth(self): "*** YOUR CODE HERE ***" if Mint.current_year-self.year> 50: return self.cents + Mint.current_year-self.year-50 else: return self.cents class Nickel(Coin): cents = 5 class Dime(Coin): cents = 10 ## Tree ADT ## def tree(label, branches=[]): """Construct a tree with the given label value and a list of branches.""" for branch in branches: assert is_tree(branch), 'branches must be trees' return [label] + list(branches) def label(tree): """Return the label value of a tree.""" return tree[0] def branches(tree): """Return the list of branches of the given tree.""" return tree[1:] def is_tree(tree): """Returns True if the given tree is a tree, and False otherwise.""" if type(tree) != list or len(tree) < 1: return False for branch in branches(tree): if not is_tree(branch): return False return True def is_leaf(tree): """Returns True if the given tree's list of branches is empty, and False otherwise. """ return not branches(tree) def print_tree(t, indent=0): """Print a representation of this tree in which each node is indented by two spaces times its depth from the root. >>> print_tree(tree(1)) 1 >>> print_tree(tree(1, [tree(2)])) 1 2 >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])]) >>> print_tree(numbers) 1 2 3 4 5 6 7 """ print(' ' * indent + str(label(t))) for b in branches(t): print_tree(b, indent + 1) def copy_tree(t): """Returns a copy of t. Only for testing purposes. >>> t = tree(5) >>> copy = copy_tree(t) >>> t = tree(6) >>> print_tree(copy) 5 """ return tree(label(t), [copy_tree(b) for b in branches(t)])
from criandoListaTxtDesejos.interface.produto import * from criandoListaTxtDesejos.interface.efeito import * arq = 'Lista_de_desejo.txt' if not existeArqu(arq): criarArquivo(arq) while True: linha2() choice = lista(['Ler Lista de Desejos',"Adicionar item a Lista de desejos",'Fechar programa']) if choice == 1: titulo('---Ler Lista de Aqruivos---') lerArqui(arq) elif choice == 2: titulo('---Adicionar item a Lista---') produto = str(input('Digite o produto: ')) preco = testInt("Digite o preço: ") desconto = testInt("Qual o percentual do desconto[%]: ") precDesconto = preco-(preco*(desconto/100)) escrever(arq, produto,preco,desconto,precDesconto) elif choice == 3: titulo('---Fechando Programa---') break else: print('Digite uma opção valida') sleep(1) print('FIM DO PROGRAMA')
import time import threading import random from pynput.mouse import Button, Controller from pynput.keyboard import Listener, KeyCode print("Welcome. This auto-clicker uses variance to click randomly within a certain specified time period.") print("The variance is used in such a way that the time between clicks is set to a minimum and then randomly picked for a maximum within set parameters by the user.") print("") print("") print("To start the autoclicker once you have set your parameters, click the '[' character.") print("To stop, simply click the ']' character.") print("") print("") c = float(input("How many seconds (minimum) in between clicks: ")) print("The way this program uses variance in your auto-clicking is by using a normal bell curve centered at 0.") print("The variance number you input is the standard deviation from 0. \nInputting variables higher than recommended can lead to exponential increases in varied click times.") print("For instance, if you used a variance of 7, the numbers range anywhere from 'your preferred clicking speed' to 'your preferred speed + 14 seconds'.") print("") print("") b = float(input("Please state your random variance for the varied clicking. \nI would this at around 1.8 (Warning - Going above 2 can create long variations) unless you know how standard deviation works. At 1.8, \nyou get around a 1-2 second ramdonmized delay after your minimum click time.: ")) delay = c button = Button.left start_stop_key = KeyCode(char='[') exit_key = KeyCode(char=']') class ClickMouse(threading.Thread): def __init__(self, delay, button): super(ClickMouse, self).__init__() self.delay = delay self.button = button self.running = False self.program_running = True def start_clicking(self): self.running = True def stop_clicking(self): self.running = False def exit(self): self.stop_clicking() self.program_running = False def run(self): while self.program_running: while self.running: mouse.click(self.button) time.sleep((self.delay) + abs(random.normalvariate(0,b))) time.sleep(1) mouse = Controller() click_thread = ClickMouse(delay, button) click_thread.start() def on_press(key): if key == start_stop_key: if click_thread.running: click_thread.stop_clicking() else: click_thread.start_clicking() elif key == exit_key: click_thread.exit() listener.stop() with Listener(on_press=on_press) as listener: listener.join() input('Thank you! Press ENTER to exit.') import sys sys.exit()
def movies(): age=input("Enter age (child, middle school, high school, or other): ") weather=input("Enter weather(rainy, sunny, hailing, snowing, or other): ") if age=="child": if weather=="sunny": print("Pay $2.") elif weather=="snowing": print("Pay $1.50.") else: print("You're in for free!") elif age=="middle school": if weather=="rainy": print("Pay $3.") elif weather=="sunny": print("Pay $7.") elif weather=="snowing": print("Pay $6.50.") elif weather=="hailing": print("You're in for free!") else: print("Pay $5.") elif age=="high school": if weather=="rainy": print("Pay $5.") elif weather=="sunny": print("Pay $9.") elif weather=="snowing": print("Pay $8.50.") elif weather=="hailing": print("You're in for free!") else: print("Pay $7.") else: if weather=="sunny": print("Pay $10.") elif weather=="rainy": print("Pay $14.") elif weather=="snowing": print("Pay #13.50.") elif weather=="hailing": print("You're in for free!") else: print("Pay $12.") print("Thanks for coming to the movies!") movies()
from collections import Counter import nltk UPPERCASE_LETTERS = [chr(i) for i in range(65, 91)] LOWERCASE_LETTERS = [chr(i) for i in range(97, 123)] LETTERS = UPPERCASE_LETTERS + LOWERCASE_LETTERS STOP_WORDS = Counter(nltk.corpus.stopwords.words('english')) if __name__ == '__main__': print("is" in STOP_WORDS) print("as" in STOP_WORDS) print("was" in STOP_WORDS)
def isWordGuessed(secretWord, lettersGuessed): tester=0 for letterS in secretWord: if letterS in lettersGuessed: tester+=1 else: return False return True def getAvailableLetters(lettersGuessed): list="" import string availableL=string.ascii_lowercase for availL in availableL: if availL not in lettersGuessed: list= list+ availL return (list) def Hangaroo(secretWord): import string availableL=string.ascii_lowercase lettersGuessed = [] list(lettersGuessed) mistakesMade = 0 secretWord=secretWord.lower() print("Let's Play Hangaroo!") print("The word is " + str(len(secretWord)) + " letters long.") print("You have made",mistakesMade,"mistakes!") print(getGuessedWord(secretWord,lettersGuessed)) while mistakesMade < 1000000000: if isWordGuessed(secretWord, lettersGuessed): return print("Awesome! You got the word right!") print("Available letters: ") print(getAvailableLetters(lettersGuessed)) guess = input("Type a letter to guess the word: ") guess = guess.lower() if guess not in lettersGuessed: lettersGuessed.append(guess) if guess in secretWord: print("You got a letter right! Way to go!") print(getGuessedWord(secretWord, lettersGuessed)) else: mistakesMade += 1 print("Nope!Try again!") print("You have made",mistakesMade,"mistakes!") print(getGuessedWord(secretWord, lettersGuessed)) else: print("You already tried that letter!") print(getGuessedWord(secretWord, lettersGuessed)) return print("Try Again! You have unlimited tries!")
import pyCardDeck from random import randint import os import time """<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>""" class Player: def __init__(self, name, is_computer): self.name = name self.cards = [] self.is_computer = is_computer self.uno = False def __repr__(self): return "Player: " + self.name def print_cards(self): for i in range(len(self.cards)): print(i + 1) print(self.cards[i]) """<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>""" class Card: def __init__(self, value, color): self.value = value # 0-9 OR "plus4 ", "plus2 ", "skip ", "reverse", "wild " self.color = color # "yellow ", "red ", "green ", "blue ", "choose " self.played = False def is_valid_play(self, discarded): if (discarded.value == "plus2 " or discarded.value == "plus4 ") and discarded.played == False: if self.value == discarded.value: return True else: return False elif self.color == discarded.color or self.value == discarded.value or self.value == "plus4 " or self.value == "wild ": return True else: return False def is_adder(self): if self.value == "plus2 " or self.value == "plus4 ": return True return False def __repr__(self): """ Example: ========= |yellow | |6 | ========= """ val_str = "" if isinstance(self.value, int): val_str = str(self.value) + " " else: val_str = self.value return '=========\n|%s|\n|%s|\n=========\n' % (self.color, val_str) """<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>""" class Game: def __init__(self, players, deck): self.players = players self.deck = pyCardDeck.Deck(deck) self.deck.shuffle() self.deal_cards() top_card = self.deck.draw() if top_card.color == "choose ": top_card.color = "red " #for simplicity, completely arbitrary self.discard = top_card self.plus_cards = 0 self.discarded = [] def deal_cards(self): for card in range(7): for player in self.players: player.cards.append(self.deck.draw()) def take_turn(self): if self.deck.cards_left < 10: self.deck = pyCardDeck.Deck(discarded).shuffle() self.discarded = [] print("\nDISCARD PILE") print(self.discard) time.sleep(2) colors = ["red ", "yellow ", "green ", "blue "] player = self.players[0] valid_plays = [card for card in player.cards if Card.is_valid_play(card, self.discard)] if valid_plays == []: card_drawn = self.deck.draw() print(player.name + " drew a card.\n") time.sleep(1) if Card.is_valid_play(card_drawn, self.discard): player.cards.append(card_drawn) valid_plays.append(card_drawn) else: if Card.is_adder(self.discard): self.discard.played = True for _ in range(self.plus_cards): player.cards.append(self.deck.draw()) if self.plus_cards > 0: print(player.name + " had to draw " + str(self.plus_cards) + " cards!") time.sleep(2) self.plus_cards = 0 self.shift_players() return if player.is_computer: card = valid_plays[randint(0, len(valid_plays) - 1)] if card.color == "choose ": card.color = colors[randint(0, 3)] else: print("\nYOUR HAND") Player.print_cards(player) index = input("\nPlay a card by typing a number between 1 and the number of cards in your hand: ").strip() while not isinstance(int(index), int): index = input("\nThat wasn't a valid number. Try again: ").strip() index = int(index) - 1 card = player.cards[index] while card not in valid_plays: index = int((input("\nSorry, that's not a valid play. Try again: ")).strip()) - 1 card = player.cards[index] if card.color == "choose ": print("What's the next color?") letter = (input("Type r for red, y for yellow, g for green, or b for blue: ")).strip() for color in colors: if letter == color[0]: # "red ", "yellow ", "blue ", "green " card.color = color if Card.is_adder(card): for i in range(int(card.value[4])): # "plus2 " or "plus4 " at index 4 gives num of cards self.plus_cards += 1 print("\n" + player.name + " played a " + "\n") print(card) self.discarded.append(self.discard) self.discard = card player.cards.remove(card) self.effect() def effect(self): if self.discard.value == "reverse": self.players = self.players[::-1] print("\nREVERSED!\n") elif self.discard.value == "skip ": print("\n" + self.players[1].name + " has been skipped!\n") self.shift_players() self.shift_players() else: self.shift_players() time.sleep(3) def shift_players(self): p = self.players p[0], p[1], p[2], p[3] = p[1], p[2], p[3], p[0] self.players = p def uno_or_over(self): for player in self.players: if len(player.cards) == 0: print("\nCongratulations, " + player.name + " you win!\n") time.sleep(1) return True elif len(player.cards) == 1: if player.uno == False: print(player.name + " has an UNO!") player.uno = True time.sleep(1) else: player.uno = False return False """<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>""" # deck is the same initially every time, so it # didn't make sense to me to take a class-based approach. def deck(): my_deck = [] colors = ["red ", "yellow ", "green ", "blue "] values = [1, 2, 3, 4, 5, 6, 7, 8, 9, "skip ", "reverse", "plus2 "] for color in colors: my_deck.append(Card(0, color)) for value in values: my_deck.append(Card(value, color)) my_deck.append(Card(value, color)) for num in range(4): my_deck.append(Card("plus4 ", "choose ")) my_deck.append(Card("wild ", "choose ")) return my_deck def play_again(): again = input("Wanna play again? y/n ") os.system('cls' if os.name == 'nt' else 'clear') if again == "y": play_game() return """<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>""" def play_game(): os.system('cls' if os.name == 'nt' else 'clear') print("\nWelcome to the game of UNO!\n") option = input("\nType ONE to play against 3 computers,\nTWO to play with 2-4 people,\nor THREE to watch 4 computers play. ") while option != "ONE" and option != "TWO" and option != "THREE": option = input("\nType ONE to play against 3 computers\nor TWO to play with 2-4 people. ") if option == "ONE": name = input("\nWhat's your name, Player 1? ") game = Game([Player(name, False), Player("computer1", True), Player("computer2", True), Player("computer3", True)], deck()) elif option == "TWO": num_players = int(input("\nHow many people (including you) will be playing? ").strip()) count = 0 players = [] while count < num_players: name = input("\nWhat's your name, Player " + str(count + 1) + "? ") players.append(Player(name, False)) count += 1 comp_count = 1 while num_players != 4: players.append(Player("computer" + str(comp_count), True)) num_players += 1 comp_count += 1 game = Game(players, deck()) else: players = [] for i in range(4): players.append(Player("computer" + str(i+1), True)) game = Game(players, deck()) while not game.uno_or_over(): os.system('cls' if os.name == 'nt' else 'clear') print("\n") if game.players[0].is_computer: print(game.players[0].name + " is playing now...") time.sleep(1) else: input("It's your turn, " + game.players[0].name + ". Press any key to start. ") game.take_turn() play_again() play_game()
import threading ''' This class reverses each word it receives and appends it to sentence ''' class ReverseStrThread(threading.Thread): def __init__(self, word): if type(word) is not str: raise Exception("word is not a string") self.word = word threading.Thread.__init__(self) sentence = " " def run(self): ReverseStrThread.sentence += self.word[::-1] + " "
""" --- Day 7: The Sum of Its Parts --- You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed ashore. It's quite cold out, so you decide to risk creating a paradox by asking them for directions. "Oh, are you the search party?" Somehow, you can understand whatever Elves from the year 1018 speak; you assume it's Ancient Nordic Elvish. Could the device on your wrist also be a translator? "Those clothes don't look very warm; take this." They hand you a heavy coat. "We do need to find our way back to the North Pole, but we have higher priorities at the moment. You see, believe it or not, this box contains something that will solve all of Santa's transportation problems - at least, that's what it looks like from the pictures in the instructions." It doesn't seem like they can read whatever language it's in, but you can: "Sleigh kit. Some assembly required." "'Sleigh'? What a wonderful name! You must help us assemble this 'sleigh' at once!" They start excitedly pulling more parts out of the box. The instructions specify a series of steps and requirements about which steps must be finished before others can begin (your puzzle input). Each step is designated by a single letter. For example, suppose you have the following instructions: Step C must be finished before step A can begin. Step C must be finished before step F can begin. Step A must be finished before step B can begin. Step A must be finished before step D can begin. Step B must be finished before step E can begin. Step D must be finished before step E can begin. Step F must be finished before step E can begin. Visually, these requirements look like this: -->A--->B-- / \ \ C -->D----->E \ / ---->F----- Your first goal is to determine the order in which the steps should be completed. If more than one step is ready, choose the step which is first alphabetically. In this example, the steps would be completed as follows: Only C is available, and so it is done first. Next, both A and F are available. A is first alphabetically, so it is done next. Then, even though F was available earlier, steps B and D are now also available, and B is the first alphabetically of the three. After that, only D and F are available. E is not available because only some of its prerequisites are complete. Therefore, D is completed next. F is the only choice, so it is done next. Finally, E is completed. So, in this example, the correct order is CABDFE. In what order should the steps in your instructions be completed? Your puzzle answer was PFKQWJSVUXEMNIHGTYDOZACRLB. --- Part Two --- As you're about to begin construction, four of the Elves offer to help. "The sun will set soon; it'll go faster if we work together." Now, you need to account for multiple people working on steps simultaneously. If multiple steps are available, workers should still begin them in alphabetical order. Each step takes 60 seconds plus an amount corresponding to its letter: A=1, B=2, C=3, and so on. So, step A takes 60+1=61 seconds, while step Z takes 60+26=86 seconds. No time is required between steps. To simplify things for the example, however, suppose you only have help from one Elf (a total of two workers) and that each step takes 60 fewer seconds (so that step A takes 1 second and step Z takes 26 seconds). Then, using the same instructions as above, this is how each second would be spent: Second Worker 1 Worker 2 Done 0 C . 1 C . 2 C . 3 A F C 4 B F CA 5 B F CA 6 D F CAB 7 D F CAB 8 D F CAB 9 D . CABF 10 E . CABFD 11 E . CABFD 12 E . CABFD 13 E . CABFD 14 E . CABFD 15 . . CABFDE Each row represents one second of time. The Second column identifies how many seconds have passed as of the beginning of that second. Each worker column shows the step that worker is currently doing (or . if they are idle). The Done column shows completed steps. Note that the order of the steps has changed; this is because steps now take time to finish and multiple workers can begin multiple steps simultaneously. In this example, it would take 15 seconds for two workers to complete these steps. With 5 workers and the 60+ second step durations described above, how long will it take to complete all of the steps? Your puzzle answer was 864. """ def build_steps(puzzle_input): steps = set() pre_reqs = {} for line in puzzle_input: step_position_1 = line.find(" must") - 1 step_position_2 = line.find(" can ") - 1 step_1 = line[step_position_1:step_position_1 + 1] step_2 = line[step_position_2:step_position_2 + 1] steps.add(step_1) steps.add(step_2) if step_2 in pre_reqs: pre_reqs[step_2].append(step_1) else: pre_reqs[step_2] = [step_1] return steps, pre_reqs def part_one(puzzle_input): steps, pre_reqs = build_steps(puzzle_input) result = [] available_steps = set(steps - pre_reqs.keys()) while len(available_steps) > 0: available_steps = sorted(available_steps) this_step = available_steps[0] available_steps.remove(this_step) result.append(this_step) for step, pre_req in pre_reqs.items(): if this_step in pre_req: pre_req.remove(this_step) if len(pre_req) == 0: available_steps.append(step) return ''.join(result) def part_two(puzzle_input, worker_count, base_time): steps, pre_reqs = build_steps(puzzle_input) steps_to_finish = steps.copy() worker_next_available = [0 for _ in range(worker_count)] time = 0 in_progress_steps = {} available_steps = set(steps - pre_reqs.keys()) # We're checking off all the tasks in the input. while len(steps_to_finish) > 0: # Find a worker that is free for current_worker in range(worker_count): if worker_next_available[current_worker] <= time: # Is there work for this available worker? if len(available_steps) > 0: # Find the worker a task. Work out when it'll be finish available_steps = sorted(available_steps) this_step = available_steps[0] available_steps.remove(this_step) step_time = (ord(this_step) - ord('A') + 1 + base_time) step_finish = time + step_time worker_next_available[current_worker] = step_finish # Add this task to the list of tasks to check on over time. in_progress_steps[this_step] = step_finish time += 1 # Check to see if any running task has finished for this_step, end_time in in_progress_steps.items(): if time >= end_time: # So we're done with this step... remove it from the check list if this_step in steps_to_finish: steps_to_finish.remove(this_step) # Check the prereqs to see if this frees up another task for step, pre_req in pre_reqs.items(): if this_step in pre_req: pre_req.remove(this_step) if len(pre_req) == 0: available_steps.append(step) return max(worker_next_available) with open("Day7.txt") as file: file_text = file.readlines() test_data = [ 'Step C must be finished before step A can begin.', 'Step C must be finished before step F can begin.', 'Step A must be finished before step B can begin.', 'Step A must be finished before step D can begin.', 'Step B must be finished before step E can begin.', 'Step D must be finished before step E can begin.', 'Step F must be finished before step E can begin.' ] print(part_one(test_data)) print(part_one(file_text)) print(part_two(test_data, 2, 0)) print(part_two(file_text, 5, 60))
import cv2 import numpy as np img = cv2.imread("resources/Skullz.jpg") #grayscale # cv2.cvtColor(img Variable , color change ) -> convert color # in open cv its not rgb its bgr so we choose bgr2gray imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #blur # using the GaussianBlur .GaussianBlur(input_img, k_size , ) imgBlur = cv2.GaussianBlur(imgGray,(7,7),0) #edge detector #.Canny(img , threshold1 , threshold2) imgCanny = cv2.Canny(img,150,200) #dilation - sometimes edges are not joined completely , hence dilation # makes edges thicker # cv2.dilate(img_var, kernel, iteration) a kernel is a matrix # iteration helps to set edge width kernel = np.ones((5,5),np.uint8) imgDilation = cv2.dilate(imgCanny,kernel=kernel,iterations=1) # erosion - makes edges thinner imgEroded = cv2.erode(imgDilation,kernel=kernel,iterations=1) cv2.imshow("Erosion",imgEroded) cv2.waitKey(0)
# web scraping tutorial 1 # using beautiful soup 4 import bs4 as bs import urllib.request import re source = urllib.request.urlopen('https://pythonprogramming.net/parsememcparseface/').read() # gives the source code soup = bs.BeautifulSoup(source,'lxml') print(soup.title) print(soup.title.string) #print(soup.find_all('p')) #for para in soup.find_all('p'): # print(para.string) # string will work if you don't have child tags under it #print(soup.get_text()) pattern = re.compile('https:\W\W | http:\W\W') urlList = [] for url in soup.find_all('a'): match = pattern.match(str(url)) if(match): url.group() print(urlList)
class Item(object): def __init__(self,name,value,cost): self.name = name self.value = value self.cost = cost def getName(self): return self.name def getValue(self): return self.value def getCost(self): return self.cost def getDensity(self): return self.getValue()/self.getCost() def __str__(self): return ("Name: " + self.getName() + " Cost: " + str(self.getCost()) + " Value: " + str(self.getValue())) food = ["clock","painting","radio","vase","book","computer"] value = [175,90,20,50,10,200] weight = [10,9,4,2,1,20] def buildmenu(food,value,weight): menu = [] for i in range(len(food)): menu.append(Item(food[i],value[i],weight[i])) return menu items = buildmenu(food,value,weight) for item in items: print(item) def greedy(items, maxCost, keyfunction): sortitems = sorted(items, key = keyfunction, reverse=True) resultItems = [] totalValue = 0.0 totalCost = 0.0 for i in range(len(sortitems)): if sortitems[i].getCost() + totalCost <= maxCost: resultItems.append(sortitems[i]) totalCost += sortitems[i].getCost() totalValue += sortitems[i].getValue() else: break return (resultItems,totalValue) def testgreedy(items, constraint, functionkey): taken, val = greedy(items, constraint,functionkey) print("Total number of items : " + str(len(taken))) print("Maxvalue of items: " + str(val)) for item in taken: print(item) def testgreedys(items,maxUnits): print('Use greedy by Value to allocate ',str(maxUnits), ' weight') testgreedy(items,maxUnits,Item.getValue) print('Use greedy by Cost to allocate ',str(maxUnits),' weight') testgreedy(items,maxUnits, lambda x: 1/Item.getCost(x)) print("Use greedy by Density to allocate ", str(maxUnits), " weight") testgreedy(items,maxUnits,Item.getDensity) testgreedys(items,20)
#-*- coding:utf-8 -*- from os import path from wordcloud import WordCloud #脚本所在路径 d=path.dirname(__file__) #Read the whole text. text=open(path.join(d,'constitution.txt')).read() #Generate a word cloud image wordcloud=WordCloud().generate(text) #Display the generated image: #the matplotlib way: import matplotlib.pyplot as plt #Display an image on the axes plt.imshow(wordcloud) #Convenience method to get or set axis properties plt.axis("off") #lower max_font_size wordcloud=WordCloud(max_font_size=40).generate(text) #Creates a new figure plt.figure() plt.imshow(wordcloud) plt.axis("off") #Display a figure plt.show()