text
stringlengths
37
1.41M
import random n = int(input("Enter a number: ")) a = [[0] * n for i in range(n)] qpos = [0]*n # putting '.' characters in nxn cells for i in range(n): for j in range(n): a[i][j] = '.' # putting randomly n number of queens in n coloumns # so there is one queen in every row. # but there can be multiple queens in one row. becasue the row is chosen randomly # and then stored the row number where queen exits in qpos[] list for j in range(n): i = random.randint(0,n-1) a[i][j] = 'X' qpos[j] = i # the row number of every col of queen position # this function will count and the return the no of violation of the rth row and cth coloumn queen. # by violation I mean how many queen are this queen attacking from that rth row and cth coloumn position. def violations(r,c): count = -1 leftDiagonal = r+c rightDiagonal = r-c for i in range(n): for j in range(n): if ((i+j) == leftDiagonal or (i-j) == rightDiagonal or i == r or j==c) and (a[i][j]=='X'): count = count + 1 return count sum = 1 # first i am finding which coloumn's queen is attacking maximum number of queen # then i am changing that queen's row position in that coloumn # to where it is attacking less number of queen from it's previous position # and in every iteration i am calculating the sum of all the violations(number of queens the queen is attacking) of every queen. # until that sum is zero meaning no queen is attacking any other queen the loop will continue while sum != 0: sum = 0 maxViolation = 0 col = 0 row = 0 # here I a looping through every coloumn to find out # Queen of which coloumn is attacking maximum number of queen from it's current position. for j in range(n): temp = violations(qpos[j],j) sum = sum + temp if temp > maxViolation: maxViolation = temp col = j #Queen of which coloumn has the max violations # if more than one queen is attacking maximum no of queens then i am choosing one of them randomly t = random.randint(0,2) if temp == maxViolation and t == 0: maxViolation = temp col = j a[qpos[col]][col] = '.' # now i am changing that queen's row position in that coloumn to minimize the violations minViolation = n+1 for i in range(n): a[i][col] = 'X' temp = violations(i,col) if temp < minViolation: minViolation = temp row = i # again if the queen is attacking same minimum no of queens from different row position # then i am choosing one of the row randomly t1 = random.randint(0,2) if temp == minViolation and t1 == 0: minViolation = temp row = i a[i][col] = '.' qpos[col] = row # here i am changing the queen position to a row # where it is attacking less number of queen from it's previous position a[row][col] = 'X' # printing the queen's position in chess board where no queen is attacking each other. for i in range(0,n): for j in range(0,n): print(" ",a[i][j],end='') print()
def gettoday(today): ''' 请按此格式输入今天的日期(2019-3-25) ''' # today = input("请按此格式输入今天的日期(2019-3-25):") todaylist = today.split("-") try: year = int(todaylist[0]) month = int(todaylist[1]) day = int(todaylist[2]) except: print("输入的格式不正确,异常退出!!") exit() if month > 12: print("请输入正确的月份!!!") exit() monthlist = [31,28,31,30,31,30,31,31,30,31,30,31] if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): monthlist[1] = 29 res = 0 for i in range(month-1): res += monthlist[i] res = res + day print("今天是%d年的第%d天!" % (year, res)) def total(a): ''' 说明:用来计算输入的字符串的长度, a 就是传入的字符串的变量 ''' lang = len(a) print('这段话一共有',lang,'个字!!') def printnum(a): ''' 题目: 定义一个方法,这个方法的功能是输入一个数字,比如5,那么会打印出一个三角形, 格式如下: 1 22 333 4444 55555 ''' for i in range(1,a+1): print(i*str(i)) ''' @全体成员 今天的作业1: http://www.runoob.com/quiz/python-quiz.html 做下简单的选择题。 2、编程练习。 2.1 设计一个方法,这个方法的功能是,输入一个四位数,计算各个位数的和。如1234,输出结果为10。 2.2 设计一个方法,这个方法的功能是,输入账号密码进行登录,登录成功后,可以进行学生信息的添加,将添加的学生信息存到字典里。添加结束后,打印结果。如果账号密码不对,则直接退出程序。 '''
# Shirt Count and Shirt Register shirt_count = 0 shirt_size = "" small = 0 medium = 0 large = 0 small_size_price = 6 medium_size_price = 7 large_size_price = 8 total_small_price = 0 total_medium_price = 0 total_large_price = 0 total_price = 0 while True: shirt_size = input("Enter the size of shirt (S, M, L) or enter exit to exit the program: ") if shirt_size.lower() == "exit": print() break elif shirt_size.upper() == "S": small += 1 elif shirt_size.upper() == "M": medium += 1 elif shirt_size.upper() == "L": large += 1 else: print("Not a valid size: Counted as a medium shirt size M") medium += 1 shirt_count += 1 total_small_price = small*small_size_price total_medium_price = medium*medium_size_price total_large_price = large*large_size_price total_price = total_small_price + total_medium_price + total_large_price print("Total shirts = ", shirt_count, "\nSmall shirts = ", small, "\nMedium shirts = ", medium, "\nLarge shirts = ", large) print("Total shirt price = ", total_price, "\nTotal Small S size price = ", total_small_price, "\nTotal Medium M size price = ", total_medium_price, "\nTotal Large L size price = ", total_large_price)
# Weekday Function - Date Time Formatting # [ ] Complete the function `weekday` to return the weekday name of `some_date` # Use the function to find the weekday on which you were born from datetime import date def weekday(some_date): formatted_string = some_date.strftime("%A") return formatted_string # Modify to your birthdate bd = date(day=5, month=4, year=1985) # Display the day on which you were born day = weekday(bd) print(day)
# [ ] review the code, run, fix the error tickets = int(input("enter tickets remaining (0 to quit): ")) while tickets > 0: # if tickets are multiple of 3 then "winner" if int(tickets/3) == tickets/3: print("you win!") break else: print("sorry, not a winner.") tickets = int(input("enter tickets remaining (0 to quit): ")) print("Game ended")
# find and display the index of all the letter i's in code_tip code_tip = "code a conditional decision like you would say it" location = code_tip.find("i") while location >= 0: print(location) location = code_tip.find("i", location + 1)
# Assigning a datetime object from datetime import datetime # July 4th 2022, at 4:30 PM # Method 1 dt = datetime(2022, 7, 4, 16, 30) print("Method 1: ", dt) # Method 2 dt = datetime(day = 4, month = 7, year = 2022, minute = 30, hour = 16) print("Method 2: ", dt) # Getting a datetime attribute from datetime import datetime # July 4th 2022, at 4:30 PM dt = datetime(2022, 7, 4, 16, 30) # access year print("Year is: ", dt.year) # access minute print("Minute is: ", dt.minute)
# Combining separate date and time objects into a datetime object from datetime import datetime, time, date # assign a time object t = time(hour = 6, minute = 45, second = 0) # assign a date object d = date.today() # combine t and d into a datetime object dt = datetime.combine(date = d, time = t) print(dt)
# Read Write Append to a File # Location: C:\Users\N\PycharmProjects\Python Fundamentals # Instead of .txt, .doc or .xls file can be also created in the same way # Create a local log file log_file = open('log-file.txt', 'w') # log_file = open('log-file.doc', 'w') # log_file = open('log-file.xls', 'w') log_file.close() # Enter data input for log file from user using a function log_file = open('log_file.txt', 'a+') # log_file = open('log_file.doc', 'a+') # log_file = open('log_file.xls', 'a+') def logger(log): log_entry = input("enter log item (press enter to quit): ") count = 0 while log_entry: count += 1 log.write(str(count) + ": " + log_entry + "\n") log_entry = input("enter log item (press enter to quit): ") return count num_logs = logger(log_file) # Seek pointer to beginning of file and print everything in the file log_file.seek(0) log_text = log_file.read() print("\n Number of logs entered: ", num_logs, "\n") print(log_text) log_file.close()
# Find out if you are closer to the current year's June or December solstice from datetime import datetime, timedelta import math now = datetime.today() december_solstice = datetime(month = 12, day = 21, year = now.year) june_solstice = datetime(month = 6, day = 21, year = now.year) time_to_jun = june_solstice - now time_jun = time_to_jun.days time_jun = math.fabs(time_jun) time_to_dec = december_solstice - now time_dec = time_to_dec.days time_dec = math.fabs(time_dec) print("June: ", time_jun) print("December: ", time_dec) if time_jun < time_dec: print("June solstice is closer") elif time_jun > time_dec: print("December solstice is closer") else: print("Both are equally close, and is", time_jun, "days before and after from today")
# [ ] using range(start,stop) - print the 3rd, 4th and 5th words in spell_list # output should include "February", "November", "Annual" spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"] for item in range(2, 5): print(spell_list[item]) # [ ] using code find the index of "Annual" in spell_list # [ ] using range, print the spell_list including "Annual" to end of list spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"] for item in range(7): if spell_list[item] == "Annual": print("Index of 'Annual' is: ", item) spell_list.remove("Annual") spell_list.append("Annual") print(spell_list)
# Practice Task 4E: Birthday days # Write a program to display a list of all your birthdays from the day you were born till 2025. # You should also show the weekdays so you can see which of them was (or will be) on a weekend from datetime import datetime for yr in range(1985, 2026): birthday = datetime(month = 4, day = 5, year = yr) print(birthday.strftime("%A, %d %B, %Y"))
# Program: Words after "G"/"g" # prints all of the words that start with h-z quote = input("Enter a famous quote: ") quote = quote + " " word = "" start = 0 space_index = quote.find(" ") while space_index >= 0: for letter in quote[start:space_index]: word += letter if word[0].lower() > "g": print(word.upper()) word = "" start = space_index + 1 space_index = quote.find(" ", space_index + 1) '''for letter in quote[start:]: word += letter if word[0].lower() > "g": print(word) '''
# Cash Register Input purchase_amounts = [] item_price = input('Enter price of items or "done" to exit: ') while True: if item_price.lower() == "done": break else: purchase_amounts.append(item_price) item_price = input('Enter price of items or "done" to exit: ') print(purchase_amounts)
# Pick a candy # In this exercise, you will write a program to randomly select a candy from a box. # [ ] Complete the function `pick_candy` so it returns a candy from box at random from random import choice def pick_candy(): box = ["Taffy", "Brownie", "Cookie", "Candy bar", "Chocolate", "Lollipop", "Gingerbread", "Marshmallow"] return choice(box) print(pick_candy())
# Path Operations - Check if Absolute Path, If File or Path, If file exists import os os.chdir('parent_dir') print("Current working directory", os.getcwd()) abs_path = os.path.abspath('child1_dir/leaf1.txt') print("Absolute path to leaf1.txt is: ", abs_path) # Test if the path exists if os.path.exists(abs_path): print("Path Exists") # Test to see if it is a file or a directory if os.path.isfile(abs_path): print("It's a file") elif os.path.isdir(abs_path): print("It's a dir") else: print("Path doesn't exist")
# City Initials !curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/cities -o cities.txt cities_file = open('cities.txt', "r") cities = cities_file.read() initials = "" for letter in cities: if letter.isupper(): initials += letter elif letter == "\n": initials += letter print(initials)
"""Channels a stream of tweets matching a given term or terms to a JSON file. Usage: python3 stream.py term1 term2 ... termN [prefix] The output file will be [prefix].json Note: the term arguments should be put in quotes to deal with hashtags """ from twitter import * from http.client import IncompleteRead import sys class TweetListener(tw.streaming.StreamListener): """StreamListener that channels tweets to a JSON file.""" def __init__(self, pref = None): """[pref].json will be the filename to which to channel tweets. If pref = None, does not save the tweets, only displays them.""" super(TweetListener, self).__init__() self.pref = pref def on_data(self, data): try: tweet = Tweet.parse(api, json.loads(data)) print(tweet) if (self.pref is not None): with open('%s.json' % self.pref, 'a') as f: f.write(data) return True except BaseException as e: print('Error on_data: %s' % str(e)) return True def on_error(self, status): print(status) return True # don't kill the stream def on_timeout(self): print("Timeout...") return True # don't kill the stream def channel_tweets(terms, pref = None): """Channels tweets with the given terms to the screen, and if pref != None, to a file named [pref].json.""" if (not isinstance(terms, list)): terms = [terms] stream = tw.Stream(auth, TweetListener(pref)) while True: try: stream.filter(track = terms) except IncompleteRead: # oh well, just keep on trucking continue except KeyboardInterrupt: stream.disconnect() break def main(): nargs = len(sys.argv) - 1 assert (nargs >= 2) terms = sys.argv[1:-1] prefix = sys.argv[-1] channel_tweets(terms, prefix) if __name__ == "__main__": main()
num1 = int(input('Digite o primeiro número inteiro: ')) num2 = int(input('Digite o segundo número inteiro: ')) if num1 > num2: print('O número {} é maior que o número {}'.format(num1, num2)) elif num1 < num2: print('O número {} é maior que o número {}'.format(num2, num1)) else: print('Ambos os números são iguais!')
from datetime import date ano = date.today().year print(ano) num = 5 % 2 num2 = 9 % 2 num3 = 4 % 2 num4 = 1 % 2 num5 = 4 % 2 print(num, num2, num3, num4, num5) from random import randint num6 = randint(1, 6) res = num // 2 res2 = 5 // 2 print(res2) print(res) texto = ('Tres Pratos de Trigo para Tigres Tristes') total = texto.upper().count(texto[0]) print(total)
salario = float(input('Qual é o salário do funcionário? ')) if salario > 1250: print('O reajuste é de R$ {}. Sendo assim o salário do funcionário passa a ser R$ {}'.format((salario * 0.10), ( (salario * 0.10) + salario))) else: print('O reajuste é de R$ {}. Sendo assim o salário do funcionário passa a ser R$ {}'.format((salario * 0.15), ( (salario * 0.15) + salario)))
import math peso = float(input('Digite o peso: ')) altura = float(input('Digite a altura: ')) alturaAoQuadrado = float(pow(altura,2)) imc = peso/alturaAoQuadrado if imc <= 18.5: print('Abaixo do peso') elif imc >= 18.6 and imc <= 25: print('Peso ideal') elif imc >= 25.1 and imc <= 30: print('Sobrepeso') elif imc >= 30.1 and imc <= 40: print('Obesidade') elif imc >= 40.1: print('Obesidade mórbida')
num1 = float(input('Digite um número: ')) num2 = float(input('Digite outro número: ')) num3 = float(input('Digite mais um número: ')) if num1 > num2 and num1 > num3: if num2 < num3: print('O maior número digitado é o {} e o menor é o {}'.format(num1, num2)) else: print('O maior número digitado é o {} e o menor é o {}'.format(num1, num3)) if num2 > num1 and num2 > num3: if num3 < num1: print('O maior número digitado é o {} e o menor é o {}'.format(num2, num3)) else: print('O maior número digitado é o {} e o menor é o {}'.format(num2, num1)) if num3 > num1 and num3 > num2: if num2 < num1: print('O maior número digitado é o {} e o menor é o {}'.format(num3, num2)) else: print('O maior número digitado é o {} e o menor é o {}'.format(num3, num1))
velocidadeCarro = float(input('Digite a velocidade do carro: ')) multa = float(velocidadeCarro - 80) * 7 if velocidadeCarro > 80: print('O carro está acima do limite de velocidade!!!') print('A multa por essa negligência é R$ {}'.format(multa)) else: print('O carro está dentro do limite permitido de velocidade')
nota1 = float(input('Digite a primeira nota do aluno: ')) nota2 = float(input('Digite a segunda nota do aluno: ')) media = float((nota1+nota2)/2) if media<5 and media > 0: print('Aluno reprovado! :(') elif media >=5 and media <= 6.9: print('O aluno está de recuperação.') elif media >= 7 and media <= 10: print('Aluno está aprovado! :)') else: print('Média maior que 10 ou menor que 0. Favor rever notas digitadas. As notas não podem ser maior que 10 ou menor que 0.')
# coding: utf-8 # Começando com os imports import csv import matplotlib.pyplot as plt from datetime import datetime # Vamos ler os dados como uma lista print("Lendo o documento...") with open("chicago.csv", "r") as file_read: reader = csv.reader(file_read) data_list = list(reader) print("Ok!") # Vamos verificar quantas linhas nós temos print("Número de linhas:") print(len(data_list)) # Imprimindo a primeira linha de data_list para verificar se funcionou. print("Linha 0: ") print(data_list[0]) # É o cabeçalho dos dados, para que possamos identificar as colunas. # Imprimindo a segunda linha de data_list, ela deveria conter alguns dados print("Linha 1: ") print(data_list[1]) input("Aperte Enter para continuar...") # TAREFA 1 # TODO: Imprima as primeiras 20 linhas usando um loop para identificar os dados. print("\n\nTAREFA 1: Imprimindo as primeiras 20 amostras") # Vamos mudar o data_list para remover o cabeçalho dele. data_list = data_list[1:] ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Para imprimir as primeira 20 amostras optei por usar um for simples com range de 0 a 20 e utilizei o indice i parar numerar a listas ''' for i in range(0,20): print("{} - ".format(i+1),data_list[i]) # Nós podemos acessar as features pelo índice # Por exemplo: sample[6] para imprimir gênero, ou sample[-2] input("Aperte Enter para continuar...") # TAREFA 2 # TODO: Imprima o `gênero` das primeiras 20 linhas print("\nTAREFA 2: Imprimindo o gênero das primeiras 20 amostras") ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Seguindo o padrão da questão anterior para imprimir a coluna referente a ogenero indiquei o indice da coluna 6 ''' for i in range(0,20): print("{} - ".format(i+1),data_list[i][6]) # Ótimo! Nós podemos pegar as linhas(samples) iterando com um for, e as colunas(features) por índices. # Mas ainda é difícil pegar uma coluna em uma lista. Exemplo: Lista com todos os gêneros input("Aperte Enter para continuar...") # TAREFA 3 # TODO: Crie uma função para adicionar as colunas(features) de uma lista em outra lista, na mesma ordem def column_to_list(data, index): ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Criei a função column_to_list Essa função recebe a lista de dados originais e a percorre coletando os dados da coluna especificada pelo parametro index e adiciona esses valores em uma nova lista que será retornada ao final do processo. Argumentos: data: lista com as amostras coletadas do arquivo index: Indice da coluna cujos dados é desejado criar uma lista. Retorna: Uma lista com os valores da coluna indicada por index. ''' column_list = [] for row in data: column_list.append(row[index]) # Dica: Você pode usar um for para iterar sobre as amostras, pegar a feature pelo seu índice, e dar append para uma lista return column_list # Vamos checar com os gêneros se isso está funcionando (apenas para os primeiros 20) print("\nTAREFA 3: Imprimindo a lista de gêneros das primeiras 20 amostras") print(column_to_list(data_list[:20], -2)) # ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------ assert type(column_to_list(data_list, -2)) is list, "TAREFA 3: Tipo incorreto retornado. Deveria ser uma lista." assert len(column_to_list(data_list, -2)) == 1551505, "TAREFA 3: Tamanho incorreto retornado." assert column_to_list(data_list, -2)[0] == "" and column_to_list(data_list, -2)[1] == "Male", "TAREFA 3: A lista não coincide." # ----------------------------------------------------- input("Aperte Enter para continuar...") # Agora sabemos como acessar as features, vamos contar quantos Male (Masculinos) e Female (Femininos) o dataset tem # TAREFA 4 # TODO: Conte cada gênero. Você não deveria usar uma função para isso. ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Para contabilizar os generos masculino e feminino usei um for que percorrerá a lista retornada pela função column_to_list com index correspondendo a coluna gênero. para cada interação eu verifico se é do genero masculino ou feminino e somo +1 as suas respectivas variaveis caso correspondam a um dos dois grupos. usei o metodo lower para evitar problemas de comparação de string de entrada como por exemplo ("Female" e "female" ou "Male" e "male") ''' male = 0 female = 0 for gender in column_to_list(data_list, 6): if(gender.lower()=="male"): male += 1 elif(gender.lower()=="female"): female += 1 # Verificando o resultado print("\nTAREFA 4: Imprimindo quantos masculinos e femininos nós encontramos") print("Masculinos: ", male, "\nFemininos: ", female) # ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------ assert male == 935854 and female == 298784, "TAREFA 4: A conta não bate." # ----------------------------------------------------- input("Aperte Enter para continuar...") # Por que nós não criamos uma função para isso? # TAREFA 5 # TODO: Crie uma função para contar os gêneros. Retorne uma lista. # Isso deveria retornar uma lista com [count_male, count_female] (exemplo: [10, 15] significa 10 Masculinos, 15 Femininos) def count_gender(data_list): ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Fazendo uso do codigo que criei para o exemplo anterior eu criei a função count_gender que recebe a lista de dados originais e retorna uma lista com o somatório dos gêneros masculino e feminino respctivamente. Argumentos: data_list: lista com as amostras coletadas do arquivo Retorna: Uma lista com os valores do somatório de gêneros masculino e feminino respectivamente. ''' male = 0 female = 0 for gender in column_to_list(data_list, 6): if(gender.lower()=="male"): male += 1 elif(gender.lower()=="female"): female += 1 return [male, female] print("\nTAREFA 5: Imprimindo o resultado de count_gender") print(count_gender(data_list)) # ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------ assert type(count_gender(data_list)) is list, "TAREFA 5: Tipo incorreto retornado. Deveria retornar uma lista." assert len(count_gender(data_list)) == 2, "TAREFA 5: Tamanho incorreto retornado." assert count_gender(data_list)[0] == 935854 and count_gender(data_list)[1] == 298784, "TAREFA 5: Resultado incorreto no retorno!" # ----------------------------------------------------- input("Aperte Enter para continuar...") # Agora que nós podemos contar os usuários, qual gênero é mais prevalente? # TAREFA 6 # TODO: Crie uma função que pegue o gênero mais popular, e retorne este gênero como uma string. # Esperamos ver "Male", "Female", ou "Equal" como resposta. def most_popular_gender(data_list): ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com most_popular_gender recebe a lista original e utilizar count_gender para pegar os somatórios dos gêneros e compara-lós para dizer se um deles é maior ou se são iguais. Argumentos: data: lista com as amostras coletadas do arquivo Retorna: Uma uma string que indica qual dos gêneros tem maior quantidade ou se são iguais "Male","Female" ou "Equal" ''' answer = "" cgender = count_gender(data_list) if(cgender[0] > cgender[1]): answer = "Male" elif(cgender[0] < cgender[1]): answer = "Female" else: answer = "Equal" return answer print("\nTAREFA 6: Qual é o gênero mais popular na lista?") print("O gênero mais popular na lista é: ", most_popular_gender(data_list)) # ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------ assert type(most_popular_gender(data_list)) is str, "TAREFA 6: Tipo incorreto no retorno. Deveria retornar uma string." assert most_popular_gender(data_list) == "Male", "TAREFA 6: Resultado de retorno incorreto!" # ----------------------------------------------------- # Se tudo está rodando como esperado, verifique este gráfico! gender_list = column_to_list(data_list, -2) types = ["Male", "Female"] quantity = count_gender(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantidade') plt.xlabel('Gênero') plt.xticks(y_pos, types) plt.title('Quantidade por Gênero') plt.show(block=True) input("Aperte Enter para continuar...") # TAREFA 7 # TODO: Crie um gráfico similar para user_types. Tenha certeza que a legenda está correta. print("\nTAREFA 7: Verifique o gráfico!") def count_user_type(data_list): ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Baseado na ativida anterior eu criei uma função para contabilizar os tipo de usuarios e gerar um gráfico similar ao exercício anterior. Argumentos: data: lista com as amostras coletadas do arquivo Retorna: Uma lista com os somatórios dos tipos customer,dependet ,subscriber respectivamente ''' customer = 0 subscriber = 0 dependent = 0 for utypes in column_to_list(data_list, -3): if(utypes.lower()=="customer"): customer += 1 elif(utypes.lower()=="subscriber"): subscriber += 1 elif(utypes.lower()=="dependent"): dependent += 1 return [customer,dependent,subscriber] # Se tudo está rodando como esperado, verifique este gráfico! types = ["Customer","Dependent", "Subscriber"] quantity = count_user_type(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantidade') plt.xlabel('Tipo Usuario') plt.xticks(y_pos, types) plt.title('Quantidade por Tipo Usuario') plt.show(block=True) input("Aperte Enter para continuar...") # TAREFA 8 # TODO: Responda a seguinte questão male, female = count_gender(data_list) print("\nTAREFA 8: Por que a condição a seguir é Falsa?") print("male + female == len(data_list):", male + female == len(data_list)) answer = "Nem todos os campos Gender estão preenchidos, alguns estão vazios e isso gera uma diferença entre o total de amostras e a soma dos gêneros." print("resposta:", answer) # ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------ assert answer != "Escreva sua resposta aqui.", "TAREFA 8: Escreva sua própria resposta!" # ----------------------------------------------------- input("Aperte Enter para continuar...") # Vamos trabalhar com trip_duration (duração da viagem) agora. Não conseguimos tirar alguns valores dele. # TAREFA 9 # TODO: Ache a duração de viagem Mínima, Máxima, Média, e Mediana. # Você não deve usar funções prontas para isso, como max() e min(). trip_duration_list = column_to_list(data_list, 2) min_trip = 0. max_trip = 0. mean_trip = 0. median_trip = 0. def calc_min(trip_list): ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Para verificar o menor valor da lista eu usei a seguite lógica: iniciei a variavel min_trip com o primeiro valor da lista. Em seguida percorri a lista fazer uma comparação para cada variavel 1) - se o valor atual for MENOR que min_trip min_trip recebe valor atual (Fazendo isso eu garato que ao final das interações min_trip terá o valor MENOR) Argumentos: trip_list: lista com os dados da coluna trip_list_duration Retorna: Retorna o menor valor da lista ''' min_trip = float(trip_list[0]) for val in trip_list: if float(val) < min_trip: min_trip = round(float(val)) return min_trip def calc_max(trip_list): ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Para verificar o maior e o menor valor da lista eu usei a seguite lógica: iniciei as variaveis min_trip e max_trip com o primeiro valor da lista. Em seguida percorri a lista fazer uma comparação para cada variavel 1) - se o valor atual for MAIOR que max_trip max_trip recebe valor atual (Fazendo isso eu garato que ao final das interações max_trip terá o valor MAIOR) Argumentos: trip_list: lista com os dados da coluna trip_list_duration Retorna: Retorna o maior valor da lista ''' max_trip = float(trip_list[0]) for val in trip_list: if float(val) > max_trip: max_trip = round(float(val)) return max_trip def calc_sum(any_int_list): ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Percorre a lista somando seus valores e retornando o resultado da soma Argumentos: any_int_list: lista com valores inteiros Retorna: Retorna o somatório dos itens da lista ''' soma = 0 for num in any_int_list: soma+= num return soma def calc_mean(trip_list): ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Para achar a média dos valores da lista eu somei todos os valores da lista e dividi pela quantidade de itens na lista. Argumentos: trip_list: lista com os dados da coluna trip_list_duration Retorna: Retorna o resultado da média. Soma de todos os valores da lista dividido pela quantidade de valores na lista ''' return round(calc_sum( [int(td) for td in trip_list] )/len(trip_list)) def calc_median(trip_list): ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Para fazer a mediana eu ordenei a lista trip_duration depois verifico se o tamanho da lista é par um impar: se a for impar eu pego o valor do meio da lista e esse valor é a mediana se for par eu pego os dois valores do meio somo os dois valores e divido por 2 para chegar a mediana Argumentos: trip_list: lista com os dados da coluna trip_list_duration Retorna: Retorna o resultado do calculo da mediana da lista ''' trip_list.sort(key=int) trip_dur_sort = [int(td) for td in trip_list] indx_meio = len(trip_dur_sort)//2 if (len(trip_dur_sort) % 2) == 0: median_trip = (trip_dur_sort[indx_meio] + trip_dur_sort[indx_meio +1])//2 else: median_trip = trip_dur_sort[indx_meio] return median_trip min_trip = calc_min(trip_duration_list) max_trip = calc_max(trip_duration_list) mean_trip = calc_mean(trip_duration_list) median_trip = calc_median(trip_duration_list) print("\nTAREFA 9: Imprimindo o mínimo, máximo, média, e mediana") print("Min: ", min_trip, "Max: ", max_trip, "Média: ", mean_trip, "Mediana: ", median_trip) # ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------ assert round(min_trip) == 60, "TAREFA 9: min_trip com resultado errado!" assert round(max_trip) == 86338, "TAREFA 9: max_trip com resultado errado!" assert round(mean_trip) == 940, "TAREFA 9: mean_trip com resultado errado!" assert round(median_trip) == 670, "TAREFA 9: median_trip com resultado errado!" # ----------------------------------------------------- input("Aperte Enter para continuar...") # TAREFA 10 # Gênero é fácil porque nós temos apenas algumas opções. E quanto a start_stations? Quantas opções ele tem? # TODO: Verifique quantos tipos de start_stations nós temos, usando set() ''' Autor: Claudio Azevedo Email: claudwolf@hotmail.com Para essa tarefa eu usei a função column_to_list para pegar os valores de start_stations depois usei set para excluir as repetições e vegar ao valores exato de start_stations ''' Sstations = column_to_list(data_list, 3) start_stations = set(Sstations) print("\nTAREFA 10: Imprimindo as start stations:") print(len(start_stations)) print(start_stations) # ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------ assert len(start_stations) == 582, "TAREFA 10: Comprimento errado de start stations." # ----------------------------------------------------- input("Aperte Enter para continuar...") # TAREFA 11 # Volte e tenha certeza que você documentou suas funções. Explique os parâmetros de entrada, a saída, e o que a função faz. Exemplo: # def new_function(param1: int, param2: str) -> list: """ Função de exemplo com anotações. Argumentos: param1: O primeiro parâmetro. param2: O segundo parâmetro. Retorna: Uma lista de valores x. """ input("Aperte Enter para continuar...") # TAREFA 12 - Desafio! (Opcional) # TODO: Crie uma função para contar tipos de usuários, sem definir os tipos # para que nós possamos usar essa função com outra categoria de dados. print("Você vai encarar o desafio? (yes ou no)") answer = "yes" def count_items(column_list): """ Autor: Claudio Azevedo Email: claudwolf@hotmail.com Função de exemplo com anotações. Argumentos: column_list: Lista com a coluna que será trabalahda. Retorna: Duas listas. A primeira com os nomes dos tipos e a segunda com seus respectivos totais """ item_types = list(set(column_list)) count_items = [0 for i in item_types] for item in column_list: count_items[item_types.index(item)]+=1 return item_types, count_items if answer == "yes": # ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------ column_list = column_to_list(data_list, -2) types, counts = count_items(column_list) print("\nTAREFA 12: Imprimindo resultados para count_items()") print("Tipos:", types, "Counts:", counts) assert len(types) == 3, "TAREFA 12: Há 3 tipos de gênero!" assert sum(counts) == 1551505, "TAREFA 12: Resultado de retorno incorreto!" # ----------------------------------------------------- input("Aperte Enter para continuar...") print("\n Apartir desse pontos serão exibidos resultados de questões levantas pelo aluno.") print("\n TAREFA EXTRA 1: Agrupar agrupar amostragem por faixa etária baseado no ano de aniversário") ''' Questão EXTRA elaborada pelo aluno. Autor: Claudio Azevedo Email: claudwolf@hotmail.com Um dado importante a ser considerado são as idades dos usuarios do serviço baseado em suas datas de nascimento TODO EXTRA: Criar uma lista com as idades dos usuarios Verificar as quantidades de usuarios para 3 faixas etárias até 20 anos de idade, entre 20 e 40 anos de idade e maiores de 40 anos Gerar um gráfico para exibir os dados das faixas etárias. ''' '''Obs.:Resolvi usar o ano de 2017 para calcular a idade dos usuarios no ano das amostragem. Me parece mais correto,usar a data atual pode colocar usuarios em faixas diferentes. ''' ano_atual = 2017 idade_int = lambda ano, ano_atual: ano_atual - int(float(ano)) if ano else 0 age_list = [idade_int(idade,ano_atual) for idade in column_to_list(data_list,-1)] ''' 0 -> <= 20 1 -> > 20 and <=40 2 -> > 40 3 -> usuarios que não informaram idade ''' faixas = [ 0, 0, 0, 0] for age in age_list: if age > 0: if age <= 20: faixas[0]+=1 elif age > 20 and age <= 40: faixas[1]+=1 elif age > 40: faixas[2]+=1 else: faixas[3]+=1 print("\nIdade <=20:",faixas[0],"\nIdade > 20 and Idade <= 40:",faixas[1] ,"\nIdade > 40:" ,faixas[2] ,"\nSem Idade:",faixas[3]) indfaixa = faixas.index(max(faixas)) if indfaixa == 0: print("\nA faixa etária que mais fez uso do serviço foi Menor de 20 anos.") elif indfaixa == 1: print("\nA faixa etária que mais fez uso do serviço foi Entre 20 e 40 anos.") elif indfaixa == 2: print("\nA faixa etária que mais fez uso do serviço foi Maior de 40 anos") elif indfaixa == 3: print("\nA faixa etária que mais fez uso do serviço foi a que não informou a idade.") types = ["menor/igual a 20","entre 20 e 40", "maior que 40","Sem Idade"] quantity = faixas #count_user_type(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantidade') plt.xlabel('Faixa etária') plt.xticks(y_pos, types) plt.title('Quantidade por Faixa etária') plt.show(block=True) input("Aperte Enter para continuar...") print("\n TAREFA EXTRA 2: A grupar dados por genero e faixas etárias") '''Questão EXTRA elaborada pelo aluno. Autor: Claudio Azevedo Email: claudwolf@hotmail.com TODO EXTRA: Baseado na proposta anterior, cruzar os dados de gênero e faixa etária. ''' fx_etaria_M = [0, 0, 0, 0] fx_etaria_F = [0, 0, 0, 0] list_genero = column_to_list(data_list,-2) sem_genero_ano = 0 i = 0 #print(len(list_genero)) #print(len(age_list)) for genero in list_genero: if genero.lower() == "male": if age_list[i] > 0: if age_list[i] <= 20: fx_etaria_M[0]+=1 elif age_list[i] > 20 and age_list[i] <= 40: fx_etaria_M[1]+=1 elif age_list[i] > 40: fx_etaria_M[2]+=1 else: fx_etaria_M[3]+=1 elif genero.lower() == "female": if age_list[i]: if age_list[i] <= 20: fx_etaria_F[0]+=1 elif age_list[i] > 20 and age_list[i] <= 40: fx_etaria_F[1]+=1 elif age_list[i] > 40: fx_etaria_F[2]+=1 else: fx_etaria_F[3]+=1 else: sem_genero_ano+=1 i+=1 indfaixaM = fx_etaria_M.index(max(fx_etaria_M)) print("\nIdade <=20:",fx_etaria_M[0],"\nIdade > 20 and Idade <= 40:",fx_etaria_M[1] ,"\nIdade > 40:" ,fx_etaria_M[2] ) if indfaixaM == 0: print("\nA faixa etária Masculina que mais fez uso do serviço foi Menor de 20 anos.") elif indfaixaM == 1: print("\nA faixa etária Masculina que mais fez uso do serviço foi Entre 20 e 40 anos.") elif indfaixaM == 2: print("\nA faixa etária Masculina que mais fez uso do serviço foi Maior de 40 anos") elif indfaixaM == 3: print("\nA faixa etária Masculina que mais fez uso do serviço foi a que não informou a idade.") indfaixaF = fx_etaria_F.index(max(fx_etaria_F)) print("\nIdade <=20:",fx_etaria_F[0],"\nIdade > 20 and Idade <= 40:",fx_etaria_F[1] ,"\nIdade > 40:" ,fx_etaria_F[2] ) if indfaixaF == 0: print("\nA faixa etária Feminina que mais fez uso do serviço foi Menor de 20 anos.") elif indfaixaF == 1: print("\nA faixa etária Feminina que mais fez uso do serviço foi Entre 20 e 40 anos.") elif indfaixaF == 2: print("\nA faixa etária Feminina que mais fez uso do serviço foi Maior de 40 anos") elif indfaixaF == 3: print("\nA faixa etária Feminina que mais fez uso do serviço foi a que não informou a idade.") print("\nSem idade e sem gênero:", sem_genero_ano) genero_f_etarias = [ fx_etaria_M[0], fx_etaria_F[0], fx_etaria_M[1], fx_etaria_F[1], fx_etaria_M[2], fx_etaria_F[2], sem_genero_ano ] types = ["M\ny < 20","F\ny < 20","M\n20 < y <=40","F\n20 < y <=40","M\ny > 40","F\ny > 40","Sem Idade/Gênero"] quantity = genero_f_etarias y_pos = list(range(len(types))) m1 ,f1 ,m2 ,f2, m3 ,f3 ,semGA = plt.bar(y_pos, quantity) m1.set_facecolor('blue') f1.set_facecolor('red') m2.set_facecolor('blue') f2.set_facecolor('red') m3.set_facecolor('blue') f3.set_facecolor('red') semGA.set_facecolor('gray') plt.ylabel('Quantidade') plt.xlabel('Gênero / faixa etária') plt.xticks(y_pos, types) plt.title('Quantidade por Gênero / faixa etária') plt.show(block=True) ''' IMPORTANTE Obs.: Se compararmos os dados dos valores dos gráficos de faixa etária e o de Gênero/Faixa etária, vamos ver que os somatórios não batem.Isso ocorre por que alguns registros não tem dados de gênero e de ano de nascimento. '''
# PLEASE NOTE: This snippet is about basic arithmetic and variable operations ### AUFGABE: Wie funktionieren Variablenzuweisungen und Operationen mit Variablen? # ONE Arithmetic operations with numbers a = 10 b = 2 c = 12.7 #print(a + b) #print(a - c) #print(a * b) #print(a / c) # TWO Same artihmetic operations possible with type "string"? c = "Hello" d = "Anna" #print(c + d) # vs print(c,d) #print(c - d) #print(c * d) #print(c / d) # THREE "Mixing" numerical and textual data? number = 12.4 text = "random text" #print(number + text) #print(number,text) # FOUR Advanced Maths e = 3 f = 9 #print(a % b)
""" This file contains functions that are used to augment a cluster """ from collections import defaultdict from matplotlib import pyplot as plt from matplotlib.lines import Line2D def flatten(list): """ flattens a list of lists or tuple of tuples to a 1d list """ return [item for sublist in list for item in sublist] def plot_cluster(cluster, maxy=None, maxx=None, ax=None, color="k"): """ plots a cluster along a lattice with dim [maxy, maxx] """ if maxy is None or maxx is None: if maxy is None: maxy, doy = 0, True else: doy = False if maxx is None: maxx, dox = 0, True else: dox = False for y, x, _ in cluster: maxy = y if doy and y > maxy else maxy maxx = x if dox and x > maxx else maxx if ax is None: plt.figure() ax = plt.gca() ax.invert_yaxis() ax.set_aspect("equal") ax.axis("off") for y in range(maxy + 1): for x in range(maxx + 1): a = 0.9 if (y, x, 0) in cluster else 0.1 ax.plot([x, x + 1], [y, y], alpha=a, color=color, lw=4) a = 0.9 if (y, x, 1) in cluster else 0.1 ax.plot([x, x], [y, y + 1], alpha=a, color=color, lw=4) def plot_clusters(data, type_count, plotnum, extra=5): print("Plotting...") fig = plt.figure(figsize=(16, 20)) plotcols = -int(-(plotnum ** (1 / 2)) // 1) plotrows = -(-plotnum // plotcols) grid = plt.GridSpec(plotrows + extra, plotcols, wspace=0.4, hspace=0.3) maxy, maxx = 0, 0 for cluster, count in data[:plotnum]: for (y, x, td) in cluster: maxy = y if y > maxy else maxy maxx = x if x > maxx else maxx for plot_i, (cluster, _) in enumerate(data[:plotnum]): ax = plt.subplot(grid[plot_i // plotcols, plot_i % plotcols]) ax.set_title(str(plot_i)) plot_cluster(cluster, maxy, maxx, ax=ax, color="C{}".format(plot_i % 10)) ax_count1 = plt.subplot(grid[plotrows:, :2]) ax_count2 = plt.subplot(grid[plotrows:, 2:]) ax_count1.set_ylabel("Normalized occurence") ax_count2.set_xlabel("Cluster type") CU, CV = [], [] for i, (_, (cu, cv)) in enumerate(data[:plotnum]): CU.append(cu / type_count[0]) CV.append(cv / type_count[0]) ax_count1.plot(list(range(plotcols)), CU[:plotcols], ":", alpha=0.1, color="black") ax_count1.plot(list(range(plotcols)), CV[:plotcols], "--", alpha=0.1, color="black") for i in range(plotcols): ax_count1.scatter(i, CU[i], s=50, marker="+", color="C{}".format(i % 10)) ax_count1.scatter(i, CV[i], s=50, marker="x", color="C{}".format(i % 10)) ax_count2.plot( list(range(plotcols, plotnum)), CU[plotcols:], ":", alpha=0.1, color="black" ) ax_count2.plot( list(range(plotcols, plotnum)), CV[plotcols:], "--", alpha=0.1, color="black" ) for i in range(plotcols, plotnum): ax_count2.scatter(i, CU[i], s=50, marker="+", color="C{}".format(i % 10)) ax_count2.scatter(i, CV[i], s=50, marker="x", color="C{}".format(i % 10)) legend_elements = [ Line2D( [0], [0], ls=":", color="black", marker="+", markersize=10, alpha=0.5, label="ubuck", ), Line2D( [0], [0], ls="--", color="black", marker="x", markersize=10, alpha=0.5, label="vcomb", ), ] # Create the figure ax_count2.legend(handles=legend_elements) plt.title( "Cluster data from {} ubuck wins and {} vcomb wins".format( type_count[0], type_count[1] ) ) # plt.show() return fig def get_neighbor(y, x, td, L): # Only check for existing vertices in row after row # neighbors = [(y-1, x+1, 1)] if td == 0 else [(y, x, 0)] # neighbors += [(y-1, x, 1), (y, x-1, 0)] if td: return [ (y, x, 0), ((y + 1) % L, (x - 1) % L, 0), ((y - 1) % L, x, 1), ((y + 1) % L, x, 1), (y, (x - 1) % L, 0), ((y + 1) % L, x, 0), ] else: return [ (y, (x + 1) % L, 1), ((y - 1) % L, x, 1), (y, (x + 1) % L, 0), (y, (x - 1) % L, 0), ((y - 1) % L, (x + 1) % L, 1), (y, x, 1), ] def get_support2clusters(graph, size, minl=1, maxl=4): errors = [ graph.E[(0, y, x, td)].qID[1:] for y in range(size) for x in range(size) for td in range(2) if graph.E[(0, y, x, td)].support == 2 ] # Get clusters from array data clusters = get_clusters_from_list(errors, size) # Remove outlier clusters clusters = [ cluster for cluster in clusters.values() if len(cluster) >= minl and len(cluster) <= maxl ] return clusters def get_clusters_from_list(list_of_qubits, size): """ Returns a dict of clusters, with values lists of connected vertices from a list of vertices """ clusters, vertices, cnum = defaultdict(list), {}, 0 for y, x, td in list_of_qubits: y, x, td = int(y), int(x), int(td) v = (y, x, td) neighbors = get_neighbor(*v, size) nomerged = True for n in neighbors: if n in vertices: if nomerged: cluster = vertices[n] vertices[v], nomerged = cluster, False clusters[cluster].append(v) else: cluster, merging = vertices[v], vertices[n] if cluster != merging: for mv in clusters[merging]: vertices[tuple(mv)] = cluster clusters[cluster].extend(clusters[merging]) clusters.pop(merging) break if nomerged: vertices[v] = cnum clusters[cnum].append(v) cnum += 1 return clusters def get_logical_cluster(dict_of_clusters, lattice): """ returns the clusters which crosses the logical boundary """ if len(dict_of_clusters) != 1: sorted_list = sorted( [cluster for cluster in dict_of_clusters.values()], key=lambda k: len(k), reverse=True, ) for cluster in sorted_list: ycheck, xcheck = [0] * lattice, [0] * lattice for y, x, _ in cluster: ycheck[y], xcheck[x] = 1, 1 if all(ycheck) or all(xcheck): break return cluster elif len(dict_of_clusters) == 1: return dict_of_clusters[0] else: print("No clusters!") exit() def tupleit(t): return tuple(map(tupleit, t)) if isinstance(t, (tuple, list)) else t def listit(t): return list(map(listit, t)) if isinstance(t, (tuple, list)) else t def max_dim(cluster): """ Gets a cluster's max x coordinate and max diagnal """ maxy, maxx = cluster[0][0], cluster[0][1] for (y, x, _) in cluster: maxy = y if y > maxy else maxy maxx = x if x > maxx else maxx mdiag = (maxy ** 2 + maxx ** 2) ** (1 / 2) return (maxx, mdiag) def principal(cluster, augment=1, ydim=0, xdim=0): """ returns any cluster to its principal cluster with: - only positive coordiates in its vertices - minimal weight of its center of mass """ if augment: midy, midx = cluster[0][0], cluster[0][1] for vi, (y, x, _) in enumerate(cluster): mirrors = [ (y + dy, x + dx) for dy in [-ydim, 0, ydim] for dx in [-xdim, 0, xdim] ] distances = [ ((midy - y) ** 2 + (midx - x) ** 2) ** 1 / 2 for (y, x) in mirrors ] min_yx = mirrors[distances.index(min(distances))] cluster[vi][0], cluster[vi][1] = min_yx[0], min_yx[1] midy, midx = ( (vi * midy + min_yx[0]) / (vi + 1), (vi * midx + min_yx[1]) / (vi + 1), ) # Get min coordinates miny, minx = cluster[0][0], cluster[0][1] for (y, x, _) in cluster: miny = y if y < miny else miny minx = x if x < minx else minx # Return to principal by subtraction for vi in range(len(cluster)): cluster[vi][0] -= miny cluster[vi][1] -= minx return tupleit(cluster) def rotate(cluster, xdim): """ Rotates a cluster counterclockwise """ new_cluster = [] for (y, x, td) in cluster: qubit = [xdim + td - x, y, 1 - td] new_cluster.append(qubit) return principal(sorted(new_cluster), augment=0) def mirror(cluster, xdim): """ Flips a cluster on its vertical axis """ new_cluster = [] for (y, x, td) in cluster: qubit = [y, xdim - x + td, td] new_cluster.append(qubit) return principal(sorted(new_cluster), augment=0) def get_count(clusters, cluster_data, size, type): """ returns a defaultdict of lists of clusters countaining the tuples of the qubits """ clusters = listit(clusters) # Return to principal cluster for i, cluster in enumerate(clusters): clusters[i] = principal(cluster, ydim=size, xdim=size) for cluster in clusters: augs, cmid = [], [] for rot_i in range(4): dim = max_dim(cluster) augs.append(cluster) cmid.append(dim[1]) fcluster = frozenset(cluster) if fcluster in cluster_data: cluster_data[fcluster][type] += 1 break mcluster = mirror(cluster, dim[0]) mdim = max_dim(mcluster) augs.append(mcluster) cmid.append(mdim[1]) fmcluster = frozenset(mcluster) if fmcluster in cluster_data: cluster_data[fmcluster][type] += 1 break cluster = rotate(cluster, dim[0]) else: ftupcluster = frozenset(augs[cmid.index(min(cmid))]) cluster_data[ftupcluster][type] += 1 return cluster_data def get_count2(clusters, cluster_data, size, n, type): """ returns a defaultdict of lists of clusters countaining the tuples of the qubits """ clusters = listit(clusters) # Return to principal cluster for i, cluster in enumerate(clusters): clusters[i] = principal(cluster, ydim=size, xdim=size) for cluster in clusters: augs, cmid = [], [] for rot_i in range(4): dim = max_dim(cluster) augs.append(cluster) cmid.append(dim[1]) fcluster = frozenset(cluster) if fcluster in cluster_data: cluster_data[fcluster][(size, n)][type] += 1 break mcluster = mirror(cluster, dim[0]) mdim = max_dim(mcluster) augs.append(mcluster) cmid.append(mdim[1]) fmcluster = frozenset(mcluster) if fmcluster in cluster_data: cluster_data[fmcluster][(size, n)][type] += 1 break cluster = rotate(cluster, dim[0]) else: ftupcluster = frozenset(augs[cmid.index(min(cmid))]) cluster_data[ftupcluster][(size, n)][type] += 1 return cluster_data
def bubblesort(lst): while True: # we are going to loop through the list till we get an iteration without any swap swap = False for y in range(0, len(lst) - 1): # In this inner loop, we are going to compare two elements next to each other (from the beginning) if lst[y] > lst[y+1]: # A swap will be made if the numbers are in out of place. (Unsorted order... ) temp = lst[y+1] # if a swap is done, we will continue the outer loop one more time till there is lst[y+1] = lst[y] # no swap. lst[y] = temp swap = True if swap == False: # when we get here, we have come to an iteration without any swap and list is sorted. break return lst
s = input("Bвeдитe строку:\n") s = s.upper() k = 0 for i in range(0, len(s)): if s.count(s[i]) > k: k = s.count(s[i]) print(k)
word = list(input()) while len(word) != 1 and len(word) != 2: word.pop(0) word.pop(-1) print(''.join(word))
text = input() cyrillic = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' latin = 'a|b|v|g|d|e|e|zh|z|i|i|k|l|m|n|o|p|r|s|t|u|f|kh|tc|ch|sh|shch||y||e|iu|ia|A|B|V|G|D|E|E|Zh|Z|I|I|K|L|M|N|O|P|R|S|T|U|F|Kh|Tc|Ch|Sh|Shch||Y||E|Iu|Ia'.split('|') print(text.translate({ord(k):v for k,v in zip(cyrillic,latin)}))
# -*- coding: utf-8 -*- import sqlite3 db_file="db_chattrain.db" def create_connection(): """ create a database connection to a SQLite database """ try: conn = sqlite3.connect(db_file) print(sqlite3.version) except Error as e: print(e) finally: conn.close() def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) def setup(): try: create_connection() conn = sqlite3.connect(db_file) create_table_sql="CREATE TABLE IF NOT EXISTS chattrain (id integer PRIMARY KEY,txtdata text NOT NULL,sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)" create_table(conn,create_table_sql) print("setup ok") conn.close() except Error as e: print(e) def add_data(textget,textsent): conn = sqlite3.connect(db_file) sql = "INSERT INTO chattrain (txtdata) VALUES (?)" cur = conn.cursor() cur.execute(sql, (str(textget))) conn.commit() #print(True) conn.close()
import unittest import triangle_problem class MyTest(unittest.TestCase): def test_equilateral_triangle(self): # Arrange x = int(10) y = int(10) z = int(10) # Act receive = triangle_problem.side(x, y, z) # Assert self.assertEqual('equilateral', receive) def test_isosceles_triangle(self): # Arrange x = int(8) y = int(8) z = int(5) # Act receive = triangle_problem.side(x, y, z) # Assert self.assertEqual('isosceles', receive) def test_irregular_triangle(self): # Arrange x = int(8) y = int(6) z = int(7) # Act receive = triangle_problem.side(x, y, z) # Assert self.assertEqual('irregular', receive) if __name__ == '__main__': unittest.main()
def SwapFileData(): f1 = input("Enter the directory of the file to be swapped : ") f2 = input("Enter the directory of file to swap with : ") with open(f1 , 'r') as a: data_a = a.read() with open(f2 , 'r') as b: data_b = b.read() with open(f1 , 'w') as a: a.write(data_b) with open(f2 , 'w') as b: b.write(data_a) file1 = open(f1 , 'r') print(file1.read()) file2 = open(f2 , 'r') print(file2.read()) SwapFileData() """file1 = open(f1 , 'r') data_a = file1.read() file1.close() file2 = open(f2 , 'r') data_b = file2.read() file2.close() file1=open(f1 , 'w') file2=open(f2 , 'w') file1.write(data_b) file2.write(data_a) file1.close() file2.close()"""
import random import os IMAGES = [''' +----+ | | | | | | ==========''', ''' +----+ | | O | | | | ==========''', ''' +----+ | | O | | | | | ==========''', ''' +----+ | | O | /| | | | ==========''', ''' +----+ | | O | /|\ | | | ==========''', ''' +----+ | | O | /|\ | | | | ==========''', ''' +----+ | | O | /|\ | | | / | ==========''', ''' +----+ | | O | /|\ | | | / \ | ==========''', ''' '''] WORDS = [ 'can', 'you', 'feel', 'the', 'love', 'tonight', 'pinche', 'pendejo' ] def random_word(): idx = random.randint(0,len(WORDS) - 1) return WORDS[idx] def display(hidden_word, tries): if tries > 0: os.system('clear') display_header() print(IMAGES[tries]) print('') print(hidden_word) print('\n##########################################################') def run_game(): word = random_word() hidden_word = ['-'] * len(word) tries = 0 while True: display(hidden_word, tries) current_letter = str(input('Type a Letter: ')) letter_indexes = [] for i in range(len(word)): if word[i] == current_letter: letter_indexes.append(i) if len(letter_indexes) == 0: tries += 1 if tries == 7: display(hidden_word, tries) print('') print('Dammit, you killed the poor fuck,\nanyway, the word was: {}'.format(word)) break else: for i in letter_indexes: hidden_word[i]= current_letter letter_indexes = [] try: hidden_word.index('-') except ValueError: print('') print('Phew!\nthat MoFo sweat it out,\nthe word was \"{}\", good job!'.format(word)) break def display_header(): print('H A N G M A N\n\nGuess the word and don\'t hang the poor fuck!') if __name__ == "__main__": display_header() run_game()
import matplotlib import matplotlib.pyplot as plt import math_lib def boxplot(L, out_file_name): """Generates a boxplot from given data """ plt.figure() plt.boxplot(L) plt.xlabel('Box') plt.ylabel('Distribution') plt.title('Mean: %6.2f, Standard deviation: %6.2f' % (math_lib.list_mean(L), math_lib.list_stdev(L))) # plt.show() def histogram(L, out_file_name): """Generates a histogram from given data """ plt.figure() plt.hist(L, bins=20) plt.xlabel('Value') plt.ylabel('Frequency') plt.title('Mean: %6.2f, Standard deviation: %6.2f' % (math_lib.list_mean(L), math_lib.list_stdev(L))) plt.show() def combo(L, out_file_name): """Generates boxplot and histogram from given data """ fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 6)) plt.subplot(1, 2, 1) plt.boxplot(L) plt.xlabel('Value') plt.ylabel('Distribution') plt.subplot(1, 2, 2) plt.hist(L, bins=20) plt.xlabel('Value') plt.ylabel('Frequency') fig.suptitle('Mean: %6.2f, Standard deviation: %6.2f' % (math_lib.list_mean(L), math_lib.list_stdev(L)))v(L)))
from math import factorial fatorialn = int(input('Digite um número para calcular seu fatorial: ')) contagem = fatorialn f = 1 print (f'O fatorial de {fatorialn}! = ', end='') while contagem > 0: print ('{}'.format (contagem), end='') print (' x ' if contagem > 1 else ' = ', end='') f *= contagem contagem -= 1 print (f'{f}') ''' numero = int(input('Digite aqui seu fatorial: ')) print (f'O fatorial de {numero}! é ', end='') for f in range (numero, -1, -1): print (f'{f}' if f > 0 else '', end ='') print (' x ' if f > 0 else '= ', end ='') print (factorial(numero)) '''
lista = [[], []] for n in range (1, 8): numeros = int(input(f'Digite o {n}° número: ')) if numeros % 2 == 1: lista[0].append(numeros) if numeros % 2 == 0: lista[1].append(numeros) print (f'Os números ímpares digitados foram {sorted(lista[0])} ') print (f'Os números pares digitados foram {sorted(lista[1])} ') ''' print ('Os números ímpares digitados foram ', end = '') for i in lista: if i % 2 == 1: print (f'[{i}] ', end = '') print ('\nOs números pares digitados foram ', end = '') for i in lista: if i % 2 == 0: print (f'[{i}] ', end = '') '''
from random import randint import time cont = 1 dados = {'jogador 1': randint(1, 6), 'jogador 2': randint(1, 6), 'jogador 3': randint(1, 6), 'jogador 4': randint(1, 6)} for k, v in dados.items(): print (f'{k} tirou {v}') time.sleep(0.8) dadosorg = sorted(dados.items(), key=lambda x: x[1], reverse=True) print (25*'-') print ('Raking dos jogadores'.center(24).upper()) for k, v in dadosorg: print (f'{cont}° lugar: {k} com {v}') cont += 1 time.sleep(0.9)
lista = list() continuar2 = ' ' while True: valor = int(input('Digite um valor: ' )) if valor in lista: print ('Número já existe, não adicionado...') else: lista.append(valor) print ('Valor adicionado') continuar = input('Você deseja continuar? [S/N] ').strip().upper() if continuar == 'N': break if continuar != 'S': while True: continuar2 = input('Por favor, use somente as letras [S/N]').strip().upper() if continuar2 == 'N' or continuar2 == 'S': break if continuar2 in 'N': break lista.sort() print (f'Todos os valores únicos adicionados em ordem crescente é {lista}') ''' if valor not in lista: lista.append(valor) '''
n = int(input('Digite aqui um número inteiro ')) opção = int(input('Você deseja converter para:\n[ 1 ] Binário\n[ 2 ] Octal\n[ 3 ] Hexadecimal:\n')) if opção == 1: print ("O seu número {} convertido para binário é {}".format (n, bin(n)[2:])) elif opção == 2: print ("O seu número {} convertido para octal é {}".format (n, oct(n)[2:])) elif opção == 3: print ("O seu número {} convertido para hexadecimal é {}".format (n, hex(n)[2:])) else: print ('Por favor, digite um número de 1 a 3')
soma = 0 cont = 0 for impares in range(1, 501, 2): if impares % 3 == 0: cont = cont + 1 soma = soma + impares print (f'A soma de {cont} valores foi {soma}')
'''nome = str(input('Digite seu nome completo aqui: ')).strip().lower() existe = 'silva' in nome print (f'Em seu nome existe a palavra "Silva"? {existe}')''' nome1 = str(input('Digite seu nome completo aqui ')).strip().lower() nomebobo = nome1.split() existe2 = ('silva' in nomebobo[0]) print = (f'Existe ou não: {existe2}')
lista = list() listai = list() listap = list() while True: lista.append(int(input('Digite um número: '))) while True: continuar = input('Você deseja adicionar mais um número? [S/N] ').strip().upper() if continuar in 'N': break if continuar in 'S': break if continuar != 'S': print('Por favor, digite novamente ') if continuar in 'N': break for num in range (0, len(lista)): if lista[num] % 2 == 0: listap.append(lista[num]) else: listai.append(lista[num]) print (f'A lista inteira é {lista}') print (f'A lista ímpar é {listai}') print (f'A lista par é {listap}')
soma = cont = 0 while True: n = int(input('Digite um número (999 para parar): ')) if n == 999: break cont += 1 soma += n print (f'Foram digitados {cont} números e a soma de todos eles é {soma}')
import time ano = time.gmtime()[0] maior = 0 menor = 0 for n in range (1, 7+1): nas = int(input(f'Qual ano a {n}° pessoa nasceu? ')) nas2 = ano - nas if nas2 >= 21: maior = maior + 1 elif nas2 <21: menor = menor + 1 print ('São no total {} pessoas maiores de idade e {} pessoas menores de idade'.format (maior, menor))
nomec = str(input('Digite aqui seu nome completo ')).strip() print ('O nome com todas as letras maiúsculas é: {}'.format(nomec.upper())) print ('O nome com todas as letras minúsculas é: {}'.format(nomec.lower())) print ('O número de letras que contém sem considerar espaços é: {}'.format (len(nomec) - nomec.count(' '))) print ('A quantidade de letras que possui o primeiro nome é: {}'.format (len (nomec.split()[0]))) print ('Seu primeiro nome tem {}'.format (nomec.find(' ')))
def leiaInt(num): while True: try: n = int(input(num)) except (ValueError, TypeError): print('\33[31mErro! Digite um número real válido\33[m') continue except KeyboardInterrupt: print('\33[31mO Usuário não digitou os dados\33[m') return 0 else: return n def leiaFloat(num): while True: try: numero = float(input(num)) except (ValueError, TypeError): print ('\33[31mErro! Digite um número inteiro válido\33[m') except (KeyboardInterrupt): print ('\33[31mO usuário não digitou os dados\33[m') return 0 else: return numero n = leiaInt('Digite um número inteiro: ') nf = leiaFloat('Digite um número real: ') print (f'Você digitou o número inteiro {n} e número real {nf}')
# 用for循环实现1~100求和 sum = 0 # range,左闭右开区间 for i in range(1 ,101): sum += i print('1~100的和为:', sum)
''' 使用tkinter创建GUI - 使用画布绘图 - 处理鼠标事件 ''' import tkinter def mouse_evt_handler(evt=None): row = round((evt.y - 20) / 40) col = round((evt.x - 20) / 40) pos_x = 40 * col pos_y = 40 * row canvas.create_oval(pos_x, pos_y, 40 + pos_x, 40 + pos_y, fill='black') top = tkinter.Tk() # 设置窗口尺寸 top.geometry('620x620') # 设置窗口标题 top.title('五子棋') # 设置窗口大小不可变 top.resizable(False, False) # 设置窗口置顶 top.wm_attributes('-topmost', 1) canvas = tkinter.Canvas(top, width=600, height=600, bd=0, highlightthickness=0) canvas.bind('<Button-1>', mouse_evt_handler) canvas.create_rectangle(0, 0, 600, 600, fill='yellow', outline='white') for index in range(15): canvas.create_line(20, 20 + 40 * index, 580, 20 + 40 * index, fill='black') canvas.create_line(20 + 40 * index, 20, 20 + 40 * index, 580, fill='black') canvas.create_rectangle(15, 15, 585, 585, outline='black', width=4) canvas.pack() tkinter.mainloop() # 请思考如何用面向对象的思想对上面的代码进行封装
''' 用turtle模块绘图 这是一个非常有趣的模块 它模拟一只乌龟在窗口上爬行的方式来进行绘图 ''' import turtle turtle.pensize(3) turtle.penup() turtle.goto(-180, 150) turtle.pencolor('red') turtle.fillcolor('yellow') turtle.pendown() turtle.begin_fill() for _ in range(36): turtle.forward(200) turtle.right(170) turtle.end_fill() turtle.mainloop()
# 另一种创建类的方式 def bar(self, name): self._name = name def foo(self, course_name): print('%s正在学习%s.' % (self._name, course_name)) def main(): Student = type('Student', (object,), dict(__init__=bar, study=foo)) stu1 = Student('骆新') stu1.study('python程序设计') if __name__ == '__main__': main()
''' 将华氏温度转换为摄氏温度 F =1.8C + 32 ''' f =float(input('请输入华氏温度:')) c =(f - 32) / 1.8 print('%.1f华氏度 = %.f摄氏度' % (f, c))
''' 生成器 - 生成器语法 ''' seq = [x * x for x in range(10)] print(seq) gen = (x * x for x in range(10)) print(gen) for x in gen: print(x) num = 10 gen = (x ** y for x, y in zip(range(1, num), range(num - 1, 0, -1))) print(gen) n = 1 while n < num: print(next(gen)) n += 1
from itertools import permutations from math import sqrt class Point: def __init__(self, x, y): self.x = x self.y = y def sqr_dist(self, other): "Квадрат расстояния - этого достаточно, чтобы отличать разные расстояния между точками" return (self.x - other.x)**2 + (self.y - other.y)**2; def __repr__(self): return f'<Point {self.x}, {self.y}>' n = int(input()) # Считываем все точки в массив a = [] for i in range(n): a.append(Point(*[int(x) for x in input().split()])) # Найденные расстояния складываем в множество, дубликаты отбрасываются автоматически unique_dists = set() # Генерируем все комбинации пар точек for (a, b) in permutations(a, 2): # Считаем растояния между точками пары unique_dists.add(a.sqr_dist(b)) dists = sorted([round(sqrt(sqr_dist), 9) for sqr_dist in unique_dists]) print(len(dists)) for dist in dists: print(dist)
from math import ceil def ariphm_sum(start, stop, step=1): """ Сумма арифметической прогрессии Аргументы аналогичны функции range, т.е. [start, stop) с шагом step """ n = ceil((stop - start) / step) return (start + step*(n-1)/2) * n assert ariphm_sum(1, 101) == 5050 assert ariphm_sum(-100, 0) == -5050 assert ariphm_sum(-100, 101) == 0 assert ariphm_sum(1, 8, 2) == 16 assert ariphm_sum(1, 10, 2) == 25 assert ariphm_sum(-3, 10, 2) == 21 assert ariphm_sum(-3, 10, 3) == 15 assert ariphm_sum(-10**8, 10**8+1) == 0 assert ariphm_sum(-10**8, 10**8+2) == 100000001 # 1 2 3 4 5 (1, 6, 1) = 15 # 1 3 5 7 9 (1, 10, 2) = 25 # -3 -1 1 3 5 7 9 (-3, 10, 2) = 21 # -3 0 3 6 9 (-3, 10, 3) = 15
import time def time_passed(func): def wrap(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end = time.time() print('Время выполнения: {} секунд.'.format(end-start)) return res return wrap from math import ceil @time_passed def second_task0(n, x, y, z, w): solutions = [] cubes = [x*x*x for x in range(1, n+1)] cube_set = set(cubes) for x_, x3 in enumerate(cubes): x = x_ + 1 for y_, y3 in enumerate(cubes[x_+1:]): y = x + y_ + 1 for z_, z3 in enumerate(cubes[x_+y_+2:]): z = y + z_ + 1 x3y3z3 = x3+y3+z3 if x3y3z3 in cube_set: w = ceil(x3y3z3 ** (1/3)) solutions.append((x, y, z, w)) return solutions @time_passed def second_task(n, x, y, z, w): solutions = [] cubes = [(x, x*x*x) for x in range(1, n+1)] m3 = cubes[-1][1] for x, x3 in cubes: for y, y3 in cubes[x:]: for z, z3 in cubes[y:]: x3y3z3 = x3+y3+z3 w = ceil(x3y3z3 ** (1/3)) if m3 >= x3y3z3 == cubes[w-1][1]: solutions.append((x, y, z, w)) return solutions sol = second_task0(1000, 0, 0, 0, 0) print(len(sol), sol) sol = second_task(1000, 0, 0, 0, 0) print(len(sol), sol)
def compareWithNones(A, B): for i, row in enumerate(A): for j, cell in enumerate(row): b_cell = B[i][j] if cell is not None and b_cell is not None and cell != b_cell: return False return True _ = None # 0 or 1 A = [ [1, _, 1, _], [0, 1, _, 0], [_, 1, 1, 0], [0, 0, 0, 0] ] B = [ [0, 1, 0, 0], [1, 0, 1, 0], [1, 1, 0, 0], [0, 0, 0, 0] ] C = [ [_, 1, 1, 0], [0, 1, 0, 0], [1, _, 1, 0], [0, 0, _, 0] ] print(compareWithNones(A, B)) # False print(compareWithNones(A, C)) # True
from random import randint def new_gladiator(health, rage, damage_low, damage_high): '''input -> dictionary Returns a dictionary representing the gladiator with the provided values: health, rage, lowest damage, and highest damage''' gladiator = { 'health': health, 'rage': rage, 'lowest damage': damage_low, 'highest damage': damage_high } return gladiator def attack(attacker, defender): '''dictionary -> None Attacker(gladiator) strikes defender(other gladiator) with normal hit or critical hit, and gladiators reacts accordingly''' hit = randint(attacker['lowest damage'], attacker['highest damage']) probability = randint(1, 80) if probability <= attacker['rage']: # if a critical hit health = defender['health'] - (2 * hit) # makes sure health does not drop below 0 defender['health'] = max(health, 0) attacker['rage'] = 0 print('Critical hit!') else: health = defender['health'] - hit # makes sure health does not drop below 0 defender['health'] = max(health, 0) rage = attacker['rage'] + 15 # makes sure rage does not go over 100 attacker['rage'] = min(rage, 100) def heal(gladiator): '''dictionary -> bool or None Makes gladiator use rage to heal 5 HP''' #make sure gladiator's health stays less then 100 if gladiator['health'] >= 100: gladiator['health'] = min(gladiator['health'], 100) #make sure gladiator can heal elif gladiator['rage'] < 10: return None #gladiator uses the Power of Rage! to heal else: gladiator['rage'] = gladiator['rage'] - 10 gladiator['health'] = gladiator['health'] + 5 def is_dead(gladiator): '''dictionary -> bool Checks gladiator's health and if they are dead returns True, if they are alive returns False''' if gladiator['health'] == 0: return True else: return False
#encoding=utf-8 ''' Copyright : CNIC Author : LiuYao Date : 2017-8-31 Description : test my algorithm ''' import pandas as pd import numpy as np from marchine_learning.linear_model import LogisticRegression import matplotlib.pyplot as plt def load_data(): ''' load data ''' data = pd.read_csv('./data.csv') x = data[['x', 'y']] y = data['label'] return x, y def plot(x_train, y_train, theta): [m, n] = x_train.shape plt.scatter(x_train.values[:, 0], x_train.values[:, 1], c=y_train) x1 = np.random.rand(100, 1) * 25 x2 = (-theta[2] - x1 * theta[0]) / theta[1] plt.plot(x1, x2) plt.show() # def train(): # x, y = load_data() # x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0) # lr = LogisticRegression(iterator_num=100) # lr.train(x_train.values, y_train.values.T) # y_predict = lr.predict(x_test.values) # y_predict[y_predict > 0.5] = 1 # y_predict[y_predict < 0.5] = 0 # print lr.theta # print "accuracy : ", np.sum(y_predict.getA()[0] == y_test.values) / (len(y_test) * 1.0) def main(): ''' program entry ''' x, y = load_data() lr = LogisticRegression(iterator_num=5, optimization='sgd') lr.train(x.values, y.values.T) print lr.theta plot(x, y, lr.theta) if __name__ == '__main__': main()
n1 = float(input('Primeira nota:')) n2 = float(input('Segunda nota')) m = (n1 + n2)/2 print('a primeira nota foi {}, a segunda {} e a media é {}'.format(n1, n2, m))
s = float(input('qual o seu salário ? (em reais)')) if s >= 1250: a = float((s*10/100) + (s)) print('seu salario é {} e seu almento foi de {}'.format(s, a)) else: a = float((s*15/100) + (s)) print('seu salario é {} e seu almento foi de {}'.format(s, a))
from math import trunc x = float(input("Digite o numero aqui:")) k = x*(10**11) y = (trunc(x))*(10**11) print("O numero que você digitou foi {}," " e a sua parte inteira é {}!" " E a sua parte decimal é {}!" .format(x, trunc(x), (k-y)*(1/(10**11))))
x = float(input('Qual o tamanho em metros?')) print('O tamanho em metros é {}, esse tamanho convertido para centimetros é {} e para milimetros é {}'.format( x, x*100, x*1000))
# the function cv2.medianBlur() computes the median of all the pixels under #the kernel window and the central pixel is replaced with this median value """This is highly effective in removing salt-and-pepper noise. One interesting thing to note is that, in the Gaussian and box filters, the filtered value for the central element can be a value which may not exist in the original image. However this is not the case in median filtering, since the central element is always replaced by some pixel value in the image. This reduces the noise effectively. The kernel size must be a positive odd integer.""" #---------3-------Median blur--------- import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('H:\\a.jpg') cv2.imshow("original",img) median = cv2.medianBlur(img,5) cv2.imshow("Blur",median) plt.subplot(121),plt.imshow(img),plt.title('Original') plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(median),plt.title('Blurred') plt.xticks([]), plt.yticks([]) plt.show() cv2.waitKey(0)
#!/usr/local/bin/python3 # -*- coding: UTF-8 -*- class Solution(object): def test1(self): ''' 题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少? ''' for i in range(1,5): for j in range(1,5): for k in range(1,5): if( i != k ) and (i != j) and (j != k): print(i,j,k) if __name__ == "__main__": solution = Solution() solution.test1()
#Write a function called sumall that takes any number of arguments and returns their sum. def sumall(*args): sum=0 for n in args: sum+=n return sum sumall(9,5,6,73)
import sys import time BOARD_SIZE = 20 arg_count=0 def under_attack(col, queens): return col in queens or \ any(abs(col - x) == len(queens)-i for i,x in enumerate(queens)) #count the LSV for each value # def least_constraint_value(): # def rsolve(queens, n): global arg_count if n == len(queens): return queens else: #define/call csp for i in range(n): if not under_attack(i,queens): arg_count = arg_count + 1 #the number of arguments are being counted. newqueens = rsolve(queens+[i],n) if newqueens != []: return newqueens return []# FAIL def print_board(queens): row = 0 n = len(queens) for pos in queens: for i in range(pos): sys.stdout.write( ". ") sys.stdout.write( "Q ") for i in range((n-pos)-1): sys.stdout.write( ". ") print('') time_start = time.time() ans=rsolve([],BOARD_SIZE) print_board(ans) print("The total number of arguments : %i" %arg_count) #printing the total number of arguments print("Total time taken is : %s" %(time.time()- time_start)) #time taken to run the program.
def rotate(lst): result = [lst[-1]] + lst[0:-1] return result # ls = [1, 2, 3, 4] # print(rotate(ls))
import random class Animal: animals = set() # Тут будем хранить существующих животных min_pos, max_pos = 0, 0 # Рамки позиций для животных def __init__(self, position): if not (Animal.min_pos <= position < Animal.max_pos): raise ValueError('Некорректное значение аргумента') random.seed() self.x = position self.direction = random.choice([-1, 0, 1]) if not (Animal.min_pos <= self.x + self.direction < Animal.max_pos): self.direction = 0 Animal.animals.add(self) def get_position(self): return self.x def is_dead(self): return self.hp == 0 def stop(self): self.direction = 0 def kill(self): Animal.animals.remove(self) @staticmethod def set_bounds(min_x, max_x): if min_x < 0 or max_x < 0: raise ValueError('Границы не могут быть отрицательными') if min_x > max_x: raise ValueError('Левая граница не может быть больше правой') Animal.min_pos, Animal.max_pos = min_x, max_x @staticmethod def count(): return len(Animal.animals) @staticmethod def is_meet(animal_1, animal_2): if animal_1.x > animal_2.x: raise ValueError('Второе животное должно быть правее первого') pos_1 = animal_1.x + animal_1.direction pos_2 = animal_2.x + animal_2.direction if pos_1 >= pos_2 or pos_1 >= pos_2 - animal_2.direction: return True return False class Bear(Animal): max_hp = 10 bears = set() # Тут будем хранить существующих медведов def __init__(self, position): super().__init__(position) self.hp = Bear.max_hp # max_life Bear.bears.add(self) def __str__(self): left, right = ' ', ' ' if self.direction == -1: left = '<' if self.direction == 1: right = '>' # result = left + str(self.hp) + right result = left + '🐻' + right return result @staticmethod def is_bear(obj): return obj in Bear.bears @staticmethod def count(): return len(Bear.bears) @staticmethod def set_max_hp(n): Bear.max_hp = n def go(self): Bear.bears.remove(self) self.x += self.direction self.direction = random.choice([-1, 0, 1]) if not (Animal.min_pos <= self.x + self.direction < Animal.max_pos): self.direction = 0 Bear.bears.add(self) self.hp -= 1 return self.x def stay(self): self.direction = 0 self.hp -= 1 def kill(self): Bear.bears.remove(self) super().kill() def eat(self): self.hp = Bear.max_hp + 1 class Fish(Animal): fishes = set() # Тут будем хранить существующих рыб def __init__(self, position): super().__init__(position) self.hp = 1 # max_life Fish.fishes.add(self) def __str__(self): left, right = ' ', ' ' if self.direction == -1: left = '<' if self.direction == 1: right = '>' # result = left + str(self.hp) + right result = left + '🐟' + right return result @staticmethod def is_fish(obj): return obj in Fish.fishes @staticmethod def count(): return len(Fish.fishes) def go(self): Fish.fishes.remove(self) self.x += self.direction self.direction = random.choice([-1, 0, 1]) if not (Animal.min_pos <= self.x + self.direction < Animal.max_pos): self.direction = 0 Fish.fishes.add(self) return self.x def stay(self): self.direction = 0 def kill(self): Fish.fishes.remove(self) super().kill()
# Функция, возвращающая список с делителями числа def get_dividers(num): num = abs(num) div_list = [] for div in range(- num, num + 1): if div != 0: if num % div == 0: div_list.append(div) # Заполняем список делителей return div_list print(*(get_dividers(int(input('Введите число: ')))))
def get_dividers(num): # Функция, возвращающая список с делителями числа num = abs(num) div_list = [] for div in range(-num, num + 1): if div: if not num % div: div_list.append(div) # Заполняем список делителей return div_list def is_prime(num): # Функция, определяющая, простое ли число if num < 2: return False div_list = get_dividers2(num) return len(div_list) == 4 def get_dividers2(num): # Версия через использование генераторов n = abs(num) return [k for k in range(-n, n + 1) if k and not n % k] def is_prime2(num): # Функция, определяющая, простое ли число, v2 return len(get_dividers2(num)) == 4 if num >= 2 else False n = int(input('Введите число: ')) print(is_prime(n)) print(is_prime2(n))
# -*- coding: utf-8 -*- class node: def __init__(self,key,p=None): self.p = p self.key = key self.right = None self.left = None self.height = 0 def __str__(self): return "Key: "+str(self.key) def checkparent(self): if self.p == None: return None elif self.p.left == self: return "left" else: return "right" def updateheight(self): if self.p != None: self.p.height = max(self.p.height,self.height+1) self.p.updateheight() class bst: def __init__(self,node=None): self.root=node if node != None: node.p = None def __str__(self): out = "" node = self.root def traverse(node,out): if node != None: out+=str(node)+" " traverse(node.left,out) out = traverse(node.left,out) traverse(node.right,out) out = traverse(node.right,out) return out return traverse(node,out) ''' def findleaves(self): self.leaves = [] node = self.root def traverse(node): if node != None: if node.right == None and node.left == None: self.leaves.append(node) traverse(node.left) traverse(node.right) traverse(node) def findheights(self): self.findleaves() level = self.leaves nextlevel = [] while len(level)!=0: for leaf in level: if leaf.p != None: leaf.p.height = max(leaf.p.height,leaf.height+1) if not leaf.p in nextlevel: nextlevel.append(leaf.p) level = nextlevel nextlevel = [] ''' def lefttree(self,node = None): if node == None: node = self.root if node.left != None: return bst(node.left) def righttree(self,node = None): if node == None: node = self.root if node.right != None: return bst(node.right) def insert(self,k,p=None): if self.root == None: self.root = node(k) else: if p == None: p = self.root if p.key >= k: if p.left == None: p.left = node(k,p) p.left.updateheight() else: self.insert(k,p.left) else: if p.right == None: p.right = node(k,p) p.right.updateheight() else: self.insert(k,p.right) def inserttree(self,tree,p = None): node = tree.root if self.root == None: self.root = node else: if p == None: p = self.root if p.key >= node.key: if p.left == None: p.left = node p.left.updateheight() else: self.inserttree(tree,p.left) else: if p.right == None: p.right = node p.right.updateheight() else: self.inserttree(tree,p.right) def find(self,k,p=None): if p == None: p = self.root if p.key == k: return True elif p.key > k: if p.left == None: return False else: return self.find(k,p.left) else: if p.right == None: return False else: return self.find(k,p.right) def findmin(self,node=None): if node == None: node = self.root if node.left == None: return node else: return self.findmin(node.left) def deletemin(self): minnode = self.findmin() minnode.p.left = None def next_larger(self,node): if node.right != None: return self.findmin(node.right) else: p = node.p while p!=None and node==p.right: node = p p = node.p return p def delete(self,node): p = node.p new = self.next_larger(node) left = node.left right = node.right new.p.left = new.right if new.right != None: new.right.p = new.p if node.checkparent() == "right": p.right = new elif node.checkparent() == "left": p.left = new new.left = left if node.right != new: new.right = right ''' root = node(12) tree = bst() tree.insert(12) tree.insert(23) tree.insert(10) tree.insert(33) tree.insert(5) tree.insert(17) tree.deletemin() tree.insert(5) tree.delete(tree.root.right) tree.insert(1) tree.findheights() print tree.root.height print tree.root.right print tree.root.right.right print tree.root.left print tree.find(23) print tree.find(18) print tree.findmin() print tree.next_larger(tree.root.left.left) tree.deletemin() print tree.findmin() tree.deletemin() print tree.findmin() tree.delete(root.right) '''
import math import numpy as np def reverse(L): if len(L) == 0: return [] return [L[-1]] + reverse(L[:-1]) def is_sorted(L): if len(L) <= 1: return True elif L[0] > L[1]: return False return is_sorted(L[1:]) def print_binary(string_so_far,digits_left): if digits_left == 0: print(string_so_far) else: print_binary(string_so_far + '0', digits_left - 1) print_binary(string_so_far + '1', digits_left - 1) def combinations(comb_so_far, list_of_lists): return if __name__ == "__main__": L = [4,1,7,9,3,0,6,5,2,8] print('Question 1') print(reverse(L)) print(reverse(L[:5])) print(reverse(L[5:])) print(reverse(L[:-2])) print(reverse(L[4:5])) print(reverse(L[5:5])) print('Question 2') print(is_sorted(L)) print(is_sorted([10,20,45,77])) print(is_sorted([])) print(is_sorted([2302])) print(is_sorted([10,20,45,77,65])) print('Question 3') print_binary('',2) print_binary('',3) print('Question 4') combinations([],[['salad', 'soup', 'pasta'],['steak', 'fish','lasagna'], ['cake', 'ice cream']]) combinations([],[['Dodgers', 'Braves', 'Mets','Padres'],['Yankees', 'Astros','Red Sox','Blue Jays']]) ''' Program Output Question 1 [8, 2, 5, 6, 0, 3, 9, 7, 1, 4] [3, 9, 7, 1, 4] [8, 2, 5, 6, 0] [5, 6, 0, 3, 9, 7, 1, 4] [3] [] Question 2 False True True True False Question 3 00 01 10 11 000 001 010 011 100 101 110 111 Question 4 salad steak cake salad steak ice cream salad fish cake salad fish ice cream salad lasagna cake salad lasagna ice cream soup steak cake soup steak ice cream soup fish cake soup fish ice cream soup lasagna cake soup lasagna ice cream pasta steak cake pasta steak ice cream pasta fish cake pasta fish ice cream pasta lasagna cake pasta lasagna ice cream Dodgers Yankees Dodgers Astros Dodgers Red Sox Dodgers Blue Jays Braves Yankees Braves Astros Braves Red Sox Braves Blue Jays Mets Yankees Mets Astros Mets Red Sox Mets Blue Jays Padres Yankees Padres Astros Padres Red Sox Padres Blue Jays '''
#Student: Sosa, Thomas # Course: CS 2302 Data Structures #Date of last modification: September 17 # Assignment: Lab 1 Recursion # TA: Anindita Nath # Professor: Olac Fuentes # Purpose: The purpose of this lab is to understand recursion uses stack to work import numpy as np import matplotlib.pyplot as plt import math import time def subsetsum(S,g): if g ==0: # The empty subset adds up to 0, return True return True if len(S)==0 or g<0 or sum(S)<g: return False if subsetsum(S[1:],g-S[0]): # Take S[0] return True return subsetsum(S[1:],g) # Don't take S[0] print(subsetsum([1,3,4,6,7,9],7)) def draw_squares(ax,n,p,w): if n>0: ax.plot(p[:,0],p[:,1],linewidth=1.0,color='b') # Draw rectangle i1 = [1,2,3,0,1] q = p*(1-w) + p[i1]*w draw_squares(ax,n-1,q,w) def draw_squares_stack(ax,n,p,w): S = [[n, p, w]] while len(S)>0: n, p, w = S.pop() if n>0: ax.plot(p[:,0],p[:,1],linewidth=1.0,color='b') i1 = [1,2,3,0,1] q = p*(1-w) + p[i1]*w S.append([n-1, q, w]) def circle(center,rad): # Returns the coordinates of the points in a circle given center and radius n = int(4*rad*math.pi) t = np.linspace(0,6.3,n) x = center[0]+rad*np.sin(t) y = center[1]+rad*np.cos(t) return x,y def draw_four_circles(ax,n,center,radius): if n>0: x,y = circle(center,radius) ax.plot(x,y,linewidth=1.0,color='b') draw_four_circles(ax,n-1,[center[0],center[1]+radius],radius/2) draw_four_circles(ax,n-1,[center[0],center[1]-radius],radius/2) draw_four_circles(ax,n-1,[center[0]+radius,center[1]],radius/2) draw_four_circles(ax,n-1,[center[0]-radius,center[1]],radius/2) def draw_four_circles_stack(ax,n,center,radius): S = [[n, center, radius]] while len(S)>0: n, center, radius = S.pop() if n>0: x,y = circle(center, radius) ax.plot(x,y,linewidth=1.0,color='b') S.append([n-1, [center[0],center[1]+radius], radius/2]) S.append([n-1, [center[0],center[1]-radius], radius/2]) S.append([n-1, [center[0]+radius,center[1]], radius/2]) S.append([n-1, [center[0]-radius,center[1]], radius/2]) def draw_tree(ax,n,x0,y0,dx,dy): if n>0: x = [x0-dx,x0,x0+dx] y = [y0-dy,y0,y0-dy] ax.plot(x,y,linewidth=1.0,color='b') draw_tree(ax,n-1,x0-dx,y0-dy,dx/2,dy) draw_tree(ax,n-1,x0+dx,y0-dy,dx/2,dy) def draw_tree_stack(ax,n,x0,y0,dx,dy): S = [[n,x0,y0,dx,dy]] while len(S)>0: n, x0, y0, dx, dy = S.pop() if n>0: x = [x0-dx,x0,x0+dx] y = [y0-dy,y0,y0-dy] ax.plot(x,y,linewidth=1.0,color='b') S.append([n-1, x0-dx, y0-dy, dx/2, dy]) S.append([n-1, x0+dx, y0-dy, dx/2, dy]) def draw_four_squares(ax,n,center,size): if n>0: x = center[0] + np.array([-size,-size,size,size,-size]) y = center[1] + np.array([-size,size,size,-size,-size]) ax.plot(x,y,linewidth=1.0,color='b') for i in range(4): draw_four_squares(ax,n-1,[x[i],y[i]],size/2) def draw_four_squares_stack(ax,n,center,size): S = [[n, center, size]] while len(S)>0: n, center, size = S.pop() if n>0: x = center[0] + np.array([-size,-size,size,size,-size]) y = center[1] + np.array([-size,size,size,-size,-size]) ax.plot(x,y,linewidth=1.0,color='b') for i in range(4): S.append([n-1, [x[i],y[i]], size/2]) def set_drawing_parameters_and_show(ax): show_axis = 'on' show_grid = 'True' ax.set_aspect(1.0) ax.axis(show_axis) plt.grid(show_grid) plt.show() if __name__ == "__main__": plt.close("all") # Close all figures orig_size = 1000.0 p = np.array([[0,0],[0,orig_size],[orig_size,orig_size],[orig_size,0],[0,0]]) fig, ax = plt.subplots() start = time.time() draw_squares(ax,6,p,.1) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build squares1 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('squares1.png') fig, ax = plt.subplots() start = time.time() draw_squares(ax,10,p,.2) end = time.time() set_drawing_parameters_and_show(ax) time_recusion = end-start print('time to build squares2 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('squares2.png') fig, ax = plt.subplots() start = time.time() draw_squares(ax,5,p,.3) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build squares3 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('squares3.png') fig, ax = plt.subplots() start = time.time() draw_squares_stack(ax,6,p,.1) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build squares1 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('squares1_stack.png') fig, ax = plt.subplots() start = time.time() draw_squares_stack(ax,10,p,.2) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build squares2 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('squares2_stack.png') fig, ax = plt.subplots() start = time.time() draw_squares_stack(ax,5,p,.3) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build squares3 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('squares3_stack.png') fig, ax = plt.subplots() start = time.time() draw_four_circles(ax, 2, [0,0], 100) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build four circles1 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('four_circles1.png') fig, ax = plt.subplots() start = time.time() draw_four_circles(ax, 3, [0,0], 100) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build four circles2 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('four_circles2.png') fig, ax = plt.subplots() start = time.time() draw_four_circles(ax, 4, [0,0], 100) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build four circles3 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('four_circles3.png') fig, ax = plt.subplots() start = time.time() draw_four_circles_stack(ax, 2, [0,0], 100) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build four circles1 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('four_circles1_stack.png') fig, ax = plt.subplots() start = time.time() draw_four_circles_stack(ax, 3, [0,0], 100) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build four circles2 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('four_circles2_stack.png') fig, ax = plt.subplots() start = time.time() draw_four_circles_stack(ax, 4, [0,0], 100) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build four circles3 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('four_circles3_stack.png') fig, ax = plt.subplots() start = time.time() draw_tree(ax, 4, 0, 0, 500,200) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build tree1 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('tree1.png') fig, ax = plt.subplots() start = time.time() draw_tree(ax, 5, 0, 0, 500,200) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build tree2 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('tree2.png') fig, ax = plt.subplots() start = time.time() draw_tree(ax, 6, 0, 0, 500,200) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build tree3 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('tree3.png') fig, ax = plt.subplots() start = time.time() draw_tree_stack(ax, 4, 0, 0, 500,200) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build tree1 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('tree1_stack.png') fig, ax = plt.subplots() start = time.time() draw_tree_stack(ax, 5, 0, 0, 500,200) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build tree2 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('tree2_stack.png') fig, ax = plt.subplots() start = time.time() draw_tree_stack(ax, 6, 0, 0, 500,200) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build tree3 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('tree3_stack.png') fig, ax = plt.subplots() start = time.time() draw_four_squares(ax, 2, [0, 0], 1000) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build four squares1 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('four_squares1.png') fig, ax = plt.subplots() start = time.time() draw_four_squares(ax, 3, [0, 0], 1000) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build four squares2 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('four_squares2.png') fig, ax = plt.subplots() start = time.time() draw_four_squares(ax, 4, [0, 0], 1000) end = time.time() set_drawing_parameters_and_show(ax) time_recursion = end-start print('time to build four squares3 using recursion: {:5.3f} seconds'.format(time_recursion)) fig.savefig('four_squares3.png') fig, ax = plt.subplots() start = time.time() draw_four_squares_stack(ax, 2, [0, 0], 1000) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build four squares1 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('four_squares_stack1.png') fig, ax = plt.subplots() start = time.time() draw_four_squares_stack(ax, 3, [0, 0], 1000) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build four squares2 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('four_squares_stack2.png') fig, ax = plt.subplots() start = time.time() draw_four_squares_stack(ax, 4, [0, 0], 1000) end = time.time() set_drawing_parameters_and_show(ax) time_stack = end-start print('time to build four squares3 using stack: {:5.3f} seconds'.format(time_stack)) fig.savefig('four_squares_stack3.png')
#total_secs = int(input("How many seconds, in total? ")) #hours = total_secs // 3600 #secs_still_remaining = total_secs % 3600 #minutes = secs_still_remaining // 60 #secs_finally_remaining = secs_still_remaining % 60 # #print("Hrs=", hours, "mins=", minutes, "secs=", secs_finally_remaining)
def set_level(level): return level * '\t' if __name__ == '__main__': alphabet = int(input('Quantos símbolos no alfabeto? ')) symbols = ['' for i in range(alphabet)] for i in range(alphabet): symbols[i] = input(f'Qual é o símbolo {i}? ') states_amount = int(input('Quantos estados? ')) states = ['' for i in range(states_amount)] for i in range(states_amount): states[i] = input(f'Qual é o estado {i}? ') initial_state = str() while initial_state not in states: initial_state = input('Qual é o estado inicial? ') final_states_amount = int(input('Quantos estados finais? ')) final_states = ['' for i in range(final_states_amount)] for i in range(final_states_amount): _state = input(f'Qual é o estado final {i}? ') while _state not in states: _state = input(f'Estado inexistente, qual é o estado final {i}? ') final_states[i] = _state alpha_delta = [[input(f'Para o estado {state} e o símbolo {symbol}, qual é o próximo estado? ') for symbol in symbols] for state in states] num_delta = [[states.index(state) if state in states else -1 for state in row ] for row in alpha_delta] print(f'\nAlfabeto -> {symbols}') print(f'Estados -> {states}') print(f'Estado inicial -> {initial_state}') print(f'Estados finais -> {final_states}') print('\nMatriz alfa de transição') for row in alpha_delta: print(row) print('\nMatriz numérica de transição') for row in num_delta: print(row) print('\nLinguagem\n') for i in range(len(states)): for j in range(len(symbols)): print(f'Para o estado {states[i]} e o símbolo {symbols[j]}, o próximo estado é {alpha_delta[i][j]}') automaton_name = input('Insira o nome do autômato: ') with open(f'{automaton_name}.c', 'w+') as automaton: automaton.write('#include <stdio.h>') automaton.write('\n#include <stdlib.h>') automaton.write('\n#include <conio.h>\n\n') automaton.write('int p = 0;\n') automaton.write('char fita[255];\n') for state in states: automaton.write(f'void {state}();\n') automaton.write(f'void aceita();\n') automaton.write(f'void rejeita();\n') automaton.write('\n\nint main(){\n\n') automaton.write(f'{set_level(1)}gets(fita);\n') automaton.write(f'{set_level(1)}{initial_state}();\n') automaton.write(f'{set_level(1)}return 0;\n') automaton.write('}\n') for line in range(len(states)): automaton.write(f'\nvoid {states[line]}(){"{"}\n') for col in range(len(symbols)): if num_delta[line][col] != -1: if col == 0: automaton.write(f'\n{set_level(1)}if(fita[p] == \'{symbols[col]}\'){"{"}\n') # Identação regular automaton.write(f'{set_level(2)}p++;\n') automaton.write(f'{set_level(2)}{states[num_delta[line][col]]}();\n') automaton.write(f'{set_level(1)}{"}"}\n') else: automaton.write(f'\n{set_level(1)}else') automaton.write(f'\n{set_level(2)}if(fita[p] == \'{symbols[col]}\'){"{"}\n') # Identação +1 automaton.write(f'{set_level(3)}p++;\n') automaton.write(f'{set_level(3)}{states[num_delta[line][col]]}();\n') automaton.write(f'{set_level(2)}{"}"}\n') if states[line] in final_states: automaton.write(f'{set_level(1)}else\n') automaton.write(f'{set_level(2)}if(fita[p] == \'\\0\'){"{"}\n') automaton.write(f'{set_level(3)}aceita();\n') automaton.write(f'{set_level(2)}{"}"}') automaton.write(f'\n{set_level(1)}else{"{"}\n') automaton.write(f'{set_level(2)}rejeita();\n') automaton.write(f'{set_level(1)}{"}"}\n{"}"}') automaton.write('\nvoid aceita(){\n') automaton.write(f'\n{set_level(1)}printf("ACEITO");\n') automaton.write(f'{set_level(1)}exit(0);\n') automaton.write('}\n') automaton.write('\nvoid rejeita(){\n') automaton.write(f'\n{set_level(1)}printf("REJEITADO");\n') automaton.write(f'{set_level(1)}exit(-1);\n') automaton.write('}\n')
import threading import multiprocessing import time def Fibonacci_driver(n): if n<0: print("Invalid Input") elif n==1: return 0 elif n==2: return 1 else: return Fibonacci_driver(n-1)+Fibonacci_driver(n-2) def Fibonacci(n): print(f"Fib {n} is {Fibonacci_driver(n)}") if __name__ == "__main__": num_tasks = 5 # creating thread start = time.time() threads_list = [] for i in range(num_tasks): threads_list.append(threading.Thread(target=Fibonacci, args=(40,))) for i in range(num_tasks): threads_list[i].start() for i in range(num_tasks): threads_list[i].join() end = time.time() thread_duration = end-start print(f"Threads completed their tasks in {thread_duration} s!\n") # creating process start = time.time() processes_list = [] for i in range(num_tasks): processes_list.append(multiprocessing.Process(target=Fibonacci, args=(40,)) ) for i in range(num_tasks): processes_list[i].start() for i in range(num_tasks): processes_list[i].join() end = time.time() process_duration = end-start print(f"Processes completed their tasks in {process_duration} s!\n") if process_duration < thread_duration: print("Multiprocessing wins!") else: print("Multithreading wins!")
Users = { 'huy' : { 'name' : 'Nguyen Quang Huy', 'age' : 29 }, 'don' : { "name" : 'Don zoombie', 'age' : 23 }, 'tuong' : { 'name' : "Đào Cí Cươ", 'age' : 15 } } def user_info(username,Users): return_string_of_informations= "" for info in Users[username]: return_string_of_informations += str(info) return_string_of_informations += ":" return_string_of_informations += str(Users[username][info]) return_string_of_informations += "<br/>" return return_string_of_informations print(user_info('tuong',Users)) print()
import urllib2 from PIL import Image, ImageOps, ImageDraw import ssl import os # Download the user's facebook image def download(id): url = "https://graph.facebook.com/"+id+"/picture?height=200&width=200" # evil - bypass ssl certification ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE file_name = id+".jpg" u = urllib2.urlopen(url,context=ctx) # create file f = open(file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading profile picture: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() # make the image rounded using crop and save it as PNG def crop(file_name): f = file_name+".jpg" im = Image.open(f) bigsize = (im.size[0] * 3, im.size[1] * 3) mask = Image.new('L', bigsize, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + bigsize, fill=255) mask = mask.resize(im.size, Image.ANTIALIAS) im.putalpha(mask) output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.putalpha(mask) o = file_name+".png" output.save(o) os.remove(f) fbids = open('fbids.txt','r') for line in fbids: l = str(line.rstrip()) download(l) crop(l)
a = int(input("starts from:- ")) b = int(input("to:- ")) c = ('0','2','4','6','8') d = ('1','3','5','7','9') while(str(a).endswith(c)): print (a) a = a+2 if(a>b): break continue while(str(a).endswith(d)): print (a+1) a = a+2 if(a>=b): break continue
import random def main(): welcome() name_of_player = player_name() guessing_number = [] for number in random_number(): guessing_number.append(number) print(guessing_number) guessing(name_of_player, guessing_number) def welcome(): print("Hi there!\n" "I've generated a random 4 digit number for you.\n" "Let's play a bulls and cows game.\n" + 60 * "=") def player_name(): return input("What is your name? ") def random_number(): return random.sample(range(0, 10), 4) def player_turn(): turn = input("Enter a number: ") if len(turn) != 4: print("Enter only four characters!!") return player_turn() elif turn.isalpha(): print("Enter numbers!!") return player_turn() turn_list = [] for i in turn: turn_list.append(int(i)) return turn_list def guessing(name, guess_number): guesses = 0 while True: index = 0 bulls = 0 cow = 0 for number in player_turn(): if number == guess_number[index]: bulls += 1 index += 1 elif number in guess_number: cow += 1 index += 1 else: index += 1 guesses += 1 if bulls == 4: print(f"Correct, you've guessed the right number in " f"|{guesses}| guesses!\n" + 60 * "=") rank(guesses) player_leaderboard(name, guesses) return False print("|", bulls, "<< Bulls |", cow, "<< Cow |" , guesses, "<< Guesses |\n" + 60 * "=") def rank(guess): if guess < 3: print("You are MASTER!!! or cheater :)") elif 3 <= guess <= 7: print("You are AMAZING player!") elif 7 <= guess <= 12: print("You are AVARAGE player!") else: print("You are not so good at this game :(") def player_leaderboard(name, guess): leaderboard = open("leaderboard.txt", "r") line = leaderboard.readline() txt = line.split() leaderboard.close() if not txt or guess <= int(txt[1]): leaderboard = open("leaderboard.txt", "w") leaderboard.write(name + " " + str(guess)) leaderboard.close() return print(f"NOW YOU ARE BEST PLAYER >> " f"{name} << guesses: |{guess}|") else: return print(f"ALL TIME BEST PLAYER:" f" >> {txt[0]} << GUESSES: |{txt[1]}|") main()
# -*- coding: utf-8 -*- """ HackerRank - Frequency Queries https://www.hackerrank.com/challenges/frequency-queries Created on Sun Dec 9 14:01:48 2018 @author: Arthur Dysart """ ## REQUIRED MODULES from collections import defaultdict import sys ## MODULE DEFINITIONS class Solution: """ Iterate over all elements in input array. Time complexity: O(n) - Iterate over all elements in input array Space complexity: O(max(n, k)) - Amortized collect all elements in hash maps """ def eval_freq_queries(self, a): """ Executes queries and evaluates presence of target frequences. :param list[tup[int, int]] a: array of queries as integer tuples :return: array of integer results from target frequency evaluation :rtype: list[int] """ if not a: return list() t = list() # Initialize value-frequency and frequency-presence hash maps d = defaultdict(int) f = defaultdict(int) for i, v in a: if i == 1: # Add target value to hash maps if f[d[v]] > 0: # Remove element from frequency hash map f[d[v]] -= 1 d[v] += 1 f[d[v]] += 1 elif (i == 2 and d[v] > 0): # Remove target value from hash maps f[d[v]] -= 1 d[v] -= 1 f[d[v]] += 1 elif i == 3: # Evaluate whether target frequency is present if f[v] > 0: t.append(1) else: t.append(0) return t class Solution2: """ Iterate over all elements in input array. Time complexity: O(n) - Iterate over all elements in input array Space complexity: O(max(n, k)) - Amortized iterate over all items in frequency-presence hash map """ def eval_freq_queries(self, a): """ Executes queries and evaluates presence of target frequences. :param list[tup[int, int]] a: array of queries as integer tuples :return: array of integer results from target frequency evaluation :rtype: list[int] """ if not a: return list() t = list() d = defaultdict(int) # Create hash map of code-operation pairs o = {1: (lambda x, d = d: d.update([(x, d[x] + 1)])), 2: (lambda x, d = d: d.update([(x, d[x] - 1)]) if d[0] >= 0 else None), 3: (lambda x, d = d, t = t: t.append(1) if x in d.values() else t.append(0))} for i, v in a: o[i](v) return t class Input: def stdin(self, sys_stdin): """ Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: array of queries as integer tuples :rtype: list[tup[int, int]] """ inputs = [x.strip("[]\"\n") for x in sys_stdin] n = int(inputs[0]) a = [self.cast_tup(inputs[x]) for x in range(1, n + 1, 1)] return a def cast_tup(self, sub_input): """ Transforms target input string into tuple of integers. :param int x: target array index :param str sub_input: target string from standard input :return: tuple of parsed integers :rtype: tup[int, int] """ if not sub_input: return tuple() t = tuple(int(x) for x in sub_input.split()) return t ## MAIN MODULE if __name__ == "__main__": # Import exercise parameters a = Input()\ .stdin(sys.stdin) # Evaluate solution z = Solution()\ .eval_freq_queries(a) print(*z, sep = "\n") ## END OF FILE
# -*- coding: utf-8 -*- """ HackerRank - Sock Merchant https://www.hackerrank.com/challenges/sock-merchant Created on Mon Nov 12 22:29:31 2018 @author: Arthur Dysart """ ## REQUIRED MODULES from collections import Counter import sys ## MODULE DEFINITIONS class Solution: """ Iteration over all elements of array. Time complexity: O(n) - Traverse all elements of array Space complexity: O(n) - Amortized Counter object contains all unique socks """ def count_sock_pairs(self, n, a): """ Determine minimum number of matching sock pairs. :param int n: number of individual socks :param list[int] a: array of all socks :return: maximum number of matching pairs of socks :rtype: int """ if (not n or not a): return -1 c = Counter(a) p = 0 for i, q in c.items(): p += q // 2 return p class Solution2: """ Iteration over all elements in array. Time complexity: O(n) - Traverse all elements of array Space complexity: O(n) - Amortized dictionary contains all unique socks """ def count_sock_pairs(self, n, a): """ Determine minimum number of matching sock pairs. :param int n: number of individual socks :param list[int] a: array of all socks :return: maximum number of matching pairs of socks :rtype: int """ if (not n or not a): return -1 c = {} p = 0 for i in range(n): t = a[i] if t in c: # Increase total sock count c[t] += 1 if c[t] % 2 == 0: # Increase sock pair count p += 1 else: c[t] = 1 return p class Input: def stdin(self, sys_stdin): """ Imports standard input. :param _io.TextIOWrapper sys_stdin: standard input :return: length of array and input array :rtype: tuple[int, list[int]] """ inputs = [x for x in sys_stdin] n = int(inputs[0]) a = [int(x) for x in inputs[1].split()] return n, a ## MAIN MODULE if __name__ == "__main__": # Import exercise parameters n, a = Input()\ .stdin(sys.stdin) # Evaluate solution z = Solution()\ .count_sock_pairs(n, a) print(z) ## END OF FILE
# bubblesort.py def bubbleSort(array): n = len(array) # Traverse all the array elements for i in range(n-1, 0, -1): for j in range(i): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j]
def repeat_string(string, count): print(f'{string}' * count) text = input() repeated = int(input()) repeat_string(text, repeated)
degrees = int(input()) time_of_day = input() outfit = None shoes = None if (10 <= degrees <= 18) and (time_of_day == "Morning"): outfit = "Sweatshirt" shoes = "Sneakers" elif (10 <= degrees <= 18) and (time_of_day == "Afternoon"): outfit = "Shirt" shoes = "Moccasins" elif (10 <= degrees <= 18) and (time_of_day == "Evening"): outfit = "Shirt" shoes = "Moccasins" elif (18 < degrees <= 24) and (time_of_day == "Morning"): outfit = "Shirt" shoes = "Moccasins" elif (18 < degrees <= 24) and (time_of_day == "Afternoon"): outfit = "T-Shirt" shoes = "Sandals" elif (18 < degrees <= 24) and (time_of_day == "Evening"): outfit = "Shirt" shoes = "Moccasins" elif (degrees >= 25) and (time_of_day == "Morning"): outfit = "T-Shirt" shoes = "Sandals" elif (degrees >= 25) and (time_of_day == "Afternoon"): outfit = "Swim Suit" shoes = "Barefoot" elif (degrees >= 25) and (time_of_day == "Evening"): outfit = "Shirt" shoes = "Moccasins" print(f"It's {degrees} degrees, get your {outfit} and {shoes}.")
budget = float(input()) statist = int(input()) price = float(input()) dekor = 0.10 * budget clothing = statist * price if statist > 150: discount = 0.10 * clothing total_clothing = clothing - discount total_movie = dekor + total_clothing money = abs(budget - total_movie) else: total_movie = dekor + clothing money = abs(budget - total_movie) if total_movie > budget: print(f"""Not enough money! Wingard needs {money:.2f} leva more.""") else: print(f"""Action! Wingard starts filming with {money:.2f} leva left.""")
price_flour = float(input()) kg_flour = float(input()) kg_sugar = float(input()) eggs = int(input()) yeast = int(input()) price_sugar = price_flour * 0.75 price_eggs = price_flour * 1.1 price_yeast = price_sugar * 0.2 summ_flour = price_flour * kg_flour summ_sugar = price_sugar * kg_sugar summ_eggs = price_eggs * eggs summ_yeast = price_yeast * yeast total = summ_flour + summ_sugar + summ_eggs + summ_yeast print(f"{total:.2f}")
import sys n = int(input()) max_number = -sys.maxsize - 1 min_number = sys.maxsize for num in range(n): current_number = int(input()) if current_number > max_number: max_number = current_number if current_number < min_number: min_number = current_number print(f"""Max number: {max_number} Min number: {min_number}""")
decimal_list = list(map(float, input().split())) restart = True while restart: index_counter = 1 for num in decimal_list: if index_counter >= len(decimal_list): restart = False break if num == decimal_list[index_counter]: decimal_list[index_counter] = float(num) + float(decimal_list[index_counter]) del decimal_list[index_counter - 1] restart = True break else: index_counter += 1 for num in decimal_list: multiply = num * 10 if multiply % 10 == 0: remove_zeros = multiply / 10 print(num, end=' ') else: remove_zeros = multiply / 10 print(num, end=' ') print(string_with_decimal)
area_yard = float(input()) price_yard = area_yard * 7.61 discount = price_yard * 0.18 final_price = price_yard - discount print(f'The final price is: {final_price:.2f} lv.') print(f'The discount is: {discount:.2f} lv.')
def multiply_evens_by_odds(number): even_sum = 0 odd_sum = 0 for digit in str(number): last_number = abs(number) % 10 if last_number % 2 == 0: even_sum += last_number else: odd_sum += last_number number = abs(number) // 10 return even_sum * odd_sum number = int(input()) print(multiply_evens_by_odds(number))
x_1 = float(input()) y_1 = float(input()) x_2 = float(input()) y_2 = float(input()) x = float(input()) y = float(input()) if (x == x_1 or x == x_2) and (y_1 <= y <= y_2): print("Border") elif (y == y_1 or y == y_2) and (x_1 <= x <= x_2): print("Border") else: print("Inside / Outside")
import datetime birthday_one = input() datetime_object = datetime.datetime.strptime(birthday_one, '%d-%m-%Y').date() modified_date = datetime_object + datetime.timedelta(days=1000) date = modified_date.strftime("%d-%m-%Y") print(date)
campaign = int(input()) confectioners = int(input()) cakes = int(input()) waffles = int(input()) pancakes = int(input()) cakes = cakes * 45 waffles = waffles * 5.80 pancakes = pancakes * 3.20 total_day = (cakes + waffles + pancakes) * confectioners total_campaign = total_day * campaign net = total_campaign - 1 / 8 * total_campaign print(f'{net:.2f}')
number = float(input()) unit_input = input() unit_output = input() if unit_input == "mm" and unit_output == "m": result = number / 1000 elif unit_input == "mm" and unit_output == "cm": result = number / 10 elif unit_input == "m" and unit_output == "cm": result = number * 100 elif unit_input == "m" and unit_output == "mm": result = number * 1000 elif unit_input == "cm" and unit_output == "mm": result = number * 10 elif unit_input == "cm" and unit_output == "m": result = number / 100 print(f"{result:.3f}")
import math vineyard = int(input()) grapes_meter = float(input()) needed_liters = int(input()) workers = int(input()) total_grapes = vineyard * grapes_meter wine_produced = (0.40 * total_grapes) / 2.5 if wine_produced < needed_liters: lack_wine = needed_liters - wine_produced print(f"It will be a tough winter! More {math.floor(lack_wine)} liters wine needed.") else: wine_left = wine_produced - needed_liters wine_workers = wine_left / workers print(f"""Good harvest this year! Total wine: {math.floor(wine_produced)} liters. {math.ceil(wine_left)} liters left -> {math.ceil(wine_workers)} liters per person.""")
for letter in range(ord("a"), ord("{")): print(chr(letter))