text
stringlengths
37
1.41M
#! /usr/bin/env python ''' visitor pattern creates new operations by adding new subclass to hierarchy, without altering base class. from GoF UML, concretVisitor class override Visitor Class operations to implement visitor-specific behaviors for the ConcretVisitable class, and once AbstractVisitable accept visitor, it sends an request to ConcretVisitor elements and encode visitor's code. ''' from abc import ABC, abstractmethod class AbstractVisitor(ABC): @abstractmethod def visit_Int(self): pass def visit_ConcretVisitableAdd(self): pass class ConcretVisitorA(AbstractVisitor): # each visit operation on Visitor declare its argument to be a particular ConcretElement def visit_Int(self, v): #v, a particular element from VistableElement return v.a def visit_ConcretVisitableAdd(self, v): return f'{self.__class__.__name__} add result is {v.a.accept(self) + v.b.accept(self)}' class ConcretVisitorB(AbstractVisitor): # visitable can accept different visitor datatype def visit_Int(self, v): return v.a def visit_ConcretVisitableAdd(self, v): return f'{self.__class__.__name__} add result is {v.a.accept(self) + v.b.accept(self) + int(10.00001)}' class ConcretVisitorC(AbstractVisitor): def visit_Int(self, v): return v.a def visit_ConcretVisitablePow(self, v): return f'{self.__class__.__name__} pow result is {v.a.accept(self) ** v.b.accept(self) }' #object structure (concept from GoF) class VisitableElement: # define an accept operation that take visitor as argument def accept(self, visitor): val = 'visit_{}'.format(self.__class__.__name__) visitorInstance = getattr(visitor, val) #getattr(object,'x')== object.x return visitorInstance(self) class Int(VisitableElement): def __init__(self, a): self.a = a class ConcretVisitableAdd(VisitableElement): def __init__(self, a, b): self.a = a self.b = b class ConcretVisitablePow(VisitableElement): def __init__(self, a, b): self.a = a self.b = b if __name__ == '__main__': output1 = ConcretVisitableAdd(Int(1),Int(2)).accept(ConcretVisitorA()) output2 = ConcretVisitableAdd(Int(1.5),Int(2)).accept(ConcretVisitorB()) output3 = ConcretVisitablePow(Int(1/2),Int(1/2)).accept(ConcretVisitorC()) list_ = [output1, output2, output3] for output in list_: print(output)
#! /usr/bin/env python # divide-conquer, merge sort complexity O(n lg n) def merge(lst1, lst2): result = list() i, j = 0, 0 while i <len(lst1) and j <len(lst2): if lst1[i] <= lst2[j]: result.append(lst1[i]) i += 1 else: result.append(lst2[j]) j += 1 result += lst1[i:] result += lst2[j:] return result def mergesort(lst): if len(lst) <= 1: return lst else: mid= int(len(lst)/2) # recursive lst1, lst2 = mergesort(lst[:mid]), mergesort(lst[mid:]) return merge(lst1, lst2) if __name__ == '__main__': lst = [4,2,10,1] print(mergesort(lst))
'''Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.''' a = input('Enter str: ') b = int(input('Enter num: ')) c = int(input('Enter another num: ')) print('Your line: {}\nYpur number: {}\nYour second number: {}'.format(a,b,c))
'''Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и через dict.''' def SeasonList(date): year = [('зима', 1, 2, 12), ('весна', 3, 4, 5), ('лето', 6, 7, 8), ('осень', 9, 10, 11)] for i in range(len(year)): if date in year[i]: return year[i][0] def SeasonDict(date): year = {1:'зима', 2:'зима', 12:'зима', 3:'весна', 4:'весна', 5:'весна', 6:'лето', 7:'лето', 8:'лето', 9:'осень', 10:'осень', 11:'осень'} return year[date] print(SeasonList(int(input()))) print(SeasonDict(int(input())))
'''6. Реализовать два небольших скрипта: а) итератор, генерирующий целые числа, начиная с указанного, б) итератор, повторяющий элементы некоторого списка, определенного заранее.''' from itertools import count, cycle def a(n: int): return count(n) def b(l: list): return cycle(l) def tester(): num = int(input()) for i in a(num): print(i, end = ' ') if i == num * 10: break print() l = input().split() loops = 0 for i in b(l): if i == l[-1]: loops += 1 if loops == 4: print(i, end = ' ') break print(i, end = ' ') tester()
#Printing positive numbers in a given range list1 = [12, -7, 5, 64, -14] print("List 1") for number in list1: if number > 0: print(number) print("\n") list2 = [12, 14, -95, 3] print("List 2") for number in list2: if number > 0: print(number)
# ========================================= # Передача функции в качестве аргумента # Функции - объекты первого порядка # ========================================= # Функции в python являются объектами первого класса (First Class Object). # Это означает, что с функциями вы можете работать, также как и с данными: # передавать их в качестве аргументов другим функциям, присваивать переменным # Обычная функция принимающая число и выводящая его значение на экран def f(value): print("value = ", value) # Вызов функции f(6) # В переменной func сохранены ссылка на объект-функцию func = f # Теперь через переменную func можно вызвать функцию f() func(10) def stars(func, val): print("***************") func(val) print("***************") # Мы можем передать одну функцию в качестве аргумента другой функциии вызвать ее внутри stars(f, 6)
#!/usr/bin/env python from operator import itemgetter from load_data import load # returns a 2-tuple of the similarity between two users # first element is the scoring difference, where 0 is identical and a positive # score is a sum-squared difference; if nothing in common, None # second element is the number of items in common that contribued to error def user_similarity(user1, user2, ratings): user1 = ratings[user1] user2 = ratings[user2] sse = 0 common_items = set(user1.keys()) & set(user2.keys()) for item in common_items: sse += pow(user1[item] - user2[item], 2) if len(common_items) == 0: sse = None return sse, len(common_items) # generates a dictionary of user -> list of 3-tuples, where the 3-tuple # contains (similar_user_id, similarity, support); the list is sorted such # that the most similar user is first # if min_support is provided, only users whose support is greater than 0 are # included # if max_similarity is provided, then only users whose similarity is better # than max_similarity are included def generate_similar_users(ratings, min_support=0, max_similarity=None): similarities = dict() # generate ratings for user1 in ratings: for user2 in ratings: if user1 < user2: if user1 not in similarities: similarities[user1] = [] if user2 not in similarities: similarities[user2] = [] similarity, support = user_similarity(user1, user2, ratings) if support > min_support: if not max_similarity or similarity < max_similarity: similarities[user1].append((user2, similarity, support)) similarities[user2].append((user1, similarity, support)) # sort for each user based on similarity (best first) and then support # (best first) for user in similarities: # stable sort, so sort the second-level sort first similarities[user].sort(key=itemgetter(2), reverse=True) similarities[user].sort(key=itemgetter(1)) return similarities # predict the rating that user would rate an item, based off of user # similarities # if num_required is provided, then the number of similar users used will be # <= num_similarities # returns a 2-tuple of (rating, support) def predict_rating(user, item, ratings, similarities, num_similarities=5): # ratings from like-users, limited by num_similarities # rating, similarity, support mratings = [] for ouser, similarity, support in similarities[user]: if len(mratings) == num_similarities: break if item in ratings[ouser]: mratings.append((ratings[ouser][item], similarity, support)) if not mratings: # if no similar users, cannot compute a rating; return an average rating # of 50 return 50, 0 elif len(mratings) == 1: # if only one user, return that rating return mratings[0][0], 1 # more than one user - weight based on similarity and support # compute most similar and least similar score most_similar = min([a[1] for a in mratings]) least_similar = max([a[1] for a in mratings]) # weight each rating rating = 0 total = 0 for rate, similarity, support in mratings: rating += rate * (least_similar - similarity + 1) * support total += 100 * (least_similar - similarity + 1) * support rating = float(rating) / total * 100 # round to the nearest 10 rating = round(rating, -1) return rating, len(mratings) def main(): # load data print "Loading..." objects, training, validation = load() # calculate similarities print "Calculating similarities..." similarities = generate_similar_users(training, min_support=5) # see how well predict_rating performs print "Validating..." error = 0 error2 = 0 # error from only cases where we could give a rating num_validations = 0 for user in validation: for item in validation[user]: p = predict_rating(user, item, training, similarities) a = validation[user][item] error += abs(p[0] - a) num_validations += 1 if p[1]: error2 += abs(p[0] - a) #print "Predicted: %0.2f,\t Actual: %0.2f" % (p[0], a) print "Error, on average, was %0.2f" % (error/num_validations) print "Error, excluding not enough data cases, was, on average, %0.2f" % (error2/num_validations) if __name__ == "__main__": main()
#!/usr/bin/env python # # Homework from w/b 06/03/2017 # 1.Create a list to hold the colours of the rainbow. # Experiment with retrieving the colours from the list. rainbow = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'] print("\n\n") homework = "HOMEWORK 1 - make list of raibow colours, and select." print(homework) print("-" * len(homework)+"\n") print('rainbow:', rainbow) print('rainbow first slot:', rainbow[0]) print('rainbow first four slots:', rainbow[:4]) print('rainbow slots from 5th:', rainbow[4:])
#!/usr/bin/env python # week 2 - example 3, range import sys # so I can use sys.stdout.write instead of print in python 2 & 3 # python 2: print number, python 3: print(number, end="") numbers = range(100, 10, -2) # range to print in reverse order for number in numbers: sys.stdout.write("%d\t" % (number)) # print with tabs between numbers sys.stdout.write("\n") # print newline before exit
m = int(input("введите целое число: ")) n = int(input("введите целое число: ")) p = int(input("введите целое число: ")) x = 0 if m < 0: x += 1 if n < 0: x += 1 if p < 0: x += 1 #print(f"Количество отрицательных чисел = {x}") print("Количество отрицательных чисел = ", x)
# encoding:utf-8 # 参考文献:贝叶斯优化调参 笔记前面这些链接,代码来自http://36kr.com/p/5114423.html import numpy as np import matplotlib.pyplot as plt x_obs = [-4,-2,0] # 初始值 训练数据 会变化 y_obs = [] # 初始值 训练数据 会变化 coefs = [6, -2.5, -2.4, -0.1, 0.2, 0.03] def f(x): total = 0 for exp, coef in enumerate(coefs): total += coef * (x ** exp) return total for x in x_obs: y = f(x) y_obs.append(y) print y_obs xs = np.linspace(-5.0, 3.5, 100) ys = f(xs) plt.figure() plt.plot(xs, ys) plt.show()
def evaluate(x,y,op): if op == "+": r = x + y elif op == "-": r = x - y elif op == "*": r = x * y elif op == "/": r = x / y return r
import math import par as par num = int(input('Digite um numero inteiro: ')) if (num%2) == 0: print('O numero é par!') else: print('O numero é impar')
nome = str(input('Qual é p seu nome? ')).title() if nome == 'Gustavo': print('Que nome bonito') elif nome == 'Paulo' or nome == 'Ana' or nome == 'João': print('Seu nome é bem popular no Brasil!') else: print('Seu nome é bem normal!') print('Tenha um bom dia {}!'.format(nome))
def notas(*num, sit=False): """ => Cria um dicionario com total de notas, maior nota, menor nota, média e situação :param num: recebe varias notas :param sit: recebe uma condição para exiber ou não a situação do aluno :return: retorna um dicionario """ media = sum(num) / len(num) aluno = dict() aluno['total'] = len(num) aluno['maior'] = max(num) aluno['menor'] = min(num) aluno['média'] = media if sit: if media >= 7: aluno['situação'] = 'BOA' elif 5 <= media < 7: aluno['situação'] = 'RAZOÁVEL' else: aluno['situação'] = 'RUIM' return aluno resp = notas(3.5, 2, 6.5, sit=True) print(resp)
from time import sleep def contador(): print('-=' * 20) print('Contagem de 1 até 10 de 1 em 1') for c in range(1, 11): sleep(0.5) print(c, end=' ') print('FIM', end=' ') print() print('-=' * 20) print('Contagem de 10 até 0 de 2 em 2') for c in range(10, -1, -2): sleep(0.5) print(c, end=' ') print('FIM', end=' ') print() print('-=' * 20) def contadorp(a, b, d): print(f'Contagem de {a} até {b} de {d} em {d}') for c in range(a, b, d): sleep(0.5) print(c, end=' ') print('FIM', end=' ') contador() print('Agora é sua vez de personalizar a contagem') i = int(input('Inicio: ')) f = int(input('Fim: ')) p = int(input('Passo: ')) print('-=' * 20) contadorp(i, f, p)
def voto(ano): from datetime import date i = date.today().year - ano if i < 16: return f'Com {i} anos: NÃO VOTA.' if 18 <= i < 65: return f'Com {i} anos: VOTO OBRIGATÓRIO.' if i >= 65: return f'Com {i} anos: VOTO OPCIONAL.' print('=-'*20) nasc = int(input('Em que ano você nasceu? ')) print(voto(nasc))
lista = [] c = 1 while True: lista.append(int(input('Digite um número: '))) r = str(input('Quer continuar...[S/N]: ')) if r in 'Nn': break if 5 in lista: print('O número 5 esta na lista') else: print('O número 5 não esta na lista') print(f'Foram digitados {len(lista)} números') lista.sort(reverse=True) print(f'A lista em ordem decrescente é {lista}')
n = float(input('Digita um número: ')) d = n * 2 t = n * 3 r = n ** 0.5 print('O dobro é {}, o triplo é {} e a raiz quadrata é {}'.format(d, t, r))
nome = str(input('Digite seu nome: ')).strip() print('Possui Silva no nome? {}'.format('SILVA' in nome.upper()))
print('-=-'*12) n1 = float(input('Digite o primeiro número: ')) n2 = float(input('Digite o segundo número: ')) print('-=-'*12) print(''' MENU [1] - Somar [2] - Multiplicar [3] - Maior [4] - Novos números [5] - sair do progarma ''') opcao = int(input('Informe a opção desejada: ')) sair = False while not sair:
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for l in range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f'Digite uma valor para [{l}], [{c}]: ')) print('=-'*25) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]:^5}]', end='') print() print('=-'*25) soma = 0 for v, n in enumerate(matriz): for nu in (n): if nu % 2 == 0: soma += nu print(f'A soma dos valores pares é {soma}') somac = matriz[0][2] + matriz[1][2] + matriz[2][2] print(f'A soma da terceira coluna é {somac}') somal = matriz[1][0] + matriz[1][1] + matriz[1][2] print(f'A soma da secunda linha é {somal}')
velo = float(input('Qual foi a velocidade do carro? ')) multa = (velo - 80) * 7 if velo > 80: print('Você foi multado, multa é de R${} reais'.format(multa))
from datetime import date date = date.today().year maior = 0 menor = 0 for c in range(1, 8): ano = int(input('{}ª ano de nascimento: '.format(c))) idade = date - ano if idade < 21: menor = menor + 1 else: maior = maior + 1 print('{} ainda não atingiram a maioridade'.format(menor)) print('{} pessoas ja atingiram a maioridadede'.format(maior))
def maximum(*numbers): largest = numbers[0] for x in numbers: if x > largest: largest = x return largest def main(): print(maximum(1, 3, 6, 200, 90)) if __name__ == "__main__": main()
class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # Instantiate the Cat Object with 3 cats cat1 = Cat('Garfield', 4) cat2 = Cat('Solly', 6) cat3 = Cat('Tom', 7) cats_ages = [cat1.age, cat2.age, cat3.age] oldest_age = max(cats_ages) print(f'The oldest cat is {oldest_age} years old') # create a function that finds the oldest cat '''def get_oldest_cat(*args): return max(args) print(f'The oldest cat is {get_oldest_cat(cat1.age, cat2.age, cat3.age)} years old')''' '''def oldest_age(*args): old_list = [] for item in args: old_list.append(item) return max(old_list) def oldest_name(): if oldest_age(cat1.age, cat2.age, cat3.age) == cat3.age: return cat3.name print(f'The oldest cat is {oldest_age(cat1.age, cat2.age, cat3.age)} years old and his name is {oldest_name()}')'''
class Pets(): def __init__(self, animals): self.animals = animals def walk(self): for animal in self.animals: print(animal.walk()) class Cat(): is_lazy = True def __init__(self, name, age): self.name = name self.age = age def walk(self): return f'{self.name} is just walking around' class Simon(Cat): def sing(self, sounds): return f'{sounds}' class Sally(Cat): def sing(self, sounds): return f'{sounds}' # add another cat class Garfield(Cat): def sing(self, sounds): return f'{sounds}' # instantiate the cat object with the cats Simon = Simon('Simon', 3) Sally = Sally('Sally', 6) Garfield = Garfield('Garfield', 8) # create a list of all the pets (create 3 cat instances from the above) my_cats = [Simon, Sally, Garfield] # instantiate the Pets class with all your cats use variable my_pets my_pets = Pets(my_cats) # output all of the cats walking using my_pets instance my_pets.walk()
def generator_function(num): for i in range(num): yield i # yield only keeps the most recent data in memory, unlike lists which store all items # this makes it a lot faster for item in generator_function(1000): print(item) def gen2(num): for i in range(num): yield i * 2 # yield pauses the function and comes back when next is called g = gen2(100) print(next(g)) # this returns 0, it runs 0 * 2 and that is it. List run all range h = gen2(100) next(h) # 0*2=0 next(h) # 1*2=2 print(next(h)) # 2*2=4
# works on list, set, dictionaries my_list = [] for char in 'hello': my_list.append(char) print(my_list) my_list = [char for char in 'hello'] # same as above, for char in hello, add char to list # list 2 creates a list with numbers ranging from 0 to 99 my_list2 = [num for num in range(0, 100)] # for number in range 0 to 100, add num to my_list2 print(my_list2) # multiplies all numbers from 0 to 100 times 2 my_list3 = [num * 2 for num in range(0, 100)] print(my_list3) # return only the even numbers my_list4 = [num ** 2 for num in range(0, 100) if num % 2 == 0] print(my_list4)
#Amaris Efthimiou #[email protected] #october 21, 2019 #Borough stats import matplotlib.pyplot as plt import pandas as pd pop = pd.read_csv('nycHistPop.csv',skiprows=5) b = input('Enter a borough:') print('Minimum Population:', pop[b].min()) print('Average Population:', pop[b].mean()) print('Maximum Population:', pop[b].max())
import csv with open('out.csv' ,'w') as outFile: fileWriter = csv.writer(outFile) with open('user.csv','r') as inFile: fileReader = csv.reader(inFile) for row in fileReader: fileWriter.writerow(row) with open('out.csv','r') as outFile: fileReader = csv.reader(outFile) for row in fileReader: print row
import sqlite3 def create_db(): with sqlite3.connect('company.db3') as conn: # Создаем курсор - это специальный объект который делает запросы и получает их результаты cursor = conn.cursor() cursor.execute("""DROP table if exists Terminal""") cursor.execute("""DROP table if exists Partner""") cursor.execute("""DROP table if exists Payment""") cursor.execute(""" CREATE TABLE if not exists Terminal ( id INTEGER PRIMARY KEY, title TEXT, configuration TEXT, comment TEXT, pub_key TEXT ); """) cursor.execute(""" CREATE TABLE if not exists Payment ( id INTEGER PRIMARY KEY AUTOINCREMENT, datetime TEXT, terminal_id INTEGER, transaction_id INTEGER, partner_id INTEGER, summ INTEGER, FOREIGN KEY (terminal_id) REFERENCES Terminal(id) ON DELETE CASCADE, FOREIGN KEY (partner_id) REFERENCES Partner(id) ON DELETE CASCADE ); """) cursor.execute(""" CREATE TABLE if not exists Partner ( id INTEGER PRIMARY KEY, title TEXT, comment TEXT ); """) class Terminal: def insert(self, terminal_id, title, configuration): """ Добавляет данные в БД """ with sqlite3.connect('company.db3') as conn: cursor = conn.cursor() cursor.execute(""" insert into Terminal (id, title, configuration) VALUES (?, ?, ?);""", (terminal_id, title, configuration)) def delete(self, terminal_id): """ Удаляет данные терминала из БД """ with sqlite3.connect('company.db3') as conn: cursor = conn.cursor() cursor.execute(""" delete from Terminal where id = ?;""", (terminal_id,)) def get_total_sum(self, terminal_id): """ Считает суммму прошедших через указанный терминал средств """ with sqlite3.connect('company.db3') as conn: cursor = conn.cursor() cursor.execute(""" select sum(summ) from Payment where terminal_id = ?; """, (terminal_id,)) print('terminal_id =', terminal_id, 'sum:', cursor.fetchone()) class Payment: def insert(self, datetime, terminal_id, transaction_id, partner_id, summ): with sqlite3.connect('company.db3') as conn: cursor = conn.cursor() cursor.execute(""" insert into Payment ( datetime, terminal_id, transaction_id, partner_id, summ) VALUES (?, ?, ?, ?, ?);""", (datetime, terminal_id, transaction_id, partner_id, summ)) def delete(self, transaction_id): with sqlite3.connect('company.db3') as conn: cursor = conn.cursor() cursor.execute(""" delete from Payment where transaction_id = ?;""", (transaction_id,)) # print('payment transaction_id = {} delete ok'.format(transaction_id)) def get_all_data(self): """ Выводит все данные обо всех платежах """ with sqlite3.connect('company.db3') as conn: cursor = conn.cursor() cursor.execute(""" select * from Payment"""), output = cursor.fetchall() while output: print(output) output = cursor.fetchall() class Partner: def insert(self, partner_id, title, comment): with sqlite3.connect('company.db3') as conn: cursor = conn.cursor() cursor.execute(""" insert into Partner (id, title, comment) VALUES (?, ?, ?);""", (partner_id, title, comment)) def delete(self, partner_id): with sqlite3.connect('company.db3') as conn: cursor = conn.cursor() cursor.execute(""" delete from Partner where id = ?;""", (partner_id,)) # print('partner id = {} delete ok'.format(partner_id)) def get_partners_total_sum(self): """ формирует выборку с итоговой задолжностью перед каждым из партнёров """ with sqlite3.connect('company.db3') as conn: cursor = conn.cursor() cursor.execute(""" select title, sum(summ) from Payment inner join Partner on Payment.partner_id = Partner.id group by title"""), output = cursor.fetchone() while output: print(output) output = cursor.fetchone() if __name__ == "__main__": create_db()
# program to input angles of a triangle and check whether triangle is valid or not ang1 = int(input("Enter the degree of the first angle: ")) ang2 = int(input("Enter the degree of the second angle: ")) ang3 = int(input("Enter the degree of the third angle: ")) if ang1 + ang2 + ang3 == 180: print ("It is a Triangle.") else: print ("It is NOT a Triangle.")
# cook your dish here for t in range(int(input())): s=input() count=0 while (len(s)>1): if s[:2]=='xy'or s[:2]=='yx': s=s[2:] count+=1 else: s=s[1:] print(count)
#coding: utf-8 # Day 5 of month of API # Looking at local air quality data and what the last 24 hours have been like in your local area # Greg Jackson 05/12/15 gr3gario on twitter ang gregario on github import requests import json url = "http://api.erg.kcl.ac.uk/AirQuality/Data/SiteSpecies/SiteCode=IS2/SpeciesCode=NO2/StartDate=04-12-15/EndDate=05-12-15/Json" # Gives data in closest AQ monitor r = requests.get(url).json() # Make a request to the LAQN API for data rLoop = r['RawAQData']['Data'] # You got to define this here as you can't nest it below. the for loop below only works for the list embedded in the JSON object AQugm3 = [] # A list to store the readins for key in rLoop: AQugm3temp = key['@Value'] # This loops through each data packet in the list and pulls out our relevant datapoint try: # A try catch is included here as there are blank datapoints returned from the LAQN API that would mess this up occasionally if there wasn't a catch in place AQugm3temp = float(AQugm3temp) # Converts from a string to a float so we can perform operations on it AQugm3.append(AQugm3temp) # Adds output to AQugm3 variable # Catches exceptions except: print 'error in parsing, oops' pass # Really simple averages. Sums all elements in the list and divides by the length of the list average = sum(AQugm3) / float(len(AQugm3)) average = round(average,2) # This is an EU defined goal for NO2 in the city. I figure if our daily average is below this we're doing well. Its more to give context to the number. goal = 40.0 # Simple check to give context to the number. if average < goal: print "Hurray! The air quality today is less than the yearly average target of 40 ug/m3 NO2 target in the UK and reads " +str(average)+ " ug/m3" elif average > goal: print "Unfortunately the air quality today is more than the yearly average target of 40 ug/m3 NO2 in the UK and reads " + str(average)+ " ug/m3"
h = list(map(int, input().strip().split(' '))) word = input().strip() alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] dictionary = {} for i, j in enumerate(alphabet): dictionary[j] = h[i] height = 0 for i in word: if dictionary[i] > height: height = dictionary[i] print("Dlugosc slowa {0}, najwieksza litera: {1}".format(len(word), height)) print(len(word)*height)
def total(a=5, *numbers, **phonebook): print("a", a) for number in numbers: print("number", number) for key, value in phonebook.items(): print(key, value) print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))
import turtle def draw_square(some_turtle): for i in range(1,5): some_turtle.right(90) some_turtle.forward(100) def draw_art(): window = turtle.Screen() window.bgcolor("white") # create the turtle brad - Draws a Square brad = turtle.Turtle() brad.shape("turtle") brad.color("purple") brad.speed(2) # Call draw_square as many times as the number of squares you want. for i in range(1,37): draw_square(brad) brad.right(10) # create the turtle angie - draw circle angie = turtle.Turtle() angie.shape("arrow") angie.color("blue") angie.circle(100) window.exitonclick() draw_art()
num1 = int(input("escribe un numero")) num2 = int(input("escribe otro numero")) total = 0 while num1 <= num2: total = total + num1 num1 += 1 print(f"El resultado es {total}")
# modulo de ejemplo def sumar(numero1, numero2): print(f"(módulo_mate_A): La suma es {numero1+numero2} ") def restar(numero1, numero2): print(f"(módulo_mate_A): La resta es {numero1-numero2} ")
num = int(input("elige un numero del 1 al 10")) numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] total = 0 for n in numeros: total = num*n print(f"{num} x {n} = {total}") n += 1 if n > 10: break
class clsCoche: def __init__(self, matricula, marca): self.matricula = matricula self.marca = marca self.kilometros_recorridos = 0 self.gasolina = 0 def suficiente(self, gasolina, kilometros): max_km = gasolina / 0.1 if kilometros <= max_km: return True return False def avanzar(self, kilometros): if self.suficiente(self.gasolina, kilometros): self.gasolina -= (kilometros*0.1) self.kilometros_recorridos += kilometros else: print("Hace falta gasolina") def repostar(self, gasolina): self.gasolina += gasolina c1 = clsCoche("0908IKJ", "Tesla") c1.repostar(100) print(f"KM: {c1.kilometros_recorridos} -- Gasolina: {c1.gasolina}") c1.avanzar(150) print(f"KM: {c1.kilometros_recorridos} -- Gasolina: {c1.gasolina}") c1.avanzar(600) print(f"KM: {c1.kilometros_recorridos} -- Gasolina: {c1.gasolina}") c1.avanzar(200) print(f"KM: {c1.kilometros_recorridos} -- Gasolina: {c1.gasolina}")
lista = [6,14,11,3,2,1,15,19] def rango(num): if num < 21 and num > 0: print("Numero en rango") return True else: print("Numero fuera de rango") return False def enlista(num): for n in lista: if n == num: print("Numero en lista") num = int(input("Escribe un numero entre 1 y 20: ")) if rango(num): enlista(num)
# -*- coding: utf-8 -*- """ Created on Tue Mar 7 11:54:07 2017 @author: JM """ import math def media(x): media = 0 for score in x.values(): media += score return (media / len (x.values())) """ Recibe los items, usuarios que han puntuado los dos items y el conjunto de todos los usuarios """ def similarity(item1, item2, users, conj): num = 0 den1 = 0 den2 = 0 for user in users: median = media(conj[user]) score1 = conj[user].get(item1) score2 = conj[user].get(item2) num += (score1 - median) * (score2 - median) den1 += (score1 - median)**2 den2 += (score2 - median)**2 den1 = math.sqrt(den1) den2 = math.sqrt(den2) return (num/(den1*den2)) """ A partir de un item, el conjunto de todos los usuarios y el conjunto de todos los items, calcula los items mas similares y que superen el umbral """ def neighborhood(x,conj_user,conj_item,threshold): neighborhood = {} itemX = conj_item.get(x) #Recorremos todos los items for item in conj_item: sim = 0 users = [] if item != x: itemY = conj_item.get(item) #Para cada item obtenemos todos los usuarios puntuados for user in itemY: #Comprobamos si el usuario existe puntuado en la lista del item recibido if user in itemX: users.append(user) #print("Usuarios que han puntuado",x,item, users) if users != []: sim = similarity(x,item,users,conj_user) #print("Similaridad:",sim) #Si la similaridad supera el umbral, lo consideramos vecino if(sim >= threshold): neighborhood[item] = sim return neighborhood """ a = Usuario p = Item no puntuado conj_user = Conjunto de los usuarios con sus items puntuados conj_item = Conjunto de los items con los usuarios que lo han puntuado threshold = Umbral de vecindad """ def prediction (a, p, conj_user,conj_item, threshold): neighbors = neighborhood(p, conj_user,conj_item, threshold) num = 0 den = 0 #Recorremos todos los items similares al item que queremos calcular for item in neighbors: #Elegimos solo los items similares que han sido votados por el usuario "a" if item in conj_user[a]: score = conj_user[a][item] sim = neighbors.get(item) num += (sim*score) den += sim #print("Sim",sim,"Score",score) if num == 0 and den == 0: print("No hay ningun vecino del item {} que este puntuado por el usuario {}".format(p,a)) else: return (num/den)
#Problem 24 solution (part 1) #Given a tile (from input), it return its coordinates # using "Cube coordinates" def getTileCoordinates(tile): x,y,z = 0,0,0 while tile != '': if tile.startswith('e'): x += 1 y -= 1 tile = tile[1:] elif tile.startswith('w'): x -= 1 y += 1 tile = tile[1:] elif tile.startswith('ne'): x += 1 z -= 1 tile = tile[2:] elif tile.startswith('nw'): y += 1 z -= 1 tile = tile[2:] elif tile.startswith('se'): y -= 1 z += 1 tile = tile[2:] elif tile.startswith('sw'): x -= 1 z += 1 tile = tile[2:] return (x,y,z) #1rst part "main" def p24(fileName): with open(fileName, 'r') as f: tiles = [line.strip() for line in f] blackTiles = [] for tile in tiles: coordinates = getTileCoordinates(tile) #If that tile is already black, we flipped to white # (remove from black tiles list). #If that tile is white, we flip it and store it # as a black tile. if coordinates in blackTiles: blackTiles.remove(coordinates) else: blackTiles.append(coordinates) return blackTiles #Problem 24 solution (part 2) #Get all the tiles that have to be checked. That tiles are the ones # on the flipped tiles list and its neighboors def getTilesToCheck(flippedTiles): neighboors = [(1,-1,0),(-1,1,0),(1,0,-1),(0,1,-1),(0,-1,1),(-1,0,1)] tilesToCheck = set() for (x,y,z) in flippedTiles: tilesToCheck.add((x,y,z)) for (nx,ny,nz) in neighboors: tilesToCheck.add((x+nx, y+ny, z+nz)) return tilesToCheck #Given a tile, gets the number of neighboor tiles that are black def getBlackNeighboors(tile, flippedTiles): (x,y,z) = tile neighboors = [(1,-1,0),(-1,1,0),(1,0,-1),(0,1,-1),(0,-1,1),(-1,0,1)] blackNeighboors = 0 for (nx,ny,nz) in neighboors: if (x+nx, y+ny, z+nz) in flippedTiles: blackNeighboors += 1 return blackNeighboors #2nd part "main" def p24_2(flippedTiles): for _ in range(100): newFlipped = set() tilesToCheck = getTilesToCheck(flippedTiles) for tile in tilesToCheck: blackNeighboors = getBlackNeighboors(tile, flippedTiles) if tile in flippedTiles and blackNeighboors in [1,2]: newFlipped.add(tile) if tile not in flippedTiles and blackNeighboors == 2: newFlipped.add(tile) flippedTiles = newFlipped return len(flippedTiles) #Main flippedTiles = p24('input.txt') print("P24 ->", len(flippedTiles)) result = p24_2(flippedTiles) print("P24_2 ->", result)
import itertools #Problem 3 solution (part 1) def p3(fileName, slope): with open(fileName, 'r') as f: treeMap = [line.strip() for line in f] row, column = 0,0 numTrees = 0 numColumns = len(treeMap[row]) while row < len(treeMap)-1: row = row + slope[0] column = column + slope[1] if treeMap[row][column % numColumns] == '#': numTrees += 1 return numTrees #Problem 3 solution (part 2) def p3_2(fileName, slopes): result = 1 for slope in slopes: sol = p3(fileName, slope) result *= sol return result #Main result = p3('input.txt', (1,3)) print("P3 ->",result) slopes = [(1,1), (1,3), (1,5), (1,7), (2,1)] result = p3_2('input.txt', slopes) print("P3_2 ->", result)
# coding=utf-8 """ The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. """ import unittest def _lis(array, i, res_lis): """ Recursive Longest Increasing Subsequence caluclation helper :param array: given array of integers :param i: current end of lis to be calculated :res_lis: list of all lis calculated :return: current lis of max length :rtype: int """ if not i: return 1 tmp_res, max_end_here = 1, 1 for j in range(i): tmp_res = _lis(array, j, res_lis) if array[i] > array[j]: max_end_here = max(tmp_res+1, max_end_here) # collecting list of lis throughout calculation res_lis.append(max_end_here) return max_end_here def lis_rec(array): """ Main LIS function for recursive method. calls LIS helper for each index of a given array :param array: given array of integers :return: Length of LIS :rtype: int """ result_lis = list() for _ in range(len(array)): _lis(array, _, result_lis) return max(*result_lis) def lis_dp(array): """ Longest Increasing Subsequence using dynamic programming approach. :param array: given array of integers :return: length of LIS :rtype: int """ mem = [1] * len(array) for i in range(1, len(mem)): res = 1 for j in range(i): if array[i] > array[j]: res = max(res, 1+mem[j]) mem[i] = res return max(*mem) class TestLIS(unittest.TestCase): """ Test Longest Increaing Subsequence solutions """ def test_lis(self): """ Test both recursive and dp approaches """ arr = [3, 4, -1, 0, 6, 2, 3] self.assertEqual(4, lis_rec(arr)) self.assertEqual(4, lis_dp(arr)) arr = [3, 10, 2, 1, 20] self.assertEqual(3, lis_rec(arr)) self.assertEqual(3, lis_dp(arr))
""" Quick Sort """ def _partition(array: list, left, right): """ partition with last element as a pivot """ pivot = array[right] smaller = left - 1 for i in range(left, right): if array[i] <= pivot: smaller += 1 array[i], array[smaller] = array[smaller], array[i] array[smaller+1], array[right] = array[right], array[smaller+1] return smaller+1 def quick_sort(arr: list, low, high): if low < high: pi = _partition(arr, low, high) quick_sort(arr, low, pi-1) quick_sort(arr, pi+1, high) return arr """ Quick Sort. Median of Three """ def _median(array: list, left, right, middle): if array[left] < array[right]: return right if array[right] < array[middle] else middle else: return left if array[left] < array[middle] else middle def _partition_mot(array: list, left, right): # median of three partition i = left j = right pivot = array[_median(array, left, right, (left + right)//2)] while True: while array[i] < pivot: i += 1 while array[j] > pivot: j -= 1 if i < j: array[i], array[j] = array[j], array[i] else: return j def quick_sort_mot(array: list, left, right): if right-left < 2: return array pi = _partition_mot(array, left, right) quick_sort_mot(array, left, pi) quick_sort_mot(array, pi+1, right) return array
""" Merge Sort """ def _merge(array, middle, left, right): left_len = middle - left+1 right_len = right - middle left_arr = [0]*left_len right_arr = [0]*right_len for g in range(0, left_len): left_arr[g] = array[left+g] for g in range(0, right_len): right_arr[g] = array[middle+1+g] i = 0 j = 0 k = left while i < left_len and j < right_len: if left_arr[i] <= right_arr[j]: array[k] = left_arr[i] i += 1 else: array[k] = right_arr[j] j += 1 k += 1 while i < left_len: array[k] = left_arr[i] i += 1 k += 1 while j < right_len: array[k] = right_arr[j] j += 1 k += 1 def merge_sort(array: list, l, r): """ Merge Sort :param array: given array :param l: beginning :param r: ending :return: sorted array """ if l < r: middle = (l + (r - 1)) // 2 merge_sort(array, l, middle) merge_sort(array, middle+1, r) _merge(array, middle, l, r) return array
# coding=utf-8 """ Given a string, find the longest substring which is palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”. """ import unittest def lpstr(array): """ Longest Palindromic Substring. Dynamic Programming approach :param array: given string :return: Length of LPS """ if not array: return 0 mat = [[0 for _ in range(len(array))] for _ in range(len(array))] max_length = 1 for i in range(len(array)): mat[i][i] = 1 if i+1 < len(array) and array[i] == array[i+1]: mat[i][i+1] = 1 max_length = 2 for cur_length in range(2, len(array)): j = cur_length-1 for i in range(0, len(array)-cur_length): if array[i] == array[j+1] and mat[i+1][j] == 1: mat[i][j+1] = 1 max_length = max(cur_length+1, max_length) j += 1 return max_length class TestLPStr(unittest.TestCase): """ Test Case for Longest Palindromic Substring """ def test_lpstr(self): """ Test Cases for LPS """ test_arr = list('geekeekg') self.assertEqual(lpstr(test_arr), 5) test_arr = list('forgeeksskeegfor') self.assertEqual(lpstr(test_arr), 10) self.assertEqual(lpstr([]), 0)
planet_list = ["Mercury", "Mars"] print(planet_list) planet_list.append('Jupiter') print(planet_list) planet_list.append('Saturn') print(planet_list) planet_list.extend(['Neptune', 'Uranus']) print(planet_list) planet_list.append('Pluto') print(planet_list) rockey_planets = planet_list[slice(0, 2)] print('The Rockey Planets: ' + str(rockey_planets)) del planet_list[6] print(planet_list) satellites = [('Cassini', 'Saturn'), ('Rover', 'Mars'), ('Galileo', 'Jupiter')] for planet in planet_list: for satellite in satellites: if satellite[1] is planet: print('The {} satellite landed on {}'.format(satellite[0], planet))
text = input('Text: ') # 0.0588 * L - 0.296 * S - 15.8 # creates all the necessary variables r = len(text) words, letters, sentence = len(text.split()), 0, 0 # look into each character in the string for i in range(r): if text[i].isalpha(): letters += 1 elif text[i] == '!' or text[i] == '?' or text[i] == '.': sentence += 1 # calculate de algorithm L, S = (letters / words) * 100, (sentence / words) * 100 grade = 0.0588 * L - 0.296 * S - 15.8 # verifies teh conditions to print in the prompt if grade < 1: print('Before Grade 1') elif grade >= 16: print('Grade 16+') else: print(f'Grade {round(grade)}')
import random def end(enemy_health,your_health): if your_health > 0: print(" ") print("You slay the Enemy") print('Пошли') else: print(" ") print("You were slain...") print('Перезапустите игру') time.sleep(1000) def your_first(): enemy_health = 20 your_health =20 while your_health > 0 and enemy_health > 0: your_damage = random.choice(range(7,13)) enemy_health -= your_damage if enemy_health <= 0: enemy_health = 0 print(" ") print("You dealt " + str(your_damage) + " damage!") print("Enemy health:" + str(enemy_health)) end(enemy_health,your_health) else: print(" ") print("You dealt " + str(your_damage) + " damage!") print("Enemy health:" + str(enemy_health)) enemy_damage = random.choice(range(9, 21)) your_health -= enemy_damage if your_health <= 0: your_health = 0 print(" ") print("Enemy dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) end(enemy_health,your_health) else: print(" ") print("Enemy dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) def enemy_first(): enemy_health = 20 your_health =20 while your_health > 0 and enemy_health > 0: enemy_damage = random.choice(range(9, 21)) your_health -= enemy_damage if your_health <= 0: your_health = 0 print(" ") print("Ork dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) end(enemy_health,your_health) else: print(" ") print("Enemy dealt " + str(enemy_damage) + " damage!") print("Your health:" + str(your_health)) your_damage = random.choice(range(7,13)) enemy_health -= your_damage if enemy_health <= 0: print(" ") print("You dealt " + str(your_damage) + " damage!") print("Enemy health:" + str(enemy_health)) end(enemy_health,your_health) else: print(" ") print("You dealt " + str(your_damage) + " damage!") print("Enemy health:" + str(enemy_health)) print("(+)~~~~~~~~~~~~~~~(+)") print(" | Damage: | ") print(" | 7-12 | ") print(" | Speed: | ") print(" | 6/10 | ") print(" | Critical Chance:| ") print(" | 64% | ") print("(+)~~~~~~~~~~~~~~~(+)") print(" ") print("You encountered an Enemy") enemy = "Enemy" print(" ") print("(+)~~~~~~~~~~~~~~~(+)") print(" |Enemy | Health: 20| ") print(" |-----------------| ") print(" |Damage: 9-20| ") print(" |-----------------| ") print(" |Speed: 2/10| ") print(" |-----------------| ") print(" |Crit Chance: 13%| ") print("(+)~~~~~~~~~~~~~~~(+)") print("You engage the Enemy in a battle!") your_crit = (1, 65) enemy_crits = (1, 13) your_speed = 6 ork_speed = 2 if ork_speed >= your_speed: print("The " + enemy + " is faster, it attacks first!") enemy_first() else: print("You're faster and get to attack first!") your_first()
from math import * class KalmanFilter: @staticmethod def gaussian_f(mu, sigma2, x): """ Gaussian likelihood with a mean and variance at input, `x` Args: mu: mean sigma2: variance x: Returns: (float) probability """ coefficient = 1.0 / sqrt(2.0 * pi * sigma2) exponential = exp(-0.5 * (x - mu) ** 2 / sigma2) return coefficient * exponential @staticmethod def update(mu1, sigma1, mu2, sigma2): """ Takes in two means and two squared variance terms, and returns updated gaussian parameters. Args: mu1: mean 1 sigma1: variance 1 mu2: mean 2 sigma2: variance 2 Returns: (Tuple[float, float]): mean and variance """ new_mean = (sigma2 * mu1 + sigma1 * mu2) / (sigma2 + sigma1) new_var = 1 / (1 / sigma2 + 1 / sigma1) return new_mean, new_var @staticmethod def predict(mean1, var1, mean2, var2): """ Takes in two means and two squared variance terms, and returns updated gaussian parameters, after motion. Args: mean1: var1: mean2: var2: Returns: (Tuple[float, float]): mean and variance """ new_mean = mean1 + mean2 new_var = var1 + var2 return new_mean, new_var
def LowestPosInt(IntList): #Give the lowest possible positive int Lowest=1 #Sort the List SortedList = sorted(IntList) #For every value in the sorted list, if it is equivilent to the lowest value that means that the lowest value exist, so we should bump up the lowest value by 1 for i in SortedList: if i == Lowest: Lowest=Lowest+1 return Lowest List = [5,3,4,9,2,1,-1,5,2] List2 = [1, 2, 0] print(LowestPosInt(List)) print(LowestPosInt(List2))
def gcd(a,b): if (b>a): if (a==0): return b return gcd(a, b%a) if (a>b): if (b==0): return a return gcd(b , a%b ) x = eval(input("Enter first number : ")) y = eval(input("Enter second number : ")) z = gcd(x , y) print("GCD of the numbers : ",z)
from datetime import datetime import time as t currentTime = None while True: # time_stamp = t.time() # number of seconds since 1-1-1970 UTC time # current_time = datetime.fromtimestamp(time_stamp).strftime("%d-%B,%H:%M:%S") # print(current_time) current_date = datetime.now().strftime("%d-%B,%H:%M:%S") print(current_date) t.sleep(5)
""" ***** A/B-Tests ***** > are run on websites, where one segment of the users see the old website and another part the changed websites > then the impact on user behavior is measured > can be algorithmic, design, pricing changes, etc. > first, choose what you are trying to influence: times sold, speed, ad clicks, etc. > variance is the enemy: make sure that the difference between the groups does not come from randomness only > --> T-Tests, p-values """ """ ***** T-Tests, p-values ***** > assuming normal distribution in user behavior > T-Tests normalize a values and measure along a (kind of) normal distribution how far outside normal behavior a data point is: the further outside, the less the probability that it happened by chance alone > a p-value quantifies this: the lower p, the less the probability that this happened by chance > high T-Statistic, low p means statistical significance > chosse your threshhold before the experiment! .05 or .01 most of the time """ """ ***** How long to run an experiment? ***** > after your values have become significant, both pos and neg > after an upper bound of time > when there is nothing to show you that the value will converge any time soon > this is important because you should not run more than one experiment at once because they will influence each other """ """ ***** Common Mistakes ***** > correlation != causation > novelty effects: just the fact that something changed can cause significant changes in behavior, so let the experiment run long enough to make sure the difference in behavior is really caused by the change itself, not by its novelty > to make sure: if change is implemented, run another experiment that reimplements the old state and see if it has the same effect as before. If yes, it is a novelty effect > seasonal effects, like christmas and summer time and associated behavior effects > make sure the users you select for group A and B are really randomly selected. A non-random selection can happen if they are based on customer IDs for example --> A/A-Test to make sure > data pollution: watch out for bots: you most likely want to measure people's behavior, not the ones of the crawlers """
""" ***** K-Nearest Neighbours ***** > you already have a scatterplot along any dimensions with classified data points > a new data point is classified by identifying its k nearest neighbours and then classify the data points depending on the class most of the k data points have """ """ ***** Dimensionality Reduction ***** > to reduce the number of dimensions/attributes in a data set, one has to find a hyperplane within a space in n dimensions while preserving its variance > exp.: imagine a 3 dimensional space with data points in it. Try to find a 2-dimensional hyperplane within that space that preserves best the variance of the 3 dimensional data points > now the data points' position are projected onto the plane and you have a dimensionality reduced data set > practical example is image reduction: the 3 dimensions of color are projected down to a value between 0 and 1 for brightness """ """ ***** Data Warehousing ***** > What is Data Warehousing? Putting data from many input streams into one big data bank and transforming it beforehand in a way that can be queryed and realtions between the data from different input streams can be made, "Big Data" > ETL, Extract, Transform, Load: is the conventional way of doing data warehousing. You take the wanted data from you input devices, then you transform into a format that can be taken by the data bank and load it into the data bank > problem: in the case of too much data the transforming is the bottle neck, inconvenient for big data... > ELT then loads the raw data into the data repository as-is and uses the power of software like Hadoop to transform it afterwards > is mostly a distributed database built on Hadoop """ """ ***** Reinforcement Learning ***** > Q-Learning > imagine Pac-Man, it is the agent in this expample > for each of the states s Pac-Man can be in (ghost, walls, etc. nearby), there is a set of possible actions a Pac-Man can perform (up, down, left, right) > each pair (a, s) has a value Q which is the metric by which it decides what action to take > e.g. Pac-Man performs an action and gets eaten by a ghost, then the action performed in this situation gets penalized by a lower Q so that the agent is less likely to take the same action the next time the same situation occurs. It learned. > Vice versa, if favorable things happen to the agent, the Q value of the (a, s) pair gets raised so that the agent is more likely to act in the same way > all Qs for all (a, s) start with value of 0 > exploration problem: to converge on good Q-values by starting with 0 for all Qs and always choosing a with highest Q is inefficient to explore the entire space of actions and their consequences > all this is a "Markov Decesion Process" > in short, reinforcement learning consists of an exploration phase where correct rewards for actions in certain situations are found > then there is an optimal action in each situation to take and your agent behaves in an (almost) optimal manner """
import numpy as np def rotateImage(a): a=np.array(a) a=a.transpose() a=a.tolist() for i in range(0,len(a)): a[i].reverse() return a
dict1={} dict2={} x=int(input()) dict1[x]=int(input()) y=int(input()) dict2[y]=int(input()) print("First Dictionary") print(dict1) print("Second Dictionary") print(dict2) print("Concatenated dictionary is") dict3={} dict3.update(dict1) dict3.update(dict2) print(dict3) print("The Values of Dictionary") print(list(dict3.values()))
n=int(input()) lst=list(map(int,input().split())) s=int(input()) import math lst_fact=[] for i in lst: lst_fact.append(math.factorial(i)) c=0 for i in range(n): if s==lst_fact[i]: print(lst[i]) c=1 break if c==0: print("Not found")
import random #modulo para generar valores aleatorios def busqueda_lineal(lista, objetivo): match = False for elemento in lista: #O(n) if elemento == objetivo: match = True break return match def main(): tamano_lista = int(input('De que tamaño será la lista: ')) objetivo = int(input('Numero a encontrar: ')) lista = [random.randint(0, 100) for i in range(tamano_lista)] encontrado = busqueda_lineal(lista, objetivo) print(lista) print(f'El elemento {objetivo} {"esta" if encontrado else "no esta"} en la lista') if __name__ == '__main__': main()
class Automovil: #super class def __init__(self, modelo, marca, color): self.modelo = modelo self.marca = marca self.color = color self._estado = 'en reposo' #variables privadas con "_variable" self._motor = None def __repr__(self): """Para muchos tipos, esta función intenta devolver una cadena que produciría un objeto con el mismo valor cuando se pasa a eval(); de lo contrario, la representación es una cadena encerrada entre paréntesis angulares que contiene el nombre del tipo de objeto junto con Información que a menudo incluye el nombre y la dirección del objeto. Una clase puede controlar lo que esta función devuelve para sus instancias definiendo un método __repr__(). """ return f'Automovil de caracteristicas Modelo: {self.modelo} / Marca: {self.marca} / Color: {self.color}' def acelerar(self, tipo='rapida'): self.tipo = tipo if tipo == 'despacio': self.Motor.inyecta_nafta(self, 10) print('Va rapido, bobo.') else: self.Motor.inyecta_nafta(self, 3) print('Lento pero seguro.') self._estado = 'en movimiento' print(f'Automovil {self._estado}.') print(' ') class Motor: def __init__(self, cilindros, tipo='nafta'): self.cilindros = cilindros self.tipo = tipo self._temperatura = 0 def __repr__(self): return f'de {self.cilindros} cilindros, tipo {self.tipo}' def inyecta_nafta(self, cantidad): self.cantidad = cantidad return cantidad if __name__ == '__main__': Automovil_1 = Automovil('Uno', 'Fiat', 'Verde') Automovil_1.acelerar() Motor_1 = Automovil.Motor(4, 'Nafta') Automovil_2 = Automovil('Aveo', 'Chevrolet', 'Blanco') Automovil_2.acelerar() Motor_2 = Automovil.Motor(4, 'Nafta') print(f'{repr(Automovil_1)} y motor {repr(Motor_1)}') print(f'{repr(Automovil_2)} y motor {repr(Motor_2)}')
import enumeracion as en import busqueda_binaria as binbus import aproximacion as aprox objetive = int(input('Ingrese un número entero: ')) print("Escoja una de las siguientes opciones...") opcion = int(input('1- EE 2- BB 3-Aprox. :')) while opcion != 4: if opcion == 1: en.objetivo = objetive en.enumerar() break elif opcion == 2: binbus.objetivo = objetive binbus.binbusq() break elif opcion == 3: aprox.objetivo = objetive aprox.aprox() break else: print(f'{opcion} no es una opcion.')
class Persona: def __init__(self, nombre): self.nombre = nombre def avanza(self): return 'Ando caminando' class Ciclista(Persona): def __init__(self, nombre): super().__init__(nombre) def avanza(self): return 'Ando en bici' class Motociclista(Persona): def __init__(self, nombre): super().__init__(nombre) def avanza(self): return 'Ando como bala wacho' def main(): persona = Persona('Tato') print(f'Soy {persona.nombre} y {persona.avanza()}') ciclista = Ciclista('Pepe') print(f'Soy {ciclista.nombre} y {ciclista.avanza()}') moto = Motociclista('Walter') print(f'{moto.avanza()}. El {moto.nombre} atr.') if __name__ == '__main__': main()
class Coordenada: def __init__(self, x, y): """Método constructor. self == this en JS """ self.x = x self.y = y def distancia (self, otra_coordenada): """Cada función dentro de una clase se llama "método" Calculamos con método euclidiano """ x_diff = (self.x - otra_coordenada.x)**2 y_diff = (self.y - otra_coordenada.y)**2 return (x_diff + y_diff)**0.5 if __name__ == '__main__': coord_1 = Coordenada(3, 30) coord_2 = Coordenada(4, 8) print(coord_1.distancia(coord_2)) print(isinstance(coord_2, Coordenada)) #Si es instancia de Coordenada
""" Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. """ class Solution: def backspaceCompare(self, S: str, T: str) -> bool: stackS = [] stackT = [] for ch in S: if ch == '#': if stackS: stackS.pop() else: stackS.append(ch) for ch in T: if ch == '#': if stackT: stackT.pop() else: stackT.append(ch) return stackT == stackS
""" https://leetcode.com/problems/search-a-2d-matrix/ Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. """ class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix or not matrix[0]: return False def binarySearch(row, low, high, target): if high <= low: return False mid = int((low+high) / 2) if row[mid] == target: return True if target < row[mid]: return binarySearch(row, low, mid, target) return binarySearch(row, mid + 1, high, target) for row in matrix: if row[-1] == target: return True elif row[-1] > target and binarySearch(row, 0, len(row), target): return True return False
""" https://leetcode.com/problems/single-element-in-a-sorted-array/ You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once. """ class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: res = 0 for i in range(len(nums)): if i % 2 == 0: res += nums[i] else: res -= nums[i] return abs(res)
# https://leetcode.com/problems/unique-binary-search-trees/ # Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? class Solution: def numTrees(self, n: int) -> int: self.d = {1:1,0:0} def bst(n): if n in self.d: return self.d[n] else: i, result = 0, 0 while i < n: ln, rn = i, n - 1 - i left, right = bst(ln), bst(rn) self.d[ln] = left self.d[rn] = right if left != 0 and right != 0: result += left * right else: result += left + right i += 1 return result return bst(n)
""" https://leetcode.com/problems/odd-even-linked-list/ Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head or not head.next: return head oddLL = head evenLL = head2 = head.next while evenLL and evenLL.next: oddLL.next = oddLL.next.next oddLL = oddLL.next evenLL.next = evenLL.next.next evenLL = evenLL.next oddLL.next = head2 return head
""" https://leetcode.com/problems/01-matrix/ Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. """ class Solution: def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]: if not matrix or not matrix[0]: return matrix rows = len(matrix) cols = len(matrix[0]) visited = [[0 for i in range(cols)] for j in range(rows)] queue = [] for i in range(rows): for j in range(cols): if matrix[i][j] == 0: visited[i][j] = 1 if i > 0 and matrix[i - 1][j] == 1 and visited[i - 1][j] == 0: queue.append([i - 1, j]) visited[i - 1][j] = 1 if j > 0 and matrix[i][j - 1] == 1 and visited[i][j - 1] == 0: queue.append([i, j - 1]) visited[i][j - 1] = 1 else: if (i > 0 and matrix[i - 1][j] == 0) or \ (j > 0 and matrix[i][j - 1] == 0): queue.append([i, j]) visited[i][j] = 1 while queue: i,j = queue.pop(0) if i > 0 and visited[i - 1][j] == 0: visited[i - 1][j] = 1 matrix[i - 1][j] += matrix[i][j] queue.append([i - 1,j]) if i < rows - 1 and visited[i + 1][j] == 0: visited[i + 1][j] = 1 matrix[i + 1][j] += matrix[i][j] queue.append([i + 1,j]) if j > 0 and visited[i][j - 1] == 0: visited[i][j - 1] = 1 matrix[i][j - 1] += matrix[i][j] queue.append([i,j - 1]) if j < cols - 1 and visited[i][j + 1] == 0: visited[i][j + 1] = 1 matrix[i][j + 1] += matrix[i][j] queue.append([i,j + 1]) return matrix
""" https://leetcode.com/problems/power-of-two/ Given an integer, write a function to determine if it is a power of two. """ class Solution: def isPowerOfTwo(self, n: int) -> bool: if n <= 0: return False x = math.log10(n) / math.log10(2) return x.is_integer()
""" Write a program to find the node at which the intersection of two singly linked lists begins. Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory. Method 1: Two while loops to match the heads O(n^2) Method 2: use 2 hashmap to store pointer to each node for Linkedlist A & B and check the incoming node in the other hashmap i.e. check node from LL-A in hashmap of B. O(n) time and additional memory for hashmap Method 3: iterate both the LL in one loop and calculate the difference in length. start the longer LL from the difference value. O(n) time and O(1) memory """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: currA = headA currB = headB while currA and currB: currA = currA.next currB = currB.next counter = short = long = None if currA: counter = currA short, long = headB, headA else: counter = currB short, long = headA, headB while counter: long = long.next counter = counter.next while long and short: if long == short: return long long = long.next short = short.next return None
# https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ # Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: result = defaultdict(list) if not root: return [] queue = deque() queue.append([root, 0]) while queue: node, level = queue.popleft() if node: result[level].append(node.val) queue += [[node.left, level + 1], [node.right, level + 1]] return result.values()
""" https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. """ class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 minimum = prices[0] maximum = prices[0] profit = 0 for price in prices[1:]: if minimum > price: profit = max(profit, maximum - minimum) minimum = price maximum = 0 continue maximum = max(maximum, price) return max(profit, maximum - minimum)
""" https://leetcode.com/problems/ransom-note/ Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Note: You may assume that both strings contain only lowercase letters. """ class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: if not magazine and ransomNote: return False d = defaultdict(int) for c in magazine: d[c] += 1 for r in ransomNote: if d[r] > 0: d[r] -= 1 else: return False return True
# https://leetcode.com/problems/power-of-four/ # Given an integer (signed 32 bits), write a function to check whether it is a power of 4. class Solution: def isPowerOfFour(self, num: int) -> bool: if num < 1: return False return log(num, 4).is_integer()
""" https://leetcode.com/problems/largest-divisible-subset/ Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. If there are multiple solutions, return any subset is fine. """ class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: if not nums: return nums nums.sort() d = defaultdict(list) result = [] for num in nums: arr = [] for key in d: if num % key == 0 and len(d[key]) > len(arr): arr = [] + d[key] arr.append(num) d[num] = arr return d[sorted(d, key = lambda x : -len(d[x]))[0]]
""" https://leetcode.com/problems/jump-game/ Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. """ class Solution: def canJump(self, nums: List[int]) -> bool: if len(nums) == 1: return True n = len(nums) maximum = 0 for i in range(n): if i > maximum: return False if maximum >= n - 1: return True if i + nums[i] > maximum: maximum = i + nums[i] return False
""" https://leetcode.com/problems/bitwise-and-of-numbers-range/ Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. """ class Solution: def rangeBitwiseAnd(self, m: int, n: int) -> int: if m == 0 or m == n: return m if len(bin(m)) != len(bin(n)): return 0 mb = f"{m:#033b}" nb = f"{n:#033b}" result = 0 while mb.find('1') == nb.find('1'): pos = mb.find('1') msb = 32 - pos msbint = pow(2, msb) result += msbint m = m - msbint n = n - msbint mb = f"{m:#033b}" nb = f"{n:#033b}" return result
""" Return the root node of a binary search tree that matches the given preorder traversal. (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ if not preorder: return None root = TreeNode(preorder.pop(0)) i = 0 while i < len(preorder) and preorder[i] < root.val: i += 1 root.left = self.bstFromPreorder(preorder[:i]) root.right = self.bstFromPreorder(preorder[i:]) return root
""" https://leetcode.com/problems/linked-list-cycle-ii/ Given a linked list, return the node where the cycle begins. If there is no cycle, return null. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. Note: Do not modify the linked list. Follow-up: Can you solve it without using extra space? """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: slow = fast = head flag = False while fast and fast.next: slow = slow.next fast = fast.next.next if fast == slow: flag = True break if flag: slow = head while slow: if slow == fast: return slow slow, fast = slow.next, fast.next
""" https://leetcode.com/problems/sort-colors/ Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. """ class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) pos, left, right = 0, 0, n-1 while pos <= right: num = nums[pos] if num == 0: nums[pos] = nums[left] nums[left] = 0 left += 1 pos += 1 elif num == 2: nums[pos] = nums[right] nums[right] = 2 right -= 1 else: pos += 1 """ Another Solution n = len(nums) i = 0 for x in range(n): if nums[i] == 2: nums.pop(i) nums.append(2) continue elif nums[i] == 0: nums.pop(i) nums.insert(0, 0) i += 1 """
# https://leetcode.com/problems/robot-bounded-in-circle/ # On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: # "G": go straight 1 unit; # "L": turn 90 degrees to the left; # "R": turn 90 degress to the right. # The robot performs the instructions given in order, and repeats them forever. # Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. class Solution: def isRobotBounded(self, instructions: str) -> bool: vector, direction = [0, 0], 'N' d = {'N' : [[0, 1], 'W', 'E'], 'W' : [[-1, 0], 'S', 'N'], 'S' : [[0, -1], 'E', 'W'], 'E' : [[1, 0], 'N', 'S']} for ch in instructions: if ch == 'G': v = d[direction][0] vector[0] += v[0] vector[1] += v[1] elif ch == 'R': direction = d[direction][2] else: direction = d[direction][1] if direction != 'N' or vector == [0, 0]: return True return False
# https://leetcode.com/problems/number-of-recent-calls/ # You have a RecentCounter class which counts the number of recent requests within a certain time frame. # Implement the RecentCounter class: # RecentCounter() Initializes the counter with zero recent requests. # int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t]. # It is guaranteed that every call to ping uses a strictly larger value of t than the previous call. class RecentCounter: def __init__(self): self.pings, self.count = [], 0 def ping(self, t: int) -> int: self.pings.append(t) self.count += 1 while self.pings: if self.pings[0] < t - 3000: self.count -= 1 self.pings.pop(0) else: break return self.count # Your RecentCounter object will be instantiated and called as such: # obj = RecentCounter() # param_1 = obj.ping(t)
""" https://leetcode.com/problems/subsets/ Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. """ class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: result = [[]] arr = [] for num in nums: arr.extend(result) for r in arr: if r: result.append(r + [num]) else: result.append([num]) arr = [] return result
# https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ # Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. # For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. # Return the sum of these numbers. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: self.total = 0 def dfs(s: str, root: TreeNode): if not root: return ch = str(root.val) if not root.left and not root.right: self.total += int(s + ch, 2) return dfs(s + ch, root.left) dfs(s + ch, root.right) dfs('', root) return self.total
def grade(num, rank): import math n = math.ceil(rank / (num / 10)) if(n == 1): return "A+" elif(n == 2): return "A0" elif(n == 3): return "A-" elif(n == 4): return "B+" elif(n == 5): return "B0" elif(n == 6): return "B-" elif(n == 7): return "C+" elif(n == 8): return "C0" elif(n == 9): return "C-" else: return "D0" T = int(input()) for i in range(T): N, K = map(int, input().split()) score = [] for idx, j in enumerate(range(N),1): mid, fin, proj = map(int, input().split()) total = mid * 0.35 + fin * 0.45 + proj * 0.2 score.append([total,idx]) score.sort(reverse=True) for j in range(len(score)): if(score[j][1] == K): print(f"#{i+1} {grade(N,j+1)}")
import random class Poketmon(): def __init__(self, name, lv): self.name = name self.lv = lv self.hp = random.randint(100,150) * lv self.power = random.randint(1,5) * lv self.speed = random.randint(1,4) * lv def fight(self, enemy): for i in range(100): if(i%2): print(f"{enemy.name}이 {enemy.power*enemy.speed}만큼 공격합니다") self.hp -= enemy.power*enemy.speed else: print(f"{self.name}이 {self.power*self.speed}만큼 공격합니다") enemy.hp -= self.power*self.speed if(self.hp<0): self.hp = 0 print(f"{self.name}의 체력이 {self.hp}이 되었습니다") print(f"{enemy.name}이 이겼습니다. {enemy.hp}이 남았습니다") break elif(enemy.hp<0): enemy.hp = 0 print(f"{self.name}의 체력이 {self.hp}이 되었습니다") print(f"{enemy.name}이 이겼습니다. {enemy.hp}이 남았습니다") break p1 = Poketmon("피까쮸",5) p2 = Poketmon("파이리",5) print(p1.name, p1.hp, p1.power) print(p2.name, p2.hp, p2.power) p1.fight(p2)
''' Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops. ''' def count_th(word): sub = "th" # the sub string, technically it should be pass into the function as an attribute len_word = len(word) # find the length of both the word and string for base cases len_sub = len(sub) # let's set the base case i.e. if len(word) == 0 and len_word < len_sub: # simplest base case that if the length of the word is less than the string, return 0 # we return 0 if word[0:len_sub] == sub: # if we go through the word were in word, we have the string present return count_th(word[len_sub-1:]) + 1 # we do the recursive call to the function until it reaches the base case # and then, as we find one instance, we add 1 and if we find another one, we add another return count_th(word[len_sub-1:]) # we can only go -1 because of the lenght of the substring. If we have a bigger substring, # we have to do negative 2, otherwise it won't iterate through the whole word and would only print the first instance # of the substring word = "thethemthem" print(word[0:2]) print(count_th(word))
# Exercise 1 def get_list(L): return L # Exercise 2.1 def get_sum_of_elements_in_list_with_for_loop(L): sum = 0 for k in range(len(L)): sum = sum + L[k] return sum # Exercise 2.2 def get_sum_of_elements_in_list_with_while_loop(L): sum = 0 i = 0 while i < len(L): sum += L[i] i += 1 return sum # Exercise 3.1 def repetitions(x, k): L = [] for i in range(k): L.append(x) return L # Exercise 3.2 def repetition_block(L, k): new_L = [] for i in range(k): for j in range(len(L)): new_L.append(L[j]) return new_L # Exercise 4 def number_of_occurrences(L, element): occ = 0 for k in range(len(L)): if L[k] == element: occ += 1 return occ # Exercise 5 def max__element_in_list(L): max = L[0] for i in range(len(L)): if L[i] > max: max = L[i] return max
# 3. Longest Substring Without Repeating Characters # Given a string, find the length of the longest substring without repeating characters. # Examples: # Given "abcabcbb", the answer is "abc", which the length is 3. # Given "bbbbb", the answer is "b", with the length of 1. # Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. class MyString: def __init__(self, s): self.content = s def distSubstring(self): result = [] temp = [] for c in self.content: if c in temp: if len(temp) > len(result): result = temp idx = temp.index(c) temp = temp[idx+1:len(result)] temp.append(c) return "".join(result) def main(): myString = MyString("pwwkew") print(myString.distSubstring()) if __name__ == "__main__": main()
# Vanessa Koelling, August 11th, 2017. This document contains some notes and code examples in Python 3 from "Python for Biologists". # Chapter 6 notes # conditional tests print(3 == 5) print(3 > 5) print(3 <= 5) print(len("ATGC") > 5) print("GAATTC".count("T") > 1) print("ATGCTT".startswith("ATG")) print("ATGCTT".endswith("TTT")) print("ATGCTT".isupper()) print("ATGCTT".islower()) print("V" in ["V", "W", "L"]) # equals '==' # greater than '>' # less than '<' # greater than or equal to '>=' # less than or equal to '<=' # not equal '!=' # is a value in a list 'in' # are two objects the same 'is' # if/else, and elif statements expression_level = 125 if expression_level > 100: print("gene is highly expressed") else: print("gene is lowly expressed") file1 = open("one.txt", "w") file2 = open("two.txt", "w") file3 = open("three.txt", "w") accs = ['ab56', 'bh84', 'hv76', 'ay93', 'ap97', 'bd72'] for accession in accs: if accession.startswith('a'): file1.write(accession + "\n") elif accession.startswith('b'): file2.write(accession + "\n") else: file3.write(accession + "\n") # while loops count = 0 while count < 10: print(count) count = count + 1 # building up complex conditions # using boolean operators: and/or/not accs = ['ab56', 'bh84', 'hv76', 'ay93', 'ap97', 'bd72'] for accession in accs: if accession.startswith('a') and accession.endswith('3'): print(accession) accs = ['ab56', 'bh84', 'hv76', 'ay93', 'ap97', 'bd72'] for accession in accs: if accession.startswith('a') or accession.endswith('3'): print(accession) accs = ['ab56', 'bh84', 'hv76', 'ay93', 'ap97', 'bd72'] for accession in accs: if (accession.startswith('a') or accession.startswith('b')) and accession.endswith('4'): print(accession) # parentheses added around the or statement to avoid ambiguity accs = ['ab56', 'bh84', 'hv76', 'ay93', 'ap97', 'bd72'] for accession in accs: if accession.startswith('a') and not accession.endswith('6'): print(accession) # writing true/false functions def is_at_rich(dna): length = len(dna) a_count = dna.upper().count('A') t_count = dna.upper().count('T') at_content = (a_count + t_count)/length if at_content > 0.65: return True else: return False print(is_at_rich("ATTATCTACTA")) print(is_at_rich("CGGCAGCGCT")) # alternative, more concise version def is_at_rich(dna): length = len(dna) a_count = dna.upper().count('A') t_count = dna.upper().count('T') at_content = (a_count + t_count)/length return at_content > 0.65
# Vanessa Koelling, August 11th, 2017. # Chapter 6, exercise 4: complex condition input_file = open("/Users/vkoelling/Desktop/Python_practice_files/Python_for_Biologists_exercises_and_examples/Chapter_6/exercises/data.csv") for row in input_file: new_row = row.rstrip("\n").split(",") species = new_row[0] sequence = new_row[1] gene_name = new_row[2] expression_level = new_row[3] if (gene_name.startswith('k') or gene_name.startswith('h')) and not species == "Drosophila melanogaster": print(gene_name)
# Vanessa Koelling, August 9th, 2017. # Ch. 4 exercise 2: Multiple exons from genomic DNA # open the genomic DNA file genomic_dna = open("/Users/vkoelling/Desktop/Python_practice_files/Python_for_Biologists_exercises_and_examples/Chapter_4/exercises/genomic_dna.txt") # read the contents of the file into a new variable seq = genomic_dna.read() # open the exon positions file exons = open("/Users/vkoelling/Desktop/Python_practice_files/Python_for_Biologists_exercises_and_examples/Chapter_4/exercises/exons.txt") # open a new file called coding_seq coding_seq = open("coding_seq.txt", "w") # loop writes the exons to the new file for exon in exons: exon_position = exon.split(",") # create a list out of the first set of exon positions exon_start = int(exon_position[0]) # index the list and convert the string to an integer exon_stop = int(exon_position[1]) exon_seq = seq[exon_start:exon_stop] # get the exon sequence coding_seq.write(exon_seq) # write the exon sequence to a new file coding_seq.close()
#encoding=utf-8 #!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should explore features_dict as part of the mini-project, but here's an example to get you started: enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 """ import pickle enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r")) """ Quiz 1 """ print("數據集中一共有 %d 個人的資料" % len(enron_data)) #146 """ Quiz 2 """ vs = enron_data.values() print("每個人共有 %d 個特徵可以使用" % len(vs[0])) #21 """ Quiz 3 """ poi_num = 0 for p in vs: if p["poi"] == 1: poi_num += 1 print("在安然數據集的嫌疑人一共有 %d 個" % poi_num) #18 """ Quiz 4 """ poi_all = open("../final_project/poi_names.txt",'r') poi_all_num = 0 # 資料格式 # (y/n) Name for line in poi_all: poi_all_num += 1 poi_all_num -= 2 # 去除描述列 print("但是在我們自己準備的資料集裡,一共有 %d 個嫌疑人" % poi_all_num) print("也就是我們準備的資料集,與安然資料集並不一致") """ Quiz 5 James Prentice 名下的股票总值是多少? """ #請注意一下,格式是LASTNAME FIRSTNAME MIDDLENAME #所以會找的是 Prentice James print("James Prentice 名下股票總值: %d" % enron_data["PRENTICE JAMES"]["total_stock_value"]) #1095040 """ Quiz 6 我们有多少来自 Wesley Colwell 发给嫌疑人的电子邮件? """ print("有 %d 封 Wesley Colwell 發給嫌疑人的郵件" % enron_data["COLWELL WESLEY"]["from_this_person_to_poi"]) #11 """ Quiz 7 Jeffrey Skilling 行使的股票期权价值是多少? """ print("Jeff Skilling's exercised stock options: %d" % enron_data["SKILLING JEFFREY K"]["exercised_stock_options"]) """ Quiz 8 此数据集中有多少雇员有量化的工资?已知的邮箱地址是否可用? """ ava_email_num = 0 ava_salary_num = 0 nava_total_payments_num = 0. nava_total_payments_poi_num = 0. for v in vs: if v["email_address"] != "NaN": ava_email_num += 1 if v["salary"] != "NaN": ava_salary_num += 1 if v["total_payments"] == "NaN": nava_total_payments_num += 1 if v["poi"]: nava_total_payments_poi_num += 1 print("有效郵件計數共有: %d" %ava_email_num) #111 print("有效薪水計數共有: %d" %ava_salary_num) #95 """ Quiz 9 (当前的)E+F 数据集中有多少人的薪酬总额被设置了“NaN”?数据集中这些人的比例占多少? """ print("數據集中total_payments被設為NaN的比例為:%f" % (nava_total_payments_num/float(len(vs)))) #0.14 (14%) print("數據集中total_payments被設為NaN且為Poi的比例為:%f" % (nava_total_payments_poi_num/float(len(vs)))) #ITS ZERO !
#creates folder for each file specified as second argument #the folder has the same name of the file, but has no extension and the first letter is lower import subprocess import sys argvalues = sys.argv if(len(argvalues) > 1): directory=sys.argv[1] if(directory[len(directory)-1] != '/'): directory+='/' else: directory="./" print directory filename=directory+"tmp_file" #sends ls output to a temporary file with open(filename, 'w+') as f: p=subprocess.Popen(['ls', '-p', directory], stdout=f) p.communicate() f.seek(0) ls_output = f.read() #saves output to ls_output ls_output=ls_output.split("\n") working_files=[] for line in ls_output: if ('/' in line or '.py' in line or "tmp_file" in line): #this line is a folder pass else: working_files.append(line) import os #now working_files contains all files that must be moved to a new folder for elem in working_files: if(len(elem) < 1): break elif(elem[0].islower() and '.' not in elem): print(elem+" won't be moved") continue package_name_str=elem[0].lower()+elem[1:] package_name = package_name_str.split(".")[0] os.mkdir(directory+package_name) subprocess.Popen(["mv", directory+elem, directory+package_name+"/"]) subprocess.Popen(["rm", filename])