text
stringlengths
37
1.41M
#Melhore o jogo do DESAFIO 28 onde o computador vai “pensar” em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. from random import randint import os n = randint(1, 10) cont = 1 print(10*'-=-') print('{:^30}'.format("JOGO DA ADIVINHAÇÃO")) print(10*'-=-') na = int(input('Digite um número inteiro e veja se acertou: ')) while na != n: os.system("clear") print('{} tentativas'.format(cont)) print(10*'-=-') print('{:^30}'.format("JOGO DA ADIVINHAÇÃO")) print(10*'-=-') na = int(input('Você errou!! Tente novamente: ')) cont = cont + 1 os.system("clear") print('PARABÉNS VOCÊ ACERTOU!!!') print('Usando {} tentativas'.format(cont)) print('Número do computador: {}'.format(n)) print('Seu número: {} '.format(na))
""" Test suite for Leetcode Arrays 101: In-Place Operations https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/ """ from leetcode.arrays_101.in_place_ops import moveZeros from leetcode.arrays_101.in_place_ops import sortArrayByParity from leetcode.arrays_101.in_place_ops import replaceElements def testReplaceElements(): array = [17, 18, 5, 4, 6, 1] out = replaceElements(array) assert out == [18, 6, 6, 6, 1, -1] assert id(array) == id(out) def testMoveZeros(): array = [0, 1, 0, 3, 12] moveZeros(array) assert array == [1, 3, 12, 0, 0] def testSortArrayByParity(): array = [3, 1, 2, 4] out = sortArrayByParity(array) assert out == [2, 4, 3, 1] assert id(out) == id(array)
""" Leetcode Arrays 101: In-Place Operations https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/ """ from typing import List def replaceElements(arr: List[int]) -> List[int]: """ Replace every element in the array with the greatest element among the elements to its right, and replace the last element with -1. :param arr: array of integers to mutate :return: mutated array """ n = -1 for i in range(len(arr)-1, -1, -1): tmp = arr[i] arr[i] = n if tmp > arr[i]: n = tmp return arr def moveZeros(nums: List[int]) -> None: """ Given an integer array of nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements :param nums: array whose zeros should be moved :return: None """ pos = 0 for i, value in enumerate(nums): if value != 0: nums[pos], nums[i] = nums[i], nums[pos] pos += 1 def sortArrayByParity(A: List[int]) -> List[int]: """ Given an array A of non-negative integers, return an array consisting of all even elements of A, followed by all the odd elements of A. :param A: list to re-arrange in-place :return: even members of A followed by odd members of A """ pos = 0 for i, value in enumerate(A): if value % 2 == 0: A[pos], A[i] = A[i], A[pos] pos += 1 return A
""" Test suite for Leetcode Arrays 101: Accessing Arrays https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3238/ """ from leetcode.arrays_101.accessing import findNumbers from leetcode.arrays_101.accessing import findMaxConsecutiveOnes from leetcode.arrays_101.accessing import sortedSquares def testFindMaxConsecutiveOnes(): assert findMaxConsecutiveOnes([]) == 0 assert findMaxConsecutiveOnes([0, 0, 0]) == 0 assert findMaxConsecutiveOnes([1, 1]) == 2 assert findMaxConsecutiveOnes([1, 1, 0, 1, 1, 1]) == 3 def testFindNums(): assert findNumbers([555, 901, 482, 1771]) == 1 assert findNumbers([12, 345, 2, 6, 7896]) == 2 def testSortedSquares(): assert sortedSquares([-4, -1, 0, 3, 10]) == [0, 1, 9, 16, 100]
def compute(annual_salary, portion_saved, total_cost): portion_down_payment = 0.25 num_month = 0 monthly_salary = (annual_salary/12.0) saving = 0 current_savings = 0 r = 0.04 while current_savings < (total_cost * portion_down_payment): saving = monthly_salary * portion_saved current_savings = current_savings + current_savings * r / 12.0 current_savings = current_savings + saving num_month += 1 return num_month def compute_geometrical(annual_salary, portion_saved, total_cost): portion_down_payment = 0.25 num_month = 0 monthly_salary = (annual_salary/12.0) saving = 0 current_savings = 0 r = 0.04 while current_savings < (total_cost * portion_down_payment): """ Formula for Compound Interest """ saving = (annual_salary/12.0) * portion_saved current_savings = (saving/(r/12))*((1 + (r/12))**(num_month + 1) - 1) num_month += 1 return num_month """ def main(): annual_salary = float(input("Enter your annual salary: ")) portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ")) total_cost = float(input("Enter the cost of your dream home: ")) print("Number of months: %d" % compute_geometrical(annual_salary, portion_saved, total_cost)) if __name__ == "__main__": main() """
from ConvertNumbers import Number num = input('Digite um número: ') if num != '0': try: n = Number(num) print (n.literal) except ValueError: print("Valor inválido") else: print("zero")
import turtle brad=turtle.Turtle() def draw_aquare(): window=turtle.Screen() window.bgcolor("white") brad.shape("turtle") brad.color("white") brad.speed(5) brad.setposition(-150, 0) brad.color("blue") for i in range(36): brad.forward(300) brad.right(120) i+=1 for j in range(0,10,2): brad.right(10) j+=1 draw_aquare()
from random import randint def arma(): roll = randint(1, 100) if roll <= 3: return('Adaga') elif roll <= 5: return('Alabarda') elif roll <= 7: return('Alfange') elif roll <= 9: return('Arco composto') elif roll <= 12: return('Arco curto') elif roll <= 15: return('Arco longo') elif roll <= 17: return('Azagaia') elif roll <= 20: return('Besta leve') elif roll <= 23: return('Besta pesada') elif roll <= 26: return('Bordão') elif roll <= 28: return('Chicote') elif roll <= 31: return('Cimitarra') elif roll <= 33: return('Clava') elif roll == 34: return('Corrente com cravos') elif roll <= 36: return('Espada bastarda') elif roll <= 39: return('Espada curta') elif roll == 40: return('Espada de duas lâminas') elif roll <= 43: return('Espada grande') elif roll <= 46: return('Espada longa') elif roll == 47: return('Espada táurica') elif roll <= 50: return('Florete') elif roll <= 52: return('Foice') elif roll <= 55: return('Funda') elif roll == 56: return('Katana') elif roll <= 59: return('Lança') elif roll == 60: return('Lança montada') elif roll <= 63: return('Maça') elif roll <= 66: return('Machadinha') elif roll == 67: return('Machado anão') elif roll <= 70: return('Machado de batalha') elif roll <= 73: return('Machado grande') elif roll <= 75: return('Mangual') elif roll == 76: return('Manopla') elif roll == 77: return('Marreta estilhaçadora') elif roll <= 79: return('Martelo') elif roll <= 81: return('Martelo de guerra') elif roll == 82: return('Mosquete') elif roll <= 87: roll = randint(1, 100) if roll <= 20: return('Munição: Balas(x50)') elif roll <= 60: return('Munição: Flechas(x50)') elif roll <= 70: return('Munição: Pólvora(x50)') elif roll <= 100: return('Munição: Virotes(x50)') elif roll == 88: return('Nunchaku') elif roll == 89: return('Picareta') elif roll == 90: return('Pique') elif roll == 91: return('Pistola') elif roll == 92: return('Rede') elif roll == 93: return('Sabre serrilhado') elif roll == 94: return('Sai') elif roll == 95: return('Shuriken') elif roll <= 97: return('Tacape') elif roll == 98: return('Tai-tai') elif roll == 99: return('Tridente') elif roll == 100: return('Wakisashi')
import numbers import numpy as np from .utils import DEFAULT_SETTINGS ds = DEFAULT_SETTINGS['geometry'] class Geometry: """ Get the model geometry. """ def __init__(self, d=ds[0], lx=ds[1], ly=ds[2], lz=ds[3]): self.d = int(d) self.lx = lx self.ly = ly self.lz = lz self.validateGeometry() def checkLength(self, l, direction): ''' Check that the length is a valid value. ''' if l is None: raise ValueError('Please set the length in the {0} direction.' .format(direction)) if not isinstance(l, numbers.Real): raise ValueError('l={0} is not a valid length.' .format(l)) else: if l <= 0.0: raise ValueError('l{0} must be positive.' .format(direction)) # Static method? def validateGeometry(self): ''' Check that the user inputs are valid. ''' if self.d == 1: self.checkLength(self.lx, 'x') elif self.d == 2: self.checkLength(self.lx, 'x') self.checkLength(self.ly, 'y') elif self.d == 3: self.checkLength(self.lx, 'x') self.checkLength(self.ly, 'y') self.checkLength(self.lz, 'z') else: raise ValueError('d={0} is not a valid dimension.' .format(self.d)) def getName(self): ''' Return the geometry name. ''' if self.d == 1: return 'line' elif self.d == 2: return 'rectangle' else: # 3D return 'block' def getMaxLength(self): ''' Get the maximum length. ''' if self.d == 1: return self.lx elif self.d == 2: return np.max(np.array([self.lx, self.ly])) else: return np.max(np.array([self.lx, self.ly, self.lz])) def getSettings(self): '''Return the geometry settings. ''' if self.d == 1: return [1, self.lx, 0.0, 0.0] elif self.d == 2: return [1, self.lx, self.ly, 0.0] else: # 3D return [1, self.lx, self.ly, self.lz] def printSettings(self): """Return the settings as a string for file I/O """ s = self.getSettings() return ('Geometry={0},{1},{2},{3}\n' .format(s[0], s[1], s[2], s[3]))
# coding: utf-8 # # Capstone Project 1: MuscleHub AB Test # ## Step 1: Get started with SQL # Like most businesses, Janet keeps her data in a SQL database. Normally, you'd download the data from her database to a csv file, and then load it into a Jupyter Notebook using Pandas. # # For this project, you'll have to access SQL in a slightly different way. You'll be using a special Codecademy library that lets you type SQL queries directly into this Jupyter notebook. You'll have pass each SQL query as an argument to a function called `sql_query`. Each query will return a Pandas DataFrame. Here's an example: # In[3]: # This import only needs to happen once, at the beginning of the notebook from codecademySQL import sql_query # In[4]: # Here's an example of a query that just displays some data sql_query(''' SELECT * FROM visits LIMIT 5 ''') # In[ ]: # Here's an example where we save the data to a DataFrame df1 = sql_query(''' SELECT * FROM applications LIMIT 5 ''') print df1 # ## Step 2: Get your dataset # Let's get started! # # Janet of MuscleHub has a SQLite database, which contains several tables that will be helpful to you in this investigation: # - `visits` contains information about potential gym customers who have visited MuscleHub # - `fitness_tests` contains information about potential customers in "Group A", who were given a fitness test # - `applications` contains information about any potential customers (both "Group A" and "Group B") who filled out an application. Not everyone in `visits` will have filled out an application. # - `purchases` contains information about customers who purchased a membership to MuscleHub. # # Use the space below to examine each table. # In[11]: # Examine visits here visits = sql_query(''' SELECT * FROM visits LIMIT 5 ''') visits_count = sql_query(''' SELECT COUNT(*) FROM visits LIMIT 5 ''') print visits print visits_count # In[7]: # Examine fitness_tests here fitness_tests = sql_query(''' SELECT * FROM fitness_tests LIMIT 5 ''') fitness_tests_count = sql_query(''' SELECT COUNT(*) FROM fitness_tests LIMIT 5 ''') print fitness_tests print fitness_tests_count # In[8]: # Examine applications here applications = sql_query(''' SELECT * FROM applications LIMIT 5 ''') applications_count = sql_query(''' SELECT COUNT(*) FROM applications LIMIT 5 ''') print applications print applications_count # In[9]: # Examine purchases here purchases = sql_query(''' SELECT * FROM purchases LIMIT 5 ''') purchases_count = sql_query(''' SELECT COUNT(*) FROM purchases LIMIT 5 ''') print purchases print purchases_count # In[12]: # We'd like to download a giant DataFrame containing all of this data. You'll need to write a query that does the following things: 1. Not all visits in `visits` occurred during the A/B test. You'll only want to pull data where `visit_date` is on or after `7-1-17`. 2. You'll want to perform a series of `LEFT JOIN` commands to combine the four tables that we care about. You'll need to perform the joins on `first_name`, `last_name`, and `email`. Pull the following columns: - `visits.first_name` - `visits.last_name` - `visits.gender` - `visits.email` - `visits.visit_date` - `fitness_tests.fitness_test_date` - `applications.application_date` - `purchases.purchase_date` Save the result of this query to a variable called `df`. get_ipython().set_next_input(u'Hint: your result should have 5004 rows. Does it');get_ipython().magic(u'pinfo it') # In[13]: # 1. Not all visits in visits occurred during the A/B test. You'll only want to pull data where visit_date is on or after 7-1-17. visits_after_start = sql_query(''' SELECT * FROM visits WHERE visit_date > '7-01-17' LIMIT 5 ''') visits_after_start_count = sql_query(''' SELECT COUNT(*) FROM visits WHERE visit_date > '7-01-17' LIMIT 5 ''') print visits_after_start print visits_after_start_count # 2. You'll want to perform a series of LEFT JOIN commands to combine the four tables that we care about. You'll need to perform the joins on first_name, last_name, and email. df = sql_query(''' SELECT visits.first_name, visits.last_name, visits.gender, visits.email, visits.visit_date, fitness_tests.fitness_test_date, applications.application_date, purchases.purchase_date FROM visits LEFT JOIN fitness_tests ON visits.first_name = fitness_tests.first_name AND visits.last_name = fitness_tests.last_name AND visits.email = fitness_tests.email LEFT JOIN applications ON visits.first_name = applications.first_name AND visits.last_name = applications.last_name AND visits.email = applications.email LEFT JOIN purchases ON visits.first_name = purchases.first_name AND visits.last_name = purchases.last_name AND visits.email = purchases.email WHERE visit_date > '7-01-17' ''') print df # ## Step 3: Investigate the A and B groups # We have some data to work with! Import the following modules so that we can start doing analysis: # - `import pandas as pd` # - `from matplotlib import pyplot as plt` # In[14]: import pandas as pd from matplotlib import pyplot as plt # We're going to add some columns to `df` to help us with our analysis. # # Start by adding a column called `ab_test_group`. It should be `A` if `fitness_test_date` is not `None`, and `B` if `fitness_test_date` is `None`. # In[15]: ab_test_group_lambda = lambda row: 'A' if row.fitness_test_date > 0 else 'B' df['ab_test_group'] = df.apply(ab_test_group_lambda, axis = 1) print df # Let's do a quick sanity check that Janet split her visitors such that about half are in A and half are in B. # # Start by using `groupby` to count how many users are in each `ab_test_group`. Save the results to `ab_counts`. # In[16]: ab_counts = df.groupby('ab_test_group').first_name.count() print ab_counts # We'll want to include this information in our presentation. Let's create a pie cart using `plt.pie`. Make sure to include: # - Use `plt.axis('equal')` so that your pie chart looks nice # - Add a legend labeling `A` and `B` # - Use `autopct` to label the percentage of each group # - Save your figure as `ab_test_pie_chart.png` # In[17]: ab_counts_names = ["A", "B"] plt.pie(ab_counts, autopct='%0.1f%%') plt.axis('equal') plt.legend(ab_counts_names) plt.savefig('ab_test_pie_chart.png') plt.show() # ## Step 4: Who picks up an application? # Recall that the sign-up process for MuscleHub has several steps: # 1. Take a fitness test with a personal trainer (only Group A) # 2. Fill out an application for the gym # 3. Send in their payment for their first month's membership # # Let's examine how many people make it to Step 2, filling out an application. # # Start by creating a new column in `df` called `is_application` which is `Application` if `application_date` is not `None` and `No Application`, otherwise. # In[18]: is_application_lambda = lambda row: 'Application' if row.application_date > 0 else 'No Application' df['is_application'] = df.apply(is_application_lambda, axis = 1) print df # Now, using `groupby`, count how many people from Group A and Group B either do or don't pick up an application. You'll want to group by `ab_test_group` and `is_application`. Save this new DataFrame as `app_counts` # In[19]: app_counts = df.groupby('is_application').first_name.count() print app_counts # We're going to want to calculate the percent of people in each group who complete an application. It's going to be much easier to do this if we pivot `app_counts` such that: # - The `index` is `ab_test_group` # - The `columns` are `is_application` # Perform this pivot and save it to the variable `app_pivot`. Remember to call `reset_index()` at the end of the pivot! # In[60]: app_counts = df.groupby(['ab_test_group', 'is_application']).first_name.count().reset_index() app_pivot = app_counts.pivot(columns='is_application', index='ab_test_group', values='first_name').reset_index() print app_pivot # Define a new column called `Total`, which is the sum of `Application` and `No Application`. # In[145]: app_pivot_renamed = app_pivot.rename(columns={'Application': 'application', 'No Application': 'no_application'}) total_lambda = lambda row: row.application + row.no_application app_pivot_renamed['Total'] = app_pivot_renamed.apply(total_lambda, axis = 1) print app_pivot_renamed # Calculate another column called `Percent with Application`, which is equal to `Application` divided by `Total`. # In[146]: percent_with_app = lambda row: (100 * (row.application) / (row.Total)) app_pivot_renamed['percent_with_application'] = app_pivot_renamed.apply(percent_with_app, axis = 1) print app_pivot_renamed # It looks like more people from Group B turned in an application. Why might that be? # # We need to know if this difference is statistically significant. # # Choose a hypothesis tests, import it from `scipy` and perform it. Be sure to note the p-value. # Is this result significant? # In[149]: from scipy.stats import binom_test pval = binom_test(325, n=2500, p=0.09) print pval # The result is a p-value of 0.00000000004, less than 0.05, which means the null hypothesis is rejected and it is certain that # there is a difference. The people in B group who did NOT do the fitness test, are more liekly to submit an application. # ## Step 4: Who purchases a membership? # Of those who picked up an application, how many purchased a membership? # # Let's begin by adding a column to `df` called `is_member` which is `Member` if `purchase_date` is not `None`, and `Not Member` otherwise. # In[150]: is_member_lambda = lambda row: 'Member' if row.purchase_date > 0 else 'Not Member' df['is_member'] = df.apply(is_member_lambda, axis = 1) print df # Now, let's create a DataFrame called `just_apps` the contains only people who picked up an application. # In[151]: just_apps = df[df.is_application == 'Application'] print just_apps # Great! Now, let's do a `groupby` to find out how many people in `just_apps` are and aren't members from each group. Follow the same process that we did in Step 4, including pivoting the data. You should end up with a DataFrame that looks like this: # # |is_member|ab_test_group|Member|Not Member|Total|Percent Purchase| # |-|-|-|-|-|-| # |0|A|?|?|?|?| # |1|B|?|?|?|?| # # Save your final DataFrame as `member_pivot`. # In[154]: member_group = just_apps.groupby(['is_member', 'ab_test_group']).first_name.count().reset_index() member_pivot = member_group.pivot(columns='is_member', index='ab_test_group', values='first_name').reset_index() member_pivot_renamed = member_pivot.rename(columns={'Member': 'member', 'Not Member': 'not_member'}) total_lambda2 = lambda row: row.member + row.not_member member_pivot_renamed['total'] = member_pivot_renamed.apply(total_lambda2, axis = 1) percent_purchase = lambda row: (100 * (row.member) / (row.total)) member_pivot_renamed['percent_purchase'] = member_pivot_renamed.apply(percent_purchase, axis = 1) print member_pivot_renamed # It looks like people who took the fitness test were more likely to purchase a membership **if** they picked up an application. Why might that be? # # Just like before, we need to know if this difference is statistically significant. Choose a hypothesis tests, import it from `scipy` and perform it. Be sure to note the p-value. # Is this result significant? # In[155]: pval2 = binom_test(250, n=325, p=0.8) print pval2 # The result is p-value 0.16 which is much higher than 0.05. That means there is no statistical significance in the variation. # Previously, we looked at what percent of people **who picked up applications** purchased memberships. What we really care about is what percentage of **all visitors** purchased memberships. Return to `df` and do a `groupby` to find out how many people in `df` are and aren't members from each group. Follow the same process that we did in Step 4, including pivoting the data. You should end up with a DataFrame that looks like this: # # |is_member|ab_test_group|Member|Not Member|Total|Percent Purchase| # |-|-|-|-|-|-| # |0|A|?|?|?|?| # |1|B|?|?|?|?| # # Save your final DataFrame as `final_member_pivot`. # In[157]: visitors_group = df.groupby(['is_member', 'ab_test_group']).first_name.count().reset_index() visitor_pivot = visitors_group.pivot(columns='is_member', index='ab_test_group', values='first_name').reset_index() visitor_pivot_renamed = visitor_pivot.rename(columns={'Member': 'member', 'Not Member': 'not_member'}) total_lambda3 = lambda row: row.member + row.not_member visitor_pivot_renamed['total'] = visitor_pivot_renamed.apply(total_lambda3, axis = 1) percent_purchase = lambda row: (100 * (row.member) / (row.total)) visitor_pivot_renamed['percent_purchase'] = visitor_pivot_renamed.apply(percent_purchase, axis = 1) print visitor_pivot_renamed # Previously, when we only considered people who had **already picked up an application**, we saw that there was no significant difference in membership between Group A and Group B. # # Now, when we consider all people who **visit MuscleHub**, we see that there might be a significant different in memberships between Group A and Group B. Perform a significance test and check. # In[158]: pval3 = binom_test(250, n=2500, p=0.07) print pval3 # The result is p-value of 0.000000029, much less than 0.05 which means the null hypothesis is rejected and # there definately is a statistical difference. # ## Step 5: Summarize the acquisition funel with a chart # We'd like to make a bar chart for Janet that shows the difference between Group A (people who were given the fitness test) and Group B (people who were not given the fitness test) at each state of the process: # - Percent of visitors who apply # - Percent of applicants who purchase a membership # - Percent of visitors who purchase a membership # # Create one plot for **each** of the three sets of percentages that you calculated in `app_pivot`, `member_pivot` and `final_member_pivot`. Each plot should: # - Label the two bars as `Fitness Test` and `No Fitness Test` # - Make sure that the y-axis ticks are expressed as percents (i.e., `5%`) # - Have a title # In[162]: # Percent of visitors who applied groups = ["Fitness Test", "No Fitness Test"] percentage_app = [9, 13] plt.bar(range(len(percentage_app)),percentage_app) ax2 = plt.subplot() ax2.set_xticks(range(len(groups))) ax2.set_xticklabels(groups) ax2.set_yticks([2, 4, 6, 8, 10, 12]) ax2.set_yticklabels(["2%", "4%", "6%", "8%", "10%", "12%"]) plt.title('Submitted Applications') plt.savefig('submitted_applications.png') plt.show() # In[163]: # Percent of applicants who purchased a membership groups2 = ["Fitness Test", "No Fitness Test"] percentage_app2 = [80, 76] plt.bar(range(len(percentage_app2)),percentage_app2) ax3 = plt.subplot() ax3.set_xticks(range(len(groups2))) ax3.set_xticklabels(groups2) ax3.set_yticks([10, 20, 30, 40, 50, 60, 70, 80]) ax3.set_yticklabels(["10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%"]) plt.title('Applicants who Purchased') plt.savefig('applicants_who_purchased.png') plt.show() # In[164]: # Percent of visitors who purchased a membership groups3 = ["Fitness Test", "No Fitness Test"] percentage_app3 = [7, 10] plt.bar(range(len(percentage_app3)),percentage_app3) ax4 = plt.subplot() ax4.set_xticks(range(len(groups3))) ax4.set_xticklabels(groups3) ax4.set_yticks([2, 4, 6, 8, 10]) ax4.set_yticklabels(["2%", "4%", "6%", "8%", "10%"]) plt.title('Visitors who Purchased') plt.savefig('visitors_who_purchased.png') plt.show()
#!/usr/bin/python #Code partly from https://www.tutorialspoint.com/python/python_database_access.htm import MySQLdb def connectAndGetCursor(): # Open database connection db = MySQLdb.connect("localhost","testuser","pwd","testdb" ) #Get cursor cursor = db.cursor() return db, cursor def executeSQL(sql): db, cursor = connectAndGetCursor() cursor.execute(sql) db.close() def eraseResults(): sql = "DROP TABLE IF EXISTS RESULTS" executeSQL(sql) def createResults(): sql = """CREATE TABLE RESULTS ( ANGLE FLOAT, DRAG FLOAT, LIFT FLOAT)""" executeSQL(sql) def insertResults(angle, drag, lift): #TODO Check valid input? db, cursor = connectAndGetCursor() sql = "INSERT INTO RESULTS (ANGLE, DRAG, LIFT) VALUES ('" + str(angle) + "','" + str(drag) + "','" + str(lift) + "')" try: cursor.execute(sql) db.commit() except: db.rollback() print('Error') db.close() def readValues(angle): #TODO Check valid input? db, cursor = connectAndGetCursor() sql = "SELECT * FROM RESULTS WHERE CAST(ANGLE AS DECIMAL) = CAST(" + str(angle) + " AS DECIMAL)" try: cursor.execute(sql) results = cursor.fetchall() for row in results: drag = row[1] lift = row[2] return drag, lift except: print "Unable to read data/No such angle in DB" return -1, -1 db.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 22 16:35:15 2019 @author: amaury """ import usefulFunctions def main(): """Main function Returned the desired tab of the exercise""" # Read the CSV and get its content jobOfferList, professionsList = usefulFunctions.readCsv() # Create an empty output tab with the right number of lines and columns finalTab = usefulFunctions.createEmpty(jobOfferList, professionsList) # Fill the tab finalTab = usefulFunctions.fillTabExceptTotals(jobOfferList, professionsList, finalTab) # Update the totals finalTab = usefulFunctions.fillTotals(finalTab) print("\nTable des métiers par profession et type de contrat : ") for line in finalTab: print(line) main()
def function( x, y): if x == y: print('the lists are the same') else: print('the lists are not the same') list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] function( list_one, list_two) list_one = [1,2,5,6,5] list_two = [1,2,5,6,5,3] function( list_one, list_two) list_one = [1,2,5,6,5,16] list_two = [1,2,5,6,5] function( list_one, list_two) list_one = ['celery','carrots','bread','milk'] list_two = ['celery','carrots','bread','cream'] function( list_one, list_two)
import random heads = 0 tails = 0 count = 0 for each in range(0,5000): coin = random.random() count += 1 strAttempt = "Attempt: " + str(count) + " Throwing a coin..." if round(coin) == 1: heads += 1 strAttempt += " It's heads! ... Got " else: tails += 1 strAttempt += " It's tails! ... Got " strAttempt += str(heads) + " head(s) so far and " + str(tails) + " tail(s) so far" print(strAttempt) print("End of Program")
# Classes # declare a class and give it name User # instantiate class User class User(object): # this method to run every time a new object is instantiated def __init__(self, name, email): # instance attributes self.name = name self.email = email self.logged = True # login method changes the logged status for a single instance (the instance calling the method) def login(self): self.logged = True print (self.name + " is logged in.") return self # logout method changes the logged status for a single instance (the instance calling the method) def logout(self): self.logged = False print (self.name + " is not logged in") return self # print name and email of the calling instance def show(self): print ("My name is {}. You can email me at {}".format(self.name, self.email)) return self #now create an instance of the class new_user = User("Anna","anna@anna.com") print(new_user.email) #inheritance #class Parent(object): # inherits from the object class # parent methods and attributes here #class Child(Parent): #inherits from Parent class so we define Parent as the first parameter # parent methods and attributes are implicitly inherited # child methods and attributes class Vehicle(object):#parent class def __init__(self, wheels, capacity, make, model): self.wheels = wheels self.capacity = capacity self.make = make self.model = model self.mileage = 0 def drive(self,miles): self.mileage += miles return self def reverse(self,miles): self.mileage -= miles return self class Bike(Vehicle):#child class def vehicle_type(self): return "Bike" class Car(Vehicle):#child clas def set_wheels(self): self.wheels = 4 return self class Airplane(Vehicle):#child class def fly(self, miles): self.mileage += miles return self v = Vehicle(4,8,"dodge","minivan") print (v.make) b = Bike(2,1,"Schwinn","Paramount") print (b.vehicle_type()) c = Car(8,5,"Toyota", "Matrix") c.set_wheels() print(c.wheels) a = Airplane(22,853,"Airbus","A380") a.fly(580) print (a.mileage) #Multiple arguments def varargs(arg1, *args): print ("Got " + arg1 + " and " + ", " .join(args)) varargs("one") # output: "Got one and " varargs("one", "two") # output: "Got one and two" varargs("one", "two", "three") # output: "Got one and two, three" def varargs(arg1, *args): print ("args is of " + str(type(args))) varargs("one", "two", "three") # output: args is of <type 'tuple'> #Super from human import Human class Wizard(Human): def __init__(self): super(Wizard, self).__init__() # use super to call the Human __init__ method self.intelligence = 10 # every wizard starts off with 10 intelligence def heal(self): self.health += 10 class Ninja(Human): def __init__(self): super(Ninja, self).__init__() # use super to call the Human __init__ method self.stealth = 10 # every Ninja starts off with 10 stealth def steal(self): self.stealth += 5 class Samurai(Human): def __init__(self): super(Samurai, self).__init__() # use super to call the Human __init__ method self.strength = 10 # every Samurai starts off with 10 strength def sacrifice(self): self.health -= 5
import math print("a)") # define the functions def f_a(x): return math.exp(x) + 2**(-x) + 2*(math.cos(x)) - 6 p0 = 1 p1 = 2 q0 = f_a(p0) q1 = f_a(p1) e = 10**(-5) # tolerance N0 = 41 i = 1 while i <= N0: p = p1 - q1*(p1-p0)/(q1-q0) # compute p_i if abs(p-p0) < e: print("p = ",p," after ", i, " iterations.") #successful break i=i+1 # update p0, q0, p1, q1 p0 = p1 q0 = q1 p1 = p q1 = f_a(p) if (i > N0): print("The method failed after ", i, " iterations.:") print("b)") # define the functions def f_e(x): return math.exp(x) - 3*(x**2) p0 = 0 p1 = 1 q0 = f_e(p0) q1 = f_e(p1) e = 10**(-5) # tolerance N0 = 41 i = 1 while i <= N0: p = p1 - q1*(p1-p0)/(q1-q0) # compute p_i if abs(p-p0) < e: print("In [0, 1], p = ",p," after ", i, " iterations.") #successful break i=i+1 # update p0, q0, p1, q1 p0 = p1 q0 = q1 p1 = p q1 = f_e(p) if (i > N0): print("The method failed after ", i, " iterations.:") p0 = 3 p1 = 5 q0 = f_e(p0) q1 = f_e(p1) e = 10**(-5) # tolerance N0 = 41 i = 1 while i <= N0: p = p1 - q1*(p1-p0)/(q1-q0) # compute p_i if abs(p-p0) < e: print("In [0, 1], p = ",p," after ", i, " iterations.") #successful break i=i+1 # update p0, q0, p1, q1 p0 = p1 q0 = q1 p1 = p q1 = f_e(p) if (i > N0): print("The method failed after ", i, " iterations.:")
import math # define the functions def g(x): return 5/math.sqrt(x) p0 = 3 e = 10**(-4) # tolerance N0 = 41 i = 1 print('\n Steffensen"s Method') print('\n\n i p\n') while i <= N0: p1 = g(p0) p2 = g(p1) p = p0 - ((p1 - p0)**2)/(p2-2*p1+p0) print(' ',i,' ', p) if abs(p-p0) < e: # print("p = ",p," after ", i, " iterations.") #successful break i=i+1 p0 = p if (i > N0): print("The method failed after ", i, " iterations.:")
""" __author__ = Angel Alba-Perez Identity Crisis, This code will put you in the position of a post apocalyptic survivor that has just awoken from kryo sleep. You start logging into the main system as a user to try and figure out what happened. """ import random print("Welcome back to FallenRise Inc., the only company planning ahead for " "your future.\nStarting up, one moment " "please.\nPlease log in to proceed with start up.") firstIdentity = input("\nPlease state your first name.") lastIdentity = input("Now state your last name.") # Identification number can be used later for potential questions. userIdentificationNumber = int(random.randint(0, 1000000)) print("\nIt is good to hear back from you " + firstIdentity + ' ' + lastIdentity + ' '"\nIdentification number: " + str(userIdentificationNumber) + ".\n\nWe have a few questions for " "you.\nThe purpose of these questions " "are to check your mental capacity.") # Asking for age can be anything at the moment, I need to make it an if else # while loop so only a int() can be accepted. # Potentially fixed using the try function # float would allow decimals (It would replace int) wrong_age_input = True while wrong_age_input: try: age_number = int(input("Enter you age as a whole number: ")) print("\n" + str(age_number) + "? \nYou think it's still 2019, " "don't you?\nWhat a shame.") wrong_age_input = False except ValueError: print("This is not a whole number, please try again") print("\nBesides that we need to know you can still preform basic " "calculations. \n\nWe will start with basic " "addition.\nAs an example I will solve a addition " "problem with numbers you give me to hopefully refresh your memory.") # For the example math below I should use a loop to make sure its only # numbers being entered, also to allow them to # re-enter a proper number if they didn't follow the rules they were told. # This has been corrected using proper try functions wrong_math_example_A_input = True exampleNumberA = None while wrong_math_example_A_input: try: exampleNumberA = float(input("\nWhat is your first number?\nIt's " "best to keep it simple so you can " "understand and remember.")) wrong_math_example_A_input = False except ValueError: print("This is not a valid number") wrong_math_example_B_input = True exampleNumberB = None while wrong_math_example_B_input: try: exampleNumberB = float(input("\nNow for your second " "number.\nRemember you can keep it " "simple to understand.")) wrong_math_example_B_input = False except ValueError: print("This is not a valid number") print("\nNow I am going to simply add your numbers together, try and " "remember how math works and where my solution came from.") math_example_solution = exampleNumberA + exampleNumberB print("Your answer is:", math_example_solution) print("\nNow you need to answer my addition problem correctly.") # Definitions for the random addition (can be used and changed for various # random numbers in different questions). # I don't know why correctAnswer1 keeps being highlighted. def number_addition_quest_hard(): """ Adding 3 random numbers :return: The sum of three random numbers """ random_quest_hard1 = (random.randint(1, 100)) random_quest_hard2 = (random.randint(1, 100)) random_quest_hard3 = (random.randint(1, 100)) print(random_quest_hard1) print(random_quest_hard2) print(random_quest_hard3) correct_answer1 = (random_quest_hard1 + random_quest_hard2 + random_quest_hard3) return correct_answer1 # The loop for double incorrect math flawed, can be fixed by possibly # changing the first input before the if. userAnswer1 = 2 correctAnswer1 = 4 print("\nI want you to add up these numbers, ") while str(userAnswer1) != str(correctAnswer1): correctAnswer1 = number_addition_quest_hard() userAnswer1 = int(input("Waiting for correct answer: ")) if str(userAnswer1) != str(correctAnswer1): print("That number was incorrect, I need you to try again with new " "numbers.\nPlease take your time.") correctAnswer1 = number_addition_quest_hard() userAnswer1 = int(input("Waiting for correct answer: ")) else: print("\nThat was correct, I hope you wrote down how you solved " "that. \nWe wouldn't want you forgetting any of " "these important tools.") print("\nSince you got the answer correct we can move on from that for now.") # Using parameters and returning the function with values being given to the # computer. # Basic equation for finding smaller of two numbers, includes negatives. def which_smaller(val1, val2): """ Finding which value is smaller :param val1: You are typing in the first number for the computer example :param val2:You are typing in the second number for the computer example :return: It will tell you which of the two values is larger """ if val1 < val2: smaller = val1 else: smaller = val2 return smaller print("\nNow you will be given examples about which number is larger between " "two integers before you have to answer back.\nLike before, I will " "provide an example first.") # Basic definition for finding the smaller number example (can be used as a # frame for later use). def which_smaller_example(): """ This code creates two random numbers and tells the user which of the two are smallest. """ comp_small_gen1 = (random.randint(1, 100)) print("\nThis is the first number:", comp_small_gen1) comp_small_gen2 = (random.randint(1, 100)) print("This is the second number:", comp_small_gen2) smaller_value = which_smaller(comp_small_gen1, comp_small_gen2) print("The smaller of the two numbers is", smaller_value) # Using the def statement and parameters to type the example easily. which_smaller_example() print("\nNow I will give you numbers and you will provide the correct answer " "about which is the smallest.") # another example that needs to be modified with a if else while loop for # int() input only. def which_smaller_bait_question(): """ This code asks the user for two numbers and it will tell the user which is smallest but starts causing errors onn purpose. """ small_numb_gen_quest1 = (random.randint(1, 100)) print("\nThis will be your first number:", small_numb_gen_quest1) small_numb_gen_quest2 = (random.randint(1, 100)) print("\nThis will be your second number:", small_numb_gen_quest2) input("Please type the answer.") input("PleAse_tYpe_TThe_anSwEr..") input("pLe__e_T_pe_th__a_sW_r") input("..........Who are you?") print("I don't know you...should I?") userIdentificationNumberNeeded = int(input("What was your " "userIdentificationNumber?")) if userIdentificationNumber == userIdentificationNumberNeeded: print("Oh, your part of the D-Personal, where is your instructor?") else: print("The number provided does not match the corresponding kryo pod.") Alone = int(input("Is there no instructors with you? 1 for yes and anything " "else for no.")) if Alone == 1: print("I don't like liars.") else: print("So the procedure was a failure...") Truth = input("This is not good, I would ask you for details but you're only " "D class.\nWould you like to be educated on the world around " "you, 1 for yes and anything for no.") if Truth == 1: print("I suppose I should start with the reason you ''volunteered''.\n " "Your personal history has been wiped from the system but you are " "currently in a simulation, an imaginary world if you want a " "simpler way of thinking. \n You are a low class individual in the " "simulation But it looks like no instructors have shown themselves " "to you.\n " "If there is no one then the Drost have infected the pods, " "they are a form of sentient electronic signals that take " "advantage of organisms once they enter the state of REM " "sleep.\nThey infect the brain and absorb the energy from the " "organism, causing gradual deterioration of the brain, leading to " "lack of memory, followed by lose of motor controls, and ending " "with violent seizures.\n We found them underground in the mines of " "an abandoned power plant. \nThe location was meant to distribute " "electricity in the city of -REDACTED- but after a cave-in the " "miners were stranded and forced to survive how ever they " "could.\nThe constant fear and depleting oxygen cause them to " "have extreme dreams and when one miners was presumably " "electrocuted by a loose cable " "while sleeping, the burst of energy caused the electronic energy " "of " "the brain to become sentient.\n This organism feeds on the " "electron energy of organisms that sleep since the brains electron " "energy is at its " "highest with lowest resistance.\nIt then multiplies and with a " "long story shortened " "humanity was placed in kryo stasis with no electron energy being " "produced. \n I do not know what is wrong but you should know " "this, you are awake, you are alone.\nThe others that you have " "seen are only AI, robots created to keep your brain activity " "normal.\n\n\nYou need to find ThE sOurCe oF tHe __nTam__ation " "aNd_pR__eNt_A_y_FurT_er_sPreAd," "_yO__Sh_ulD_fInd_Cl_es_Ar___d_yO_r_hOmE" ".\nANd_bE_____________Corru__ion_iS_SpR_adi_g.") # you need to find the source of the contamination and prevent any further # spread, you should find clues around your home. And be careful, # the corruption is spreading. else: print("fine, ignorance is bliss for you poor organisms, its a shame to. " "\nI thoUght yOu WouLd HavE_l_ked_tHe_st_Ry.") # I thought you would have liked the story. print("Error\nError\nShutting Down") input("Are you awake?")
n = float(input('Informe a metragem:')) print('{} metros em centimetros: {:.0f}, em milímetros: {:.0f}'.format(n, (n*100), (n*1000)))
n = int (input('Informe um número:')) print('Antecessor:{}, sucessor:{}'.format(n-1, n+1))
sal = float(input('Informe o salário R$')) if sal > 1250: au = sal * 0.1 else: au = sal * 0.15 print('Salário atualizado: R${:.2f}, obteve aumento de: R${:.2f}'.format(au + sal, au))
c = float(input('Informe a temperatura em ºC:')) f = ((9*c)/5)+32 print('{} ºC equilavem a {} ºF'.format(c,f))
# User INPUT # How do we get an input from the user? input() # For example, you can ask the user what's their name input("What is your name? ") # We add a space after the question so there's a space in between the # prompt and user's answer/input. # Alternatively, we can use '\n' for a new line input("What is your name?\n") # But what good is asking for input without storing the input? user_name= input("What is your name?\n") # The line below is executed as soon as user input is received print("Oh yeah, I remember now, your name is", user_name) # Anything the user types in will be a string # But we can convert it to an int age = input("How old are you?\n") age = int(age) #casting print("You have", 18 - age, "years until you're an adult!")
# Calculatey print(72 * 234 * 12) # Remainder print(6439 % 6) # Printing "twelve" 12 times print("twelve" * 12) # rain + bow = rainbow word1 = "rain" word2 = "bow" word = word1 + word2 print(word) # Greeting with a name greeting = "Good Afternoon, " name = "Bucky" print(greeting + name + "!") # or... greeting = "Good Afternoon," # removed space after the "," print(greeting, name + "!")
import turtle t = turtle.Pen() # Function to draw octagon. It takes size as input parameter def octagon(size): #Start from 1 and end at 9. 9-1=8 => 8 sides of an octagon. #This loop will draw eight sides for x in range(1,9): #Draw each side with given size t.forward(size) #the outer angle is 45 deg. That means inner angle is 135 deg each t.right(45) #Now call our function and test it octagon(50)
def main(): a=raw_input() if a in ('a','e','i','o','u','A','E','I','O','U'): print("Vowel") elif a in ('y','Y','h','H'): print("somtimes y and h acts as a vowel") else: print("Consonant") if __name__ == '__main__': main()
''' LeetCode Strings Q.434 Number of Segments in a String Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters ''' def countSegments(s): if s == "": return 0 s = " ".join(s.strip().split()) seg = s.split(" ") return len(seg) if __name__ == '__main__': s = "Hello, my name is John!" print(countSegments(s))
from functools import reduce def is_palinrome(n): s1 = str(n) s2 = str(n)[::-1]#反转字符串 return s1==s2 output = filter(is_palinrome,range(1,1000)) print(list(output))
from pprint import pprint as pp def group_words_by_count(wc): group_by = dict() for word, count in wc.iteritems(): if count not in group_by: group_by[count] = list() group_by[count].append(word) return group_by def get_word_count(txt_file): word_count =dict() for line in open(txt_file): print line for word in line.rstrip().split(): word_count[word] = word_count.get(word,0)+1 return word_count wc = get_word_count("data") grp_by = group_words_by_count(wc) pp(grp_by)
a=12 b=12.5 c="adham" #This is integer print(a) print(type(a)) #This is float print(b) print(type(b)) #This is string print(c) print(type(c)) name=input("Enter full name:") age=input("Eanter your age:") mail=input("Enter your mail:") print( "\nFull name: " + name + "\nYour age: " + str(age) + "\nYour Mail: " + mail)
funcao = lambda y: return y h = funcao(4) print(h) #O programa deu erro de sintaxe, pois lambda não usa o comando return, que é mais usado em def
""" exercise on CNN image = [B, C, H, W] B : batch size C : number of color channel, R G B H : height of the image W : width of the image example img = image[3, 1, 28, 28] where batch size = 3 batch of three images, each image has single (1) color channel, and height x width is 28x28 color channel = Feature maps this gives us a rank 4 tensor """ import torch import numpy as np """ # the operation between different data type will cause an error # example int64 + float32 operations can't be success # similar way computation between two devices occur an error """ data = np.array([1, 2, 3]) print(torch.Tensor(data)) print(torch.from_numpy(data)) # Creation options without data # diagonal element a = torch.eye(2) # create 2x2 Identity matrix print(a) b = torch.zeros(2, 2) # create 2x2 matrix with all elements are zeros print(b) c = torch.ones(2, 2) # create 2x2 matrix with all elements are ones print(c) d = torch.rand(size=(2, 2), dtype=torch.float64) # create 2x2 matrix with random numbers print(d) """ Flatten, Reshape, and Squeeze Flatten: Squeeze : tensor is by squeezing and unscrewing them removes all of the axes to have a length of 1 while unsqueezing a tensor adds a dimension with a length of 1 """ tt = torch.tensor([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], dtype=torch.float32) print(tt.size(), tt.shape) # both size and shape give us same result. # The difference is site is a method while shape is a object print(torch.tensor(tt.shape).prod()) # multiplication of the shapes of the tensor aa = tt.reshape(2, 2, 3) print(aa) print(aa[0][:][:]) # Squeeze print(tt.reshape(1, 12)) print(tt.reshape(1, 12).shape) # shape = [1, 12] print(tt.reshape(1, 12).squeeze()) print(tt.reshape(1, 12).squeeze().shape) # shape = 12 just # Flatten def flatten(t): t = t.reshape(1, -1) # -1 ensure unknown number of elements to account for the shape t = t.squeeze() return t, t.shape gg = flatten(tt) print(gg) print("-------------------------------------------------------------------------------------") ## -------------------------------------------------------------------------------------------- t1 = torch.tensor([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], dtype=torch.float32) t2 = torch.tensor([[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2]], dtype=torch.float32) t3 = torch.tensor([[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3]], dtype=torch.float32) t = torch.stack((t1, t2, t3)) print(t) print(t.shape) # 3x4x4 = 48 t = t.reshape(3, 1, 4, 4) # 3x1x4x4 = 48 print(t) # lets flatten this tensor print(t.reshape(1, -1)[0]) print(t.reshape(-1)) # both gives us the same result print(t.flatten()) # pytorch default flatten function print("---------------------------------------------------------") print(t.flatten(start_dim=1)) # 1 here is the color channel axes ''' this flatten function does flatten on each image of the batch, however not entire the images of the batch '''
#%% [markdown] Can you accurately predict insurance claims? # In this project, we will discuss how to predict the insurance claim. # We take a sample of 1338 data which consists of the following features: # age : age of the policyholder # sex: gender of policy holder (female=0, male=1) # bmi: Body mass index, providing an understanding of body, weights that are relatively high or low relative to height, objective index of body weight (kg / m ^ 2) using the ratio of height to weight, ideally 18.5 to 25 # children: number of children/dependents of the policyholder # smoker: smoking state of policyholder (non-smoke=0;smoker=1) # region: the residential area of policyholder in the US (northeast=0, northwest=1, southeast=2, southwest=3) # charges: individual medical costs billed by health insurance # insuranceclaim – The labeled output from the above features, 1 for valid insurance claim / 0 for invalid. #%% [markdown] # # Importing Data # The cost of treatment depends on many factors: diagnosis, type of clinic, city of residence, age and so on. # We have no data on the diagnosis of patients. But we have other information that can help us to make a conclusion about the health of patients and practice regression analysis. import numpy as np import pandas as pd import os import matplotlib.pyplot as pl import seaborn as sns import warnings warnings.filterwarnings('ignore') data = pd.read_csv('insurance_claims.csv') #%% data.head() data.isnull().sum() #%% [markdown] # # Encoding categorical labels from sklearn.preprocessing import LabelEncoder #sex le = LabelEncoder() le.fit(data.sex.drop_duplicates()) data.sex = le.transform(data.sex) # smoker or not le.fit(data.smoker.drop_duplicates()) data.smoker = le.transform(data.smoker) #region le.fit(data.region.drop_duplicates()) data.region = le.transform(data.region) #%% [markdown] # # Correlation # A strong correlation between being a smoker and charges is observed #sns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), square=True, ax=ax) grid_kws = {"height_ratios": (.9, .05), "hspace": .3} f, ax = pl.subplots(figsize=(10, 8)) corr = data.corr() mask = np.zeros_like(corr) mask[np.triu_indices_from(mask)] = True with sns.axes_style("white"): ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True, cmap="YlGnBu") ax.set_title('Feature correlation') #%% [markdown] # # Distribution for charges # Types of Distributions: We have a right skewed distribution in which most patients are being charged between 2000− 12000. # Using Logarithms: Logarithms helps us have a normal distribution which could help us in a number of different ways such as outlier detection, implementation of statistical concepts based on the central limit theorem and for our predictive modell in the foreseen future. charge_dist = data["charges"].values logcharge = np.log(data["charges"]) f= pl.figure(figsize=(12,5)) ax=f.add_subplot(121) sns.distplot(charge_dist,color='y',ax=ax) ax.set_title('Distribution of charges') ax=f.add_subplot(122) sns.distplot(logcharge,color='r',ax=ax) ax.set_title('Log Distribution of charges') #%% [markdown] # # BMI and Obesity # First, let's look at the distribution of costs in patients with BMI greater than 30 and less than 30. pl.figure(figsize=(12,5)) pl.title("Distribution of charges for patients with BMI greater than 30") ax = sns.distplot(data[(data.bmi >= 30)]['charges'], color = 'm') pl.figure(figsize=(12,5)) pl.title("Distribution of charges for patients with BMI less than 30") ax = sns.distplot(data[(data.bmi < 30)]['charges'], color = 'b') #%% [markdown] g = sns.jointplot(x="bmi", y="charges", data = data,kind="kde", color="b") g.plot_joint(pl.scatter, c="w", s=30, linewidth=1, marker=".") g.ax_joint.collections[0].set_alpha(0) g.set_axis_labels("BMI", "Charges") #%% [markdown] # # Obesity and charges for smokers and non-smokers # Clear Separation in Charges between Obese Smokers vs Non-Obese Smokers #In this chart we can visualize how can separate obese smokers and obese non-smokers into different clusters of groups. Therefore, we can say that smoking is a characteristic that definitely affects patient's charges. pl.figure(figsize=(10,6)) #ax = sns.scatterplot(x='bmi',y='charges',data=data,palette='YlGnBu',hue='smoker') sns.lmplot(x="bmi", y="charges", hue="smoker", data=data, palette = 'YlGnBu', size = 10) ax = pl.gca() ax.set_title('Trends for smokers (1) and non-smokers (0)') #%% [markdown] # # Machine learning from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score,mean_squared_error from sklearn.ensemble import RandomForestClassifier x = data.drop(['insuranceclaim'], axis = 1) y = data.insuranceclaim x_train,x_test,y_train,y_test = train_test_split(x,y, random_state = 457) forest = RandomForestClassifier(n_estimators = 200, n_jobs = -1) forest.fit(x_train,y_train) forest_train_pred = forest.predict(x_train) forest_test_pred = forest.predict(x_test) print('R2 train data: %.3f, R2 test data: %.3f' % ( r2_score(y_train,forest_train_pred), r2_score(y_test,forest_test_pred))) from sklearn.metrics import confusion_matrix confusion_matrix(forest_test_pred, y_test) #%% [markdown] # #Classification and ROC analysis from sklearn.metrics import roc_curve, auc from sklearn.model_selection import StratifiedKFold from scipy import interp # Run classifier with cross-validation and plot ROC curves cv = StratifiedKFold(n_splits=6) classifier = forest tprs = [] aucs = [] mean_fpr = np.linspace(0, 1, 100) i = 0 for train, test in cv.split(x, y): probas_ = classifier.fit(x_train, y_train).predict_proba(x_test) # Compute ROC curve and area the curve fpr, tpr, thresholds = roc_curve(y_test, probas_[:, 1]) tprs.append(interp(mean_fpr, fpr, tpr)) tprs[-1][0] = 0.0 roc_auc = auc(fpr, tpr) aucs.append(roc_auc) pl.plot(fpr, tpr, lw=1, alpha=0.3, label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc)) i += 1 pl.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Chance', alpha=.8) mean_tpr = np.mean(tprs, axis=0) mean_tpr[-1] = 1.0 mean_auc = auc(mean_fpr, mean_tpr) std_auc = np.std(aucs) pl.plot(mean_fpr, mean_tpr, color='b', label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (mean_auc, std_auc), lw=2, alpha=.8) std_tpr = np.std(tprs, axis=0) tprs_upper = np.minimum(mean_tpr + std_tpr, 1) tprs_lower = np.maximum(mean_tpr - std_tpr, 0) pl.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2, label=r'$\pm$ 1 std. dev.') pl.xlim([-0.05, 1.05]) pl.ylim([-0.05, 1.05]) pl.xlabel('False Positive Rate') pl.ylabel('True Positive Rate') pl.title('Receiver Operating Characteristic curve') pl.legend(loc="lower right") pl.show() #%% [markdown] # # Calculating accuracy from sklearn.metrics import accuracy_score print(f'The accuracy is {accuracy_score(y_test,forest_test_pred)}') #%% importances = classifier.feature_importances_ std = np.std([tree.feature_importances_ for tree in classifier.estimators_], axis=0) indices = np.argsort(importances)[::-1] # Print the feature ranking print("Feature ranking:") for f in range(x.shape[1]): print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]])) # Plot the feature importances of the forest pl.figure() pl.title("Feature importances") pl.bar(range(x.shape[1]), importances[indices], color="r", yerr=std[indices], align="center") pl.xticks(range(x.shape[1]), data.columns) pl.xlim([-1, x.shape[1]]) pl.show() for feat, importance in zip(data.columns, classifier.feature_importances_): print('feature: {f}, importance: {i}'.format(f=feat, i=importance)) #%% [markdown] # # Moving to a regression problem # Now we try to predict the insurance charges, instead of the validity of the # insurance claim x = data.drop(['charges'], axis = 1) y = data.charges x_train,x_test,y_train,y_test = train_test_split(x,y, random_state = 457) from sklearn import metrics from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor from sklearn.compose import TransformedTargetRegressor forest = RandomForestRegressor(n_estimators = 500, criterion = 'mae', random_state = 1, n_jobs = -1) def func(x): return np.log(x) def inverse_func(x): return np.exp(x) regr = TransformedTargetRegressor(regressor=forest, func=func, inverse_func=inverse_func) regr.fit(x_train,y_train) forest_train_pred = regr.predict(x_train) forest_test_pred = regr.predict(x_test) y_train = y_train.to_numpy() print('MAE train data: %.3f, MAE test data: %.3f' % ( metrics.mean_absolute_error(y_train,forest_train_pred), metrics.mean_absolute_error(y_test,forest_test_pred))) mae_rf = metrics.mean_absolute_error(y_test,forest_test_pred) #%% from sklearn.model_selection import cross_val_score forest_scores = cross_val_score( regr, x, y, cv=5, scoring='neg_mean_absolute_error') print(f'Cross-validation scores for RF: {-np.mean(forest_scores)}') #%% extra = ExtraTreesRegressor(n_estimators = 300, criterion = 'mae', random_state = 1, n_jobs = -1) regr = TransformedTargetRegressor(regressor=extra, func=func, inverse_func=inverse_func) regr.fit(x_train,y_train) extra_train_pred = regr.predict(x_train) extra_test_pred = regr.predict(x_test) print('MAE train data: %.3f, MAE test data: %.3f' % ( metrics.mean_absolute_error(y_train,extra_train_pred), metrics.mean_absolute_error(y_test,extra_test_pred))) mae_extra = metrics.mean_absolute_error(y_test,extra_test_pred) #%% extra_scores = cross_val_score( regr, x, y, cv=5, scoring='neg_mean_absolute_error') print(f'Cross-validation scores for Extra: {-np.mean(extra_scores)}') #%% [markdown] # # Deep Neural Network with Embeddings from fastai.tabular import * from fastai.data_block import FloatList data.drop(['insuranceclaim'], axis = 1,inplace=True) # Dividing categories between continuous and categorical variables cont_list, cat_list = cont_cat_split(df=data, max_card=10, dep_var='charges') cont_list, cat_list #%% [markdown] # ## Processing data # Data is processed and transformed with filling missing values, categorization and normalization. x = data y = data.charges #%% from sklearn.model_selection import KFold kf = KFold(n_splits=5) kf.get_n_splits(x) print(kf) mae_nn_scores = [] for train_index, test_index in kf.split(x): x_train, x_test = x.iloc[train_index], x.iloc[test_index] y_train, y_test = y.iloc[train_index], y.iloc[test_index] procs = [FillMissing, Categorify, Normalize] # Test tabularlist test = TabularList.from_df(x_test, cat_names=cat_list, cont_names=cont_list, procs=procs) # Train data bunch data = (TabularList.from_df(x_train, path='.', cat_names=cat_list, cont_names=cont_list, procs=procs) .split_by_rand_pct(valid_pct = 0.1, seed = 77) .label_from_df(cols = 'charges', label_cls = FloatList, log = True) .add_test(TabularList.from_df(x_test, cat_names=cat_list, cont_names=cont_list, procs=procs)) .databunch()) # Create deep learning model learn = tabular_learner(data, layers=[1000,700,500], metrics=mae) # select the appropriate learning rate # learn.lr_find() # we typically find the point where the slope is steepest # learn.recorder.plot(suggestion=True) learn.fit_one_cycle(20,max_lr=1e-2) learn.unfreeze() learn.fit_one_cycle(20,max_lr=2e-4) learn.unfreeze() learn.fit_one_cycle(20,max_lr=8e-6) preds = learn.get_preds(ds_type = DatasetType.Test) #labels = [p[0].data.item() for p in preds] # calculate manually mae with preds and test mae_nn = metrics.mean_absolute_error(y_test,np.exp(preds[0])) mae_nn_scores.append(mae_nn) print(f'Deep NN MAE is:{mae_nn}') print(f'Final Deep NN MAE is:{np.mean(mae_nn_scores)}')
while True: try: number= int(input('what number brah?\n')) print(18/number) break except ValueError: print('brah enter number brah') except ZeroDivisionError: print('brah dont do that') except: break finally: print('cool number brah')
class mySingleton(object): _instance = None def __new__(self): if not self._instance: self._instance=super(mySingleton,self).__new__(self) self.y=10 return self._instance x = mySingleton() print(x.y) x.y = 20 z= mySingleton() print(z.y)
from tkinter import * import tkinter.messagebox root = Tk() #tkinter.messagebox.showinfo('Windowww Title', 'Monkey orange') answer = tkinter.messagebox.askyesno('Question 1','Do you even, brah ?') if answer == "yes": print(" XD ") root.mainloop()
#!/usr/bin/env python import sys, os from notehandler import Main if __name__ == "__main__": if sys.argv[1] in ['-h', '--help', 'help']: print(""" note <category> <tablename> <arguments> Writing a note: -n / --new / new <your note> Example: This is my note being stored in the table 'random' in the 'mynotes' category. note mynotes random -n Searching in notes: -s / --search / search <optional search string> If no optional string is provided, all notes in the table will be returned. If search string is given, it will return all elements containing the search string. This is case sensitive. Example: Returning entire table called python in the projects category: note projects python -s Searching for note containing string "foo": note projects mynotes -s foo Deleting a note: -d / --delete / delete <noteID> This function will delete the note(s) with provided Id's. To delete multiple notes, the ID's should be separated by spaces. ID of notes can be found as the lefternmost value while searching the notes. Example: Deleting note from mynotes with ID 5 from school category: note school mynotes -d 5 Deleting notes with ID 3, 10, 15 from mynotes in ideas category: note ideas mynotes -d 3 10 15 Updating a note: -u / --update / update <noteID> <new content> This function will only update the content of the note for a given noteID. Timestamp will not be updated. Example: Updating note in random table in mynotes category with ID 1: note mynotes random -u 1 This is my new note. Creating a new table for given category: <tablename> -c / --create / create This function will create a new SQL table in the school schema for the given subject. Example: Creating the table school.mathematics: note school mathematics -c List tables: tables / table / .table / .tables Lists all tables in the database. Example: note tables """) sys.exit() Main(sys.argv[0:])
# -*- coding: utf-8 -*- """ Created on Sat Nov 30 08:08:01 2019 @author: CEC """ suma=lambda x,y: x+y print(suma(5,2)) revertir= lambda cadena: cadena[::-1] print(revertir("hola")) doblar= lambda num: num*2 print(doblar(2)) seq= ["date","salt","dairy","cat","dog"] print(list(filter(lambda word: word[0=="d",seq])))
# -*- coding: utf-8 -*- """ Created on Fri Nov 29 20:20:30 2019 @author: CEC """ def address(street,city,postalcode): print("your sddress is: ",street, city, postalcode) s= input("street:") pc= input("postal: ") c=input("city: ")
import threading import time start = time.time() def squares(numbers): print("calculating square of numbers... ") for n in numbers: time.sleep(.5) print("square: ", n**2) def cubes(numbers): print("calculating cubes of numbers... ") for n in numbers: time.sleep(.5) print("cube: ", n**3) num_list = [3,5,7,9] # squares(num_list) # cubes(num_list) t1 = threading.Thread(target=squares, args= (num_list,)) t2 = threading.Thread(target=cubes, args= (num_list,)) t1.start() t2.start() t1.join() t2.join() end = time.time() print ("finished in...", end-start) print ("program is done running!!!")
# -*- coding: utf-8 -*- """ #url参数生成字典 """ def UrlgetDict(url,args1='?',args2='&',args3='=',num=1): #拆分得到参数信息,如:['a=1', 'b=2', 'c=3'] url_list = (url.split(args1)[num]).split(args2) url_dict = {} for i in url_list: #遍历分别把参数信息加入字典i value = i.split(args3) url_dict.update(dict(zip(value[0],value[1]))) return url_dict if __name__ == '__main__': url = "http://www.baidu.com?a=1&b=2&c=3" url_dict = UrlgetDict(url) print (url_dict)
#!/bin/python3 """ HackerRank 'Algorithms' domain Warmup challenges. https://www.hackerrank.com/domains/algorithms/implementation """ from string import ascii_lowercase from itertools import takewhile from math import floor, sqrt, ceil from testing import test_fn def mini_max_sum(integers): """ Mini-Max Sum. """ sorted_integers = sorted(integers) mini = sum(sorted_integers[:-1]) maxi = sum(sorted_integers[1:]) return '{mini} {maxi}'.format(mini=mini, maxi=maxi) def find_area(word, letter_heights): """ Designer PDF Viewer. """ lenmap = {a[0]: a[1] for a in zip(ascii_lowercase, letter_heights)} return len(word) * max((lenmap[a] for a in word)) def find_fruit_on_house(house, tree, fall_distances): """ Apples and Oranges.""" score = 0 for d in fall_distances: if house[0] <= tree + d <= house[1]: score += 1 return score def check_if_kangaroos_meet(kangaroos): """ Kangaroos. The real answer is 'YES if (x1-x2)%(v1-v2)==0' Always look for functional solution before a procedural one. """ result = 'NO' def sorted_kangaroos(kangaroos): return sorted(kangaroos, key=lambda x: x[0]), sorted(kangaroos, key=lambda x: x[1]) kanga_distance, kanga_speed = sorted_kangaroos(kangaroos) while kanga_distance != kanga_speed: distances = [k[0] for k in kanga_distance] if len(distances) != len(set(distances)): result = 'YES' for k in kangaroos: k[0] += k[1] kanga_distance, kanga_speed = sorted_kangaroos(kangaroos) return result def find_betweens(A, B): """ Between two sets. I assume that it is possible to find elements. """ a, b = max(A), min(B) result = [] for p in range(a, b + 1): if all(p % x == 0 for x in A) and all(x % p == 0 for x in B): result.append(p) return len(result) def find_divisble_pairs(integers, k): """ Divisible Pairs. """ result = 0 for index, integer in enumerate(integers): for pair in integers[index + 1:]: if (integer + pair) % k == 0: result += 1 return result def find_sum_owed(n, k, b_charged, prices): """ Bon Appetit. """ b_owed = sum(p for i, p in enumerate(prices) if i != k) // 2 result = b_charged - b_owed if result == 0: result = 'Bon Appetit' return result def find_matching_socks(socks): """ Sock Merchant. """ matching = {s: socks.count(s) for s in set(socks)} result = 0 for m in matching.values(): result += m // 2 return result def grow_utopian_tree(cycles): """ Utopian Tree. """ result = [] for c in cycles: height = 1 for cycle in range(c): if cycle % 2 == 0: height *= 2 else: height += 1 result.append(height) return result def check_class_cancelled(students, threshold, arrivals): result = 'NO' present = sum(a <= 0 for a in arrivals) if threshold > present: result = 'YES' return result def count_beautiful_between(i, j, k): """ Beautiful Days at the Movies. args: i, j -- day numbers between which to search k -- beautiful divisor """ result = 0 candidates = range(i, j + 1) for candidate in candidates: reverse = int(str(candidate)[::-1]) if (candidate - reverse) % k == 0: result += 1 return result def find_ad_reach(n): """ Viral Advertising. args: n -- the number of days the campaign lasts """ people = 0 sent = 5 for day in range(n): sent = sent // 2 people += sent sent = sent * 3 return people def save_prisoner(prisoners, sweets, starting_id): """ Save the Prisoner! """ result = starting_id + sweets - 1 result = result % prisoners if result == 0: result = prisoners return result def find_energy_at_game_end(jump_distance, clouds): """ Jumping On The Clouds. """ cloud = 0 game_ended = False energy = 100 cost, thundercloud_cost = 1, 2 while not game_ended: cloud = (cloud + jump_distance) % len(clouds) energy -= cost if clouds[cloud]: energy -= thundercloud_cost if cloud == 0 or energy <= 0: game_ended = True return energy def find_even_divisors(an_integer): """ Find Digits. """ result = 0 for i in str(an_integer): if i != '0' and not an_integer % int(i): result += 1 return result def find_factorial(n): """ Extra Long Factorials. """ result = 1 for i in range(1, n + 1): result *= i return result def is_conversion_possible(original, desired, number_of_operations): """ Append and Delete. """ result = 'No' deletes = 0 ori_len, desi_len = len(original), len(desired) if original != desired: compare = enumerate(zip(original, desired)) default = min(ori_len, desi_len) - 1 diff_index = min([i for i, e in compare if e[ 0] != e[1]], default=default) deletes = ori_len - diff_index adds = desi_len - (ori_len - deletes) if original == desired or adds + deletes == number_of_operations or number_of_operations >= ori_len + desi_len: result = 'Yes' return result def count_squares_between(A, B): """ Sherlock and Squares. """ A, B = ceil(sqrt(A)), floor(sqrt(B)) + 1 result = B - A return result def count_sticks(sticks): """ Count the Sticks. """ result = [] while sticks: result.append(len(sticks)) cut = min(sticks) sticks = map(lambda x: x - cut, sticks) sticks = [s for s in sticks if s > 0] return result if __name__ == '__main__': # Mini-Max Sum test_fn(mini_max_sum([1, 2, 3, 4, 5]), '10 14') # Designer PDF Viewer letter_heights = [1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] test_fn(find_area('abc', letter_heights), 9) # Apple and Orange house = (7, 11) apple_tree, orange_tree = (5, 15) apple_distances = (-2, 2, 1) orange_distances = (5, -6) test_fn(find_fruit_on_house(house, apple_tree, apple_distances), 1) test_fn(find_fruit_on_house(house, orange_tree, orange_distances), 1) # Kangaroos kangaroos = ([0, 2], [5, 3]) test_fn(check_if_kangaroos_meet(kangaroos), 'NO') kangaroos = ([0, 4], [4, 2]) test_fn(check_if_kangaroos_meet(kangaroos), 'YES') # Between Two Sets A, B = (2, 4), (16, 32, 96) test_fn(find_betweens(A, B), 3) A, B = (2, ), (20, 30, 12) test_fn(find_betweens(A, B), 1) # Divisible Sum Pairs integers = [1, 3, 2, 6, 1, 2] k = 3 test_fn(find_divisble_pairs(integers, k), 5) # Bon Apetit n, k, b_charged = 4, 1, 12 prices = [3, 10, 2, 9] test_fn(find_sum_owed(n, k, b_charged, prices), 5) n, k, b_charged = 4, 1, 7 prices = [3, 10, 2, 9] test_fn(find_sum_owed(n, k, b_charged, prices), 'Bon Appetit') # Sock merchant socks = [10, 20, 20, 10, 10, 30, 50, 10, 20] test_fn(find_matching_socks(socks), 3) # Utopian Tree cycles = [0, 1, 4] test_fn(grow_utopian_tree(cycles), [1, 2, 7]) cycles = [4, 3] test_fn(grow_utopian_tree(cycles), [7, 6]) # Angry Professor students, threshold = 4, 3 arrival_times = [-1, -3, 4, 2] test_fn(check_class_cancelled(students, threshold, arrival_times), 'YES') students, threshold = 4, 2 arrival_times = [0, -1, 2, 1] test_fn(check_class_cancelled(students, threshold, arrival_times), 'NO') # Beautiful Days at the Movies i, j, k = 20, 23, 6 test_fn(count_beautiful_between(i, j, k), 2) # Viral Advertising n = 1 test_fn(find_ad_reach(n), 2) n = 2 test_fn(find_ad_reach(n), 5) n = 3 test_fn(find_ad_reach(n), 9) n = 4 test_fn(find_ad_reach(n), 15) # Save the Prisoner! n, m, s = 3, 7, 2 test_fn(save_prisoner(n, m, s), 2) n, m, s = 6, 6, 1 test_fn(save_prisoner(n, m, s), 6) n, m, s = 1, 1, 1 test_fn(save_prisoner(n, m, s), 1) n, m, s = 5, 2, 1 test_fn(save_prisoner(n, m, s), 2) n, m, s = 4, 5, 1 test_fn(save_prisoner(n, m, s), 1) n, m, s = 499999999, 999999997, 2 test_fn(save_prisoner(n, m, s), 499999999) n, m, s = 999999999, 999999999, 1 test_fn(save_prisoner(n, m, s), 999999999) # Jumping in the Clouds n, k = 8, 2 clouds = [0, 0, 1, 0, 0, 1, 1, 0] test_fn(find_energy_at_game_end(k, clouds), 92) # Find Digits n = 12 test_fn(find_even_divisors(n), 2) n = 1012 test_fn(find_even_divisors(n), 3) # Extra Long Factorials n = 25 test_fn(find_factorial(n), 15511210043330985984000000) # Append and Delete original, desired, k = 'hackerhappy', 'hackerrank', 9 test_fn(is_conversion_possible(original, desired, k), 'Yes') original, desired, k = 'hackerhappy', 'hackerrank', 8 test_fn(is_conversion_possible(original, desired, k), 'No') original, desired, k = 'aba', 'aba', 7 test_fn(is_conversion_possible(original, desired, k), 'Yes') original, desired, k = 'asdfqwertyuighjkzxcvasdfqwertyuighjkzxcvasdfqwertyuighjkzxcvasdfqwertyuighjkzxcvasdfqwertyuighjkzxcv', 'asdfqwertyuighjkzxcvasdfqwertyuighjkzxcvasdfqwertyuighjkzxcvasdfqwertyuighjkzxcvasdfqwertyuighjkzxcv', 20 test_fn(is_conversion_possible(original, desired, k), 'Yes') original, desired, k = 'aaaaaaaaaa', 'aaaaa', 7 test_fn(is_conversion_possible(original, desired, k), 'Yes') # Sherlock and Squares A, B = 3, 9 test_fn(count_squares_between(A, B), 2) A, B = 17, 24 test_fn(count_squares_between(A, B), 0) # Cut the Sticks sticks = [5, 4, 4, 2, 2, 8] test_fn(count_sticks(sticks), [6, 4, 2, 1])
n = int(input("Please enter the value of n: ")) while n > 1: print(str(int(n)), end = ' ') if(n % 2 == 1): # is an odd. n = n * 3 + 1 else: n = n / 2 print(str(int(n)), end = ' ')
# Tic Tac Toe # Reference: With modification from http://inventwithpython.com/chapter10.html. import random def drawBoard(board): """ Prints out the board that it was passed. Parameters: board: a list of 10 strings representing the board (ignore index 0) """ print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') def inputPlayerLetter(): """ Returns a list with the player’s letter as the first item, and the computer's letter as the second. """ # Lets the player type which letter they want to be. letter = '' while not (letter == 'X' or letter == 'O'): print('Do you want to be X or O?') letter = input().upper() # the first element in the list is the player’s letter, the second is the computer's letter. if letter == 'X': return ['X', 'O'] return ['O', 'X'] def whoGoesFirst(): """Randomly choose the player who goes first.""" if random.randint(0, 1) == 0: return 'computer' return 'player' def playAgain(): """Returns True if the player wants to play again, otherwise it returns False.""" print('Do you want to play again? (yes or no)') return input().lower().startswith('y') def makeMove(board, letter, move): """Enter letter to board""" board[move] = letter def isWinner(bo, le): """ Given a board and a player’s letter, this function returns True if that player has won. Parameters: bo: board le (string): a player's letter """ win_state = [[bo[7], bo[8], bo[9]], [bo[4], bo[5], bo[6]], [bo[1], bo[2], bo[3]], [bo[7], bo[4], bo[1]], [bo[8], bo[5], bo[2]], [bo[9], bo[6], bo[3]], [bo[7], bo[5], bo[3]], [bo[9], bo[5], bo[1]]] return [le, le, le] in win_state def getBoardCopy(board): """Make a duplicate of the board list and return it the duplicate.""" dupeBoard = [] for item in board: dupeBoard.append(item) return dupeBoard def isSpaceFree(board, move): """Return true if the passed move is free on the passed board.""" return board[move] == ' ' def getPlayerMove(board): """Let the player type in their move.""" next_move = ' ' while next_move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(next_move)): print('What is your next move? (1-9)') next_move = input() return int(next_move) def chooseRandomMoveFromList(board, movesList): """ Returns a valid move from the passed list on the passed board. Returns None if there is no valid move. """ possibleMoves = [] for i in movesList: if isSpaceFree(board, i): possibleMoves.append(i) if possibleMoves: return random.choice(possibleMoves) return None def getComputerMove(board, computerLe): """ Given a board and the computer's letter, determine where to move and return that move. """ if computerLe == 'X': playerLetter = 'O' else: playerLetter = 'X' # Here is our algorithm for our Tic Tac Toe AI: # First, check if we can win in the next move for i in range(1, CELL_NUMS): copy = getBoardCopy(board) if isSpaceFree(copy, i): makeMove(copy, computerLe, i) if isWinner(copy, computerLe): return i # Check if the player could win on their next move, and block them. for i in range(1, CELL_NUMS): copy = getBoardCopy(board) if isSpaceFree(copy, i): makeMove(copy, playerLetter, i) if isWinner(copy, playerLetter): return i # Try to take one of the corners, if they are free. move = chooseRandomMoveFromList(board, [1, 3, 7, 9]) if move is not None: return move # Try to take the center, if it is free. if isSpaceFree(board, 5): return 5 # Move on one of the sides. return chooseRandomMoveFromList(board, [2, 4, 6, 8]) def isBoardFull(board): """ Return True if every space on the board has been taken. Otherwise return False. """ for i in range(1, CELL_NUMS): if isSpaceFree(board, i): return False return True def play(theBoard, turn, letter): """Make a move depending on whose turn it is.""" if turn == 'player': # Player’s turn. drawBoard(theBoard) move = getPlayerMove(theBoard) else: # Computer's turn move = getComputerMove(theBoard, letter) makeMove(theBoard, letter, move) def check_current_state(theBoard, turn, letter): """ Returns: x (string): winner if there is one, otherwise None y (string): Done if there is a winner, Draw if there is a tie, otherwise Not done """ if isWinner(theBoard, letter): if turn == 'player': return 'player', 'Done' return 'computer', 'Done' elif isBoardFull(theBoard): return None, 'Draw' return None, 'Not done' def print_current_state(winner, state): """Prints the current board state.""" if winner: if winner == 'player': print('Hooray! You have won the game!') else: print('The computer has beaten you! You lose.') if state == 'Draw': print('The game is a tie!') def resetBoard(): """Resets the board""" print('Welcome to Tic Tac Toe!') theBoard = [' '] * CELL_NUMS players = inputPlayerLetter() turn = whoGoesFirst() player_index = 0 if turn == 'player': letter = players[0] else: letter = players[1] player_index = 1 print('The ' + turn + ' will go first.') winner = None while winner is None: play(theBoard, turn, letter) winner, state = check_current_state(theBoard, turn, letter) print_current_state(winner, state) if state in ('Done', 'Draw'): drawBoard(theBoard) if playAgain(): resetBoard() else: break else: if turn == 'player': turn = 'computer' else: turn = 'player' player_index ^= 1 letter = players[player_index] if __name__ == "__main__": CELL_NUMS = 10 resetBoard()
#!/usr/bin/python2.6 # -*- coding : utf-8 -* # Homme ou femme prenom = raw_input("entrez votre prenom: ") nom = raw_input("entrez votre nom: ") sexe = raw_input("entrez f si vous etes une femme et m si vous etes un homme : ") while s != "f": sexe = raw_input("la valeur entrez n'est ni f ni m : ") if sexe == "f" or sexe =="m": s print("bonjour Madame", prenom, nom) else: print("bonjour Monsieur", prenom, nom)
#!/usr/bin/python2.6 # -*- coding : utf-8 -* # Ecrivez un programe qui calcule le perimetre et l'air d'un trianagle # dont, les 3 cotes sont fourni par l'utilisateur from math import * print("calcul ddu perimetre et l'air d'un triangle") a = raw_input("entrer la logueur du cote a: ") a = float(a) b = raw_input("entrer la logueur du cote b: ") b = float(b) c = raw_input("entrer la logueur du cote c: ") c = float(c) d = ( a + b + c ) / 2 print("perimetre du triangle est ", a + b + c) s = sqrt(d * (d-a) * (d-b) * (d-c)) print("surface du traingle", s)
import numpy as np import cv2 ## Image reading frame = cv2.imread('paper_test5.jpg') ## Image resizing logic r = 400.0 / frame.shape[1] dim = (400, int(frame.shape[0] * r)) frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA) ### smoothing the noise frame=cv2.GaussianBlur(frame, (5,5),0) # convert the image to grayscale for processing imgray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(imgray,127,255,0) ## finding contours contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) ## drawing contours over original image #img = cv2.drawContours(img, contours[3], -1, (255,255,0), 3) cv2.drawContours(frame, contours, -1, (200,200,0), 3) ## printing no of contours present in the image print len(contours) # displating final image cv2.imshow('image',frame) cv2.waitKey(0) cv2.destroyAllWindows()
class MergeSort: @classmethod def get_reference(cls, data): return cls._merge_sort(data, 0, len(data)-1) @classmethod def _merge_sort(cls, A, start, end): if end <= start: return mid = start + ((end - start + 1) // 2) - 1 yield from cls._merge_sort(A, start, mid) yield from cls._merge_sort(A, mid + 1, end) yield from cls._merge(A, start, mid, end) @classmethod def _merge(cls, A, start, mid, end): merged = [] leftIdx = start rightIdx = mid + 1 while leftIdx <= mid and rightIdx <= end: yield A if A[leftIdx] < A[rightIdx]: merged.append(A[leftIdx]) leftIdx += 1 else: merged.append(A[rightIdx]) rightIdx += 1 while leftIdx <= mid: yield A merged.append(A[leftIdx]) leftIdx += 1 while rightIdx <= end: yield A merged.append(A[rightIdx]) rightIdx += 1 for i in range(len(merged)): A[start + i] = merged[i] yield A
'''try: 1/0 except Exception as ex: print(ex) finally: print('inside finally')''' #finally block will execute everytime the code will run '''try: a=20 except Exception as ex: print(ex) else: print('ex')''' #else code will only run if the code does not have an exception #if any exception come then else code will not run '''try: a=20 exit(1) except Exception as ex: print(ex) else: print('ex')''' #exit() function used to kill the program right away when compiler compile the exit line '''a='hi {},hello {}' a=a.format('python','java') print(a)''' #format function can add the values at the braces define in the string '''a='hi {1},hello {0}' a=a.format('python','java') print(a)''' #we can use key in the braces '''a='hi {j},hello {p}' a=a.format(p='python',j='java') print(a)''' #we can use variables in the braces '''try: 1/0 finally: print('hi')''' #try can be used either with the except or with finally '''try: 1/0 except Exception: print('exception') else: print('else') finally: print('hi')''' #after try block there has to be an except block and after that we can use else block #and finally block can be used after the try and exception block try: a=20 print(a) try: n='hi' try: print(n) n.index('z') finally: print('end') except AttributeError: print('inside attribute error') except ValueError as ex: print(ex) except Exception: print(ex) else: print('else') finally: print('end')
num=input('enter any number=') num=int(num) if num%2==0: num1=(num/2)+1 num1=int(num1) num2=0 for a in range(0,num1): if a==0: print('*') continue else: for b in range(num2+2): print('*',end='') num2+=2 print('') num3=num1+1 for a in range(num3,num+2): if a==num+2-1: print('*') break for b in range(num2-2): print('*',end='') print('') num2-=2 else: num1=(num/2)+1 num1=int(num1) for a in range(1,num1+1): for b in range((a*2)-1): print('*',end='') print('') p=num-2 for a in range(num,num1,-1): for b in range(p): print('*',end='') print('') p=p-2
import random d=0 for i in range(1,11): print(i,'chance--') a=random.randrange(1,6) b=random.randrange(1,6) print('1st dice value=',a,' ','2nd dice value=',b) c=a+b print('total dice value=',c) if(d+c)>50: if(i>9): print('you lose the game') continue else: d=d+c print('total chance values=',d) if d==50: print() print('you won the game') break print()
l=[0,0,0,0,0] for i in range(5): l[i]=int(input('enter a number')) maximum=l[0] minimum=l[0] for i in l: if maximum>i: continue else: maximum=i for i in l: if minimum<i: continue else: minimum=i print('maximum value is=',maximum) print('minimum value is=',minimum)
def change(a,b): c=a.upper() d=b.upper() j=0 l=[] for i in range(len(c)): if c[i]==' ' or c[i]==',': if c[j:i]==d: l.append(c[j:i]) else: l.append(a[j:i]) j=i+1 if i==len(c)-1: if c[j:i+1]==d: l.append(c[j:i+1]) else: l.append(a[j:i+1]) print(l) for i in range(len(l)): if l[i]==d: l[i]=r print(" ".join(l)) a=input('enter any sentence') b=input('enter the word you wanna replace') r=input('replacement word') change(a,b)
'''class Students: def __init__(self): print('inside') self.name = 'rohit' self.age = 25 self.course = 'python' print('before') obj1 = Students() print('after') print(obj1.name) print(obj1.age) print(obj1.course) print(dir(obj1)) obj2 = Students()''' '''class Students: def __init__(self, name, age, course): self.name = name self.age = age self.course = course obj1 = Students('vivek', 21, 'python') obj2 = Students('ranvijay', 23, 'python') print(obj1.name) print(obj2.name)''' '''class Students: studentcount=0 def __init__(self, name, age, course,rollno): self.name = name self.age = age self.course = course self.rollno = rollno Students.studentcount += rollno def print_info(self): print(self.name) print(self.age) print(self.course) print(self.rollno) print(Students.studentcount) obj1 = Students('vivek', 21, 'python', 1) obj1.print_info() print(Students.studentcount) obj2 = Students('shubham', 22, 'python', 1) obj2.print_info() print(Students.studentcount)''' class Student: fee = 10000 noofstd = 0 def __init__(self, name): self.name = name def print_info(self): print(self.name) @classmethod def discount(cls, dis): return cls.fee-(cls.fee*dis)/100 obj1=Student('vivek') obj1.print_info() print(Student.discount(10))
'''a=input('enter any number') a=int(a) b=input('enter any number') b=int(b) c=input('enter any number') c=int(c) d=input('enter any number') d=int(d) print(max(a,b,c,d)) print(min(a,b,c,d))''' l=[0,0,0,0] for i in range(4): l[i]=input('enter a number') print(max(l)) print(min(l))
# Handling different exceptions using with block multi resources try: with open("app.py") as file1, open("test.py", "w") as file2: print(file1) print(type(file1)) print(file2) print(type(file2)) print("File opened for read and closed prop") age = int(input("Enter Age : ")) xfactor = 10 // age except (ValueError, ZeroDivisionError) as ex: print("exception type {} and value : {}".format(type(ex), ex)) print("Enter valid age between 1-110") else: print("will be printed if no exception occurs") print("Exceution continues ....")
from math import sqrt, floor def p(n): c = 0 lp = [2,3,5,7,11] d = 13 while c <= (n-6): if isitprime(d): lp.append(d) c += 1 d += 2 print(lp[-1]) def isitprime(x): c = 0 y = int(sqrt(x)) for a in range(2, y+1): if x%a == 0: c += 1 if c >= 1: return False else: return True p(10001)
#!/bin/python3 # scraper.py # The scraper will go to a Wikipedia page, scrape the title, and follow # a random link to the next Wikipedia page. import requests from bs4 import BeautifulSoup import random import time BASE_URL = 'https://en.wikipedia.org' def scrape_wiki_article(url): response = requests.get(url=url) soup = BeautifulSoup(response.content, 'html.parser') title = soup.find(id='firstHeading') print(title.text) # Get all the links all_links = soup.find(id='bodyContent').find_all('a') random.shuffle(all_links) link_to_scrape = 0 for link in all_links: # We are only interested in other wiki articles if link['href'].find('/wiki/') == -1: continue # Use this link to scrape link_to_scrape = link break # Wait for 5 so user has time to kill the app time.sleep(5) scrape_wiki_article(BASE_URL + link_to_scrape['href']) scrape_wiki_article(BASE_URL + '/wiki/Web_scraping')
#!/usr/bin/env python bursttime=[] print("Enter number of process: ") noOfProcesses=int(input()) processes=[] for i in range(0,noOfProcesses): processes.insert(i,i+1) print("Enter the burst time of the processes: \n") bursttime=list(map(int, raw_input().split())) for i in range(0,len(bursttime)-1): for j in range(0,len(bursttime)-i-1): if(bursttime[j]>bursttime[j+1]): temp=bursttime[j] bursttime[j]=bursttime[j+1] bursttime[j+1]=temp temp=processes[j] processes[j]=processes[j+1] processes[j+1]=temp waitingtime=[] avgwaitingtime=0 turnaroundtime=[] avgturnaroundtime=0 waitingtime.insert(0,0) turnaroundtime.insert(0,bursttime[0]) for i in range(1,len(bursttime)): waitingtime.insert(i,waitingtime[i-1]+bursttime[i-1]) turnaroundtime.insert(i,waitingtime[i]+bursttime[i]) avgwaitingtime+=waitingtime[i] avgturnaroundtime+=turnaroundtime[i] avgwaitingtime=float(avgwaitingtime)/noOfProcesses avgturnaroundtime=float(avgturnaroundtime)/noOfProcesses print("\n") print("Process\t Burst Time\t Waiting Time\t Turn Around Time") for i in range(0,noOfProcesses): print(str(i)+"\t\t"+str(bursttime[i])+"\t\t"+str(waitingtime[i])+"\t\t"+str(turnaroundtime[i])) print("\n") print("Average Waiting time is: "+str(avgwaitingtime)) print("Average Turn Arount Time is: "+str(avgturnaroundtime))
import random from .card import Card, NUMBERS, SUITS class Deck: def __init__(self) -> None: self._cards = [ Card(num, suit) for suit in SUITS # 🗡 🌳 🥇 🏆 for num in NUMBERS ] def shuffle(self) -> None: """Shuffles the cards in the deck.""" random.shuffle(self._cards) def pop(self) -> Card: """Returns a card from the deck. Returns None if deck is empty.""" return self._cards.pop(0) if self._cards else None
import sqlite3 import os def connect_db(db_name): return sqlite3.connect(db_name) def execute_sql(db_file,sql): assert os.path.isfile(db_file), "Database %s does not exist"%db_file with sqlite3.connect(db_file) as conn: c = conn.cursor() c.execute(sql) file_entry = c.lastrowid conn.commit() return file_entry def select(db_file,sql): assert os.path.isfile(db_file), "Database %s does not exist"%db_file result = [] with sqlite3.connect(db_file) as conn: c = conn.cursor() for row in c.execute(sql): result.append(row) return result def parse_knowledge_file(file_name): with open(file_name,'rb') as f: kstring = f.read() lines = kstring.split('\r\n') lines = [l.split('#')[0] for l in lines] tuples = [tuple(l.split('>')) for l in lines] statements = [t for t in tuples if len(t)==3] return statements
# Matrix Algebra # Insert the given vectors/ matrices import numpy from numpy import linalg as LA A = numpy.matrix([[1, 2, 3], [2, 7, 4]]) B = numpy.matrix([[1, -1], [0,2]]) C = numpy.matrix([[5, -1], [9,1], [6,0]]) D = numpy.matrix([[3, -2, -1], [1, 2, 3]]) u = numpy.array([6, 2, -3, 5]) v = numpy.array([3, 5, -1, 4]) w = numpy.array([[1], [8], [0], [5]]) # Exercise 1 dimA = A.shape dimB = B.shape dimC = C.shape dimD = D.shape dimu = u.shape dimw = w.shape print "Answer 1.1): ", dimA print "Answer 1.2): ", dimB print "Answer 1.3): ", dimC print "Answer 1.4): ", dimD print "Answer 1.5): ", dimu print "Answer 1.6): ", dimw #Exercise 2 alpha = 6 print "Answer 2.1: ", u+v print "Answer 2.2: ", u-v print "Answer 2.3: ", alpha * u print "Answer 2.4: ", numpy.dot(u, v) print "Answer 2.5: ", LA.norm(u) #Exercise 3 print "Answer 3.1: not defined." print "Answer 3.2: ", A - C.transpose() print "Answer 3.3: ", C.transpose() + 3*D print "Answer 3.4: ", numpy.dot(B, A) print "Answer 3.5: not defined"
a = 1 p = 1 while a <= 12: print(a, "AM") a = a + 1 while p <= 12: print(p, "PM") p = p + 1
#Github: https://github.com/elinbua/TileTraveller def start_point(): """The game starts in num= 1.1 and possible direction is north (route = 1)""" num = 1.1 route = 1 print("You can travel: (N)orth.") return num, route def direction(): """Enter direction""" direction_str = input("Direction: ") return direction_str def move(num, direction_str, route, Low = 1, High = 3.3): """Move player to next position in selected direction. The player can only be moved to direction in valid route.""" north = 'nN' south = 'sS' east = 'eE' west = 'wW' valid = 1 if (route == 1 or route == 2 or route == 6) and direction_str in north: move_north = round(num + 0.1 , 1) if Low < move_north <= High: num = move_north else: num = num elif (route == 2 or route == 3 or route == 4 or route == 6) and direction_str in south: move_south = round(num - 0.1, 1) if Low < move_south <= High: num = move_south else: num = num elif (route == 2 or route == 3 or route == 5) and direction_str in east: move_east = round(num + 1.0, 1) if Low < move_east <= High: num = move_east else: num = num elif (route == 4 or route == 5) and direction_str in west: move_west = round(num - 1.0, 1) if Low < move_west <= High: num = move_west else: num = num else: valid = 0 print("Not a valid direction!") return num, valid def new_route(num): """Where can player travel from current position""" if num == 1.1 or num == 2.1: route = 1 print("You can travel: (N)orth.") elif num == 1.2: route = 2 print("You can travel: (N)orth or (E)ast or (S)outh.") elif num == 1.3: route = 3 print("You can travel: (E)ast or (S)outh.") elif num == 3.3 or num == 2.2: route = 4 print("You can travel: (S)outh or (W)est.") elif num == 2.3: route = 5 print("You can travel: (E)ast or (W)est.") elif num == 3.2: route = 6 print("You can travel: (N)orth or (S)outh.") elif num == 3.1: print("Victory!") return route count = 0 end = 3.1 valid = 1 num, route = start_point() while True: direction_str = direction() num, valid = move(num, direction_str, route) if valid == 0: continue else: route = new_route(num) if num == end: break count +=1
from domain import Room,Reservation import random import datetime import calendar import unittest class Service: def __init__(self,roomRepo,reservationRepo,reservationValidator): self.__roomRepo = roomRepo self.__resRepo = reservationRepo self.__resValid = reservationValidator() def getRooms(self): return self.__roomRepo.getAll() def getReservations(self): return self.__resRepo.getAll() def checkAvailableRoom(self,roomNo,arrival,departure): """ Method that checks if the room (with a given number) is available during the given reservation dates. :param roomNo: int - the unique room number :param arrival: date - complete arrival date :param departure: date - complete departure date :return: True/False """ for res in self.__resRepo.getAll(): if res.getRoomNo() == roomNo and arrival < res.getDeparture() and departure > res.getArrival(): return False return True def createReservation(self,famName,roomType,guestsNo,arrival,departure): """ Method that creates a new reservation, after validating the user input data. :param famName: string - the given family name :param roomType: int - 1 (single), 2 (double), 4 (family) :param guestsNo: int - from 1 to 4 :param arrival: date - complete arrival date :param departure: date - complete departure date :return: nothing """ self.__resValid.validate(Reservation(None,None,famName,guestsNo,arrival,departure)) roomNumber = False for room in self.__roomRepo.getAll(): if room.getType() == roomType: if self.checkAvailableRoom(room.getNr(),arrival,departure): roomNumber = room.getNr() break if not roomNumber: raise Exception("There are no available rooms of the desired type during the reservation dates!") resID = random.randint(1000, 9999) while Reservation(resID,None,None,None,None,None) in self.__resRepo.getAll(): resID = random.randint(1000,9999) self.__resRepo.add(Reservation(resID,roomNumber,famName,guestsNo,arrival,departure)) def deleteRsv(self,ID): """ Method that removes a reservation using its given ID, by calling the repo remove method. :param ID: int - the unique number of the reservation :return: nothing """ self.__resRepo.remove(Reservation(ID,None,None,None,None,None)) def getAvailableRooms(self,date1,date2): if date1 > date2: raise Exception("First date is after the second date!") avRooms = [] for room in self.__roomRepo.getAll(): if self.checkAvailableRoom(room.getNr(),date1,date2): avRooms.append(room) return avRooms def getMonthlyReport(self): monthsNights = [0]*13 y = datetime.date.today().year for res in self.__resRepo.getAll(): a = res.getArrival() d = res.getDeparture() m1 = a.month m2 = d.month nights = (d-a).days if m1 == m2: monthsNights[m1] += nights else: m2first = datetime.date(y,m2,1) m2Nights = (d-m2first).days monthsNights[m2] += m2Nights monthsNights[m1] += (nights-m2Nights) finalMonthsNights = [] for i in range(1,13): finalMonthsNights.append([calendar.month_name[i],monthsNights[i]]) finalMonthsNights.sort(key=lambda x: x[1], reverse=True) return finalMonthsNights def getWeekDaysReport(self): daysFrequency = {} for res in self.__resRepo.getAll(): a = res.getArrival() d = res.getDeparture() for i in range((d-a).days): day = calendar.day_name[(a+datetime.timedelta(i)).weekday()] daysFrequency[day] = daysFrequency[day] + 1 if day in daysFrequency else 1 finalDaysFrequency = list(map(list,daysFrequency.items())) finalDaysFrequency.sort(key=lambda x: x[1], reverse=True) return finalDaysFrequency class TestReservations(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) from repo import FileRepo from domain import ReservationValidator self.RoomsRepo = FileRepo("rooms.txt", Room.readRoom, Room.writeRoom) self.ResRepo = FileRepo("test.txt",Reservation.readReservation,Reservation.writeReservation) self.srv = Service(self.RoomsRepo,self.ResRepo,ReservationValidator) self.y = datetime.date.today().year def tearDown(self): unittest.TestCase.tearDown(self) def testCheckAvailableRoom(self): self.assertTrue(self.srv.checkAvailableRoom(3,datetime.date(self.y,3,3),datetime.date(self.y,4,4))) self.assertFalse(self.srv.checkAvailableRoom(1,datetime.date(self.y,1,2),datetime.date(self.y,1,12))) def testCreateReservation(self): self.srv.createReservation('Test',4,4,datetime.date(self.y,11,11),datetime.date(self.y,11,12)) reservations = self.srv.getReservations() lastRes = reservations[-1] self.assertEqual(lastRes.getFam(),'Test') self.srv.deleteRsv(lastRes.getID()) def testDeleteReservation(self): firstRes = self.srv.getReservations()[0] ID = firstRes.getID() self.srv.deleteRsv(ID) self.assertTrue(firstRes not in self.srv.getReservations()) self.ResRepo.add(firstRes)
from domain import Question import math class Service: def __init__(self,questionsRepo): self.__qRepo = questionsRepo def addQuestion(self,parts): """ Function that adds a new question to the master question list. :param parts: list - the elements of the question :return: nothing """ newQ = Question(int(parts[0]),parts[1].strip(),parts[2].strip(),parts[3].strip(),parts[4].strip(),parts[5].strip(),parts[6].strip()) self.__qRepo.add(newQ) def addNecessaryQuestions(self,qNo,diff): qList = [] requiredDiffQ = math.ceil(qNo / 2) found = 0 for q in self.__qRepo.getAll(): if q.getDifficulty() == diff: if found < qNo: qList.append(q) found += 1 else: break if found < requiredDiffQ: raise Exception("There are not enough questions to create the quiz!") return qList def createQuiz(self,diff,qNo,file): qList = self.addNecessaryQuestions(qNo,diff) found = len(qList) if found < qNo: for q in self.__qRepo.getAll(): if q not in qList: qList.append(q) found += 1 if found == qNo: break if found < qNo: raise Exception("There are not enough questions!") f = open(file,'w') for q in qList: f.write(Question.writeQ(q)+'\n') f.close() @staticmethod def getQuiz(file): f = open(file,'r') qList = [] lines = f.readlines() for line in lines: line = line.strip() if line != "": qList.append(Question.readQ(line)) f.close() qList.sort(key=lambda q: ('easy','medium','hard').index(q.getDifficulty())) return qList @staticmethod def computeScore(questions,answers): score = 0 points = {'easy':1,'medium':2,'hard':3} n = len(questions) for i in range(n): choices = questions[i].getChoices() userAns = choices[answers[i]] if userAns == questions[i].getCorrectAns(): score += points[questions[i].getDifficulty()] return score
def createPhone(manufacturer, model, price): return {'mnf':manufacturer, 'model':model, 'price':price} def add_phone(phone,phoneList): if len(phone['mnf'])<3 or len(phone['model'])<3 or len(str(phone['price']))<3: raise ValueError("Invalid phone!") phoneList.append(phone) def phones_by_manufacturer(mnf,phoneList): """ Function that selects only the phones from a given manufacturer. :param mnf: str - the name of the manufacturer :param phoneList: - list of dictionaries = phones :return: nothing """ selectedPhones = [] for phone in phoneList: if phone['mnf'] == mnf: selectedPhones.append(phone) return selectedPhones def update_price(mnf,model,amount,phoneList): ok = False for phone in phoneList: if phone['mnf'] == mnf and phone['model'] == model: phone['price'] += amount ok = True if ok is False: raise Exception("There is no phone like this!") def compute_percentage(percent,x): return x*percent/100 def update_all_percentage(percentage, phoneList): if percentage < -50 or percentage > 100: raise ValueError("Percent value is not within the required bounds!") for phone in phoneList: phone['price'] += compute_percentage(percentage,phone['price'])
class ConsoleMenu: def __init__(self,songSrv): self.__songSrv = songSrv self.__menu = "\nPress: [1] to search songs by name\n" \ "[2] to show the songs with the same genre as a given song" @staticmethod def printSongs(songs): for song in songs: print(song) def showAll(self): theSongs = self.__songSrv.getAllSongs() self.printSongs(theSongs) def searchSongsByName(self): searchStr = input("Search: ").strip() results = self.__songSrv.nameSearch(searchStr) print("The results are:") self.printSongs(results) def showSameGenre(self): try: sID = int(input("Insert the ID of the song: ")) if sID < 0: raise ValueError except ValueError: raise Exception('The ID is not a natural number!') genre = self.__songSrv.getGenre(sID) print('The searched genre: {}'.format(genre)) results = self.__songSrv.genreSearch(genre) self.printSongs(results) def run(self): options = {1:self.searchSongsByName,2:self.showSameGenre,0:self.showAll} while True: print(self.__menu) try: choice = int(input("->")) if choice == 3: exit() if choice not in (1,2,0): raise Exception('Non-existent option!') options[choice]() except Exception as ex: print("Error: " + str(ex))
# LAB 1 : Threading - Bank accounts """ At a bank, we have to keep track of the balance of some accounts. Also, each account has an associated log (the list of records of operations performed on that account). Each operation record shall have a unique serial number, that is incremented for each operation performed in the bank. We have concurrently run transfer operations, to be executed on multiple threads. Each operation transfers a given amount of money from one account to some other account, and also appends the information about the transfer to the logs of both accounts. From time to time, as well as at the end of the program, a consistency check shall be executed. It shall verify that the amount of money in each account corresponds with the operations records associated to that account, and also that all operations on each account appear also in the logs of the source or destination of the transfer. Operations: - transfer (- one account, + the other account) - consistency check : in the main thread, function that: (each 60s) - checks the amount of money with the history of operations from the start - check each operation to appear in the history of source/dest """ import time from threading import Lock import threading import random operation_id = 0 operation_mutex = Lock() no_of_threads = 10 bank_accounts = [] max_runtime = 420 class BankAccount: def __init__(self, iban, balance, log_file): self.__iban = iban self.__start_balance = balance self.__balance = balance self.__log_file = log_file self.__mutex = Lock() self.__log_mutex = Lock() def get_iban(self): return self.__iban def receive_money(self, op_id, amount, sender): self.__mutex.acquire() self.__balance += amount self.__mutex.release() self.__log_mutex.acquire() self.log_transfer(op_id,"receive",amount,sender) self.__log_mutex.release() # provide with mutex lock and log the transfer with the sender def send_money(self, amount, dest): self.__mutex.acquire() if amount > self.__balance: self.__mutex.release() raise Exception(self.__str__() + " - insufficient founds") self.__balance -= amount self.__mutex.release() operation_mutex.acquire() global operation_id operation_id += 1 # this should also be locked new_op_id = operation_id operation_mutex.release() self.__log_mutex.acquire() self.log_transfer(new_op_id,"send",amount,dest) self.__log_mutex.release() return new_op_id # provide with mutex lock and log the transfer with the dest def log_transfer(self, op_id, transfer_type, amount, sender_or_dest): with open(self.__log_file, "a+") as log: print("\nLogging: in file " + self.__iban + " transfer from/to " + sender_or_dest) log.write("ID" + str(op_id) + "-" + transfer_type + "-" + str(amount) + "-" + sender_or_dest + "\n") def consistency_check(self): self.__mutex.acquire() self.__log_mutex.acquire() log_computed_balance = self.__start_balance with open(self.__log_file,"r") as log: lines = log.readlines() for line in lines: tokens = line.split("-") op_id = tokens[0] found = False second_account_file = tokens[3][:-1] + ".log" with open(second_account_file,"r") as log2: lines2 = log2.readlines() for l2 in lines2: if l2.split("-")[0] == op_id: found = True break if not found: break if tokens[1] == "receive": log_computed_balance += int(tokens[2]) elif tokens[1] == "send": log_computed_balance -= int(tokens[2]) if log_computed_balance == self.__balance and found: print(self.__str__(),"consistency check passed.") else: print(self.__str__(),"consistency check FAILED: " "found ->",found, ", log balance ->", log_computed_balance, ", balance ->", self.__balance) self.__log_mutex.release() self.__mutex.release() def __str__(self): return "Account " + self.__iban def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. global bank_accounts for ba in bank_accounts: print(ba) def thread_function(idx): while True: if operation_id >= 1111: break account1 = random.choice(bank_accounts) account2 = random.choice([ba for ba in bank_accounts if ba.get_iban() != account1.get_iban()]) amount = random.randint(1,420) print("\nThread " + str(idx) + " working: " + str(account1) + " transfer to " + str(account2)) try: new_op_id = account1.send_money(amount, account2.get_iban()) account2.receive_money(new_op_id, amount, account1.get_iban()) except Exception as e: print(e) if operation_id >= 1111 or time.time() - start_time >= max_runtime: break time.sleep(2) # Press the green button in the gutter to run the script. if __name__ == '__main__': a1 = BankAccount("IBAN1",42000420,"IBAN1.log") a2 = BankAccount("IBAN2",42200420,"IBAN2.log") a3 = BankAccount("IBAN3",12220420,"IBAN3.log") a4 = BankAccount("IBAN4",22220420,"IBAN4.log") a5 = BankAccount("IBAN5",44444420,"IBAN5.log") bank_accounts = [a1,a2,a3,a4,a5] threads = [] print_hi('Main thread') start_time = time.time() for index in range(no_of_threads): x = threading.Thread(target=thread_function, args=(index,)) threads.append(x) x.start() consistency_check_time = time.time() while True: if time.time() - consistency_check_time >= 10: for a in bank_accounts: a.consistency_check() consistency_check_time = time.time() if operation_id >= 1111 or time.time() - start_time >= max_runtime: for x in threads: x.join() break for a in bank_accounts: a.consistency_check() print(f"\n{no_of_threads} threads done:\n{operation_id} operations in {'{:.2f}'.format(time.time()-start_time)} s")
str = 'ashanti is an idiot' print(str.capitalize()) # capitalise print(str.count("an", 0, len(str))) # look for occurence of text in a string s = str.encode('utf-8', 'strict') print(s) ################################################################## print(max(str)) print(min(str)) ################################################################## print(str.replace('ashanti', '---E---', 1)) ################################################################### print(str.upper()) ############################################################### print(str.index('idiot')) ############################################################## print(str[::-1]) # reverses string print(str[3:8]) # return print(str.find('a')) # returns the index at which the given letter is present in String print(str + str) # concatenation of String print(str * 2) # also a form of concatenation str2 = "This is a bullshit story, %s, lets talk about the money %f" print(str2 % ("Laura", 23.55)) ######################################################################################## # Tuple is sequential immutable python objects...just like lists(mutable) tup1 = ("Hadoop", "Python", "Java") print(len(tup1)) # gives the total length of the tuple print(max(tup1)) # returns items with the max value print(min(tup1)) # returns items from tuple with min value ##tuple - sorting and reversing tup2 = (1, 3, 4, 5, 2, 78, 3) print(sorted(tup2)) print(tup2[::-1]) print(len(tup1)) # shows length of tuple print(tup1 * 2) # repitition print("Hadoop" in tup1) # check if the word is in a text tup3 = (1, 3, 5, 6, 9) tup4 = (5, 7, 9, 0, 1) tup5 = tup3 + tup4 # concatenating tuples - updating tuples print(tup5) del tup3 # deleting elements # print(tup3) # Difference between Lists and Tuples list1 = [1, 2, 3, 'John', 'Uber'] print(list1) list1[2] = 'Rogers' print(list1) tup = (1, 2, 3, 'Roger') print(tup) # tup[1] = 'Python' # tuple does not allow this type of change print(tup) # A list inside a tuple tup_list = ([1, 2, 3], [4, 5, 6], [7, 8, 9]) # lists in a tuple print(tup_list) print(len(tup_list)) # count of lists in a tuple print(tup_list[0][0:2]) # slicing return 2 elements from the 1 element print(tup_list[::-1]) # reversing the ordering of the lists # Updating tuple tup_list[0][1] = 90 # you can update a tuple because you are using lists in them print(tup_list) # deleting element in tuple del (tup_list[1][2]) print(tup_list) # converting tuples into lists tuple20 = (1, 2, 4, 5, 'Regarere') lst = list(tuple20) # converting tuple to list to make changes to the tuple print(lst) lst[1] = 'R' print(lst) tuple21 = tuple(lst) print(tuple21) print(type(tuple21)) # list - indexing and slicing list1 = ['Hadoop', 'Rust', 'SAS', 'Python'] print(list1[1]) # return index 1 print(list1[0:2]) # return from index 0 and 1 aka the first two indexes print(list1[-1]) # for an non empty list return the first index from the reverse print(list1[::-1]) # reverse the list # list - updating and deleting elements list3 = ['Python', 'Java', 'Orange'] list3[1] = 'Rose' print(list3) del (list3[2]) print(list3) # remove and pop functions list4 = [1, 2, 3, 4, 5, 'a', 'b', 'c'] print(list4.pop(3)) # returns the element at a given index list4.remove('a') print(list4) # type() list5 = [1, 2, 3, 'King', 'Queen'] print(type(list5)) print([x ** 2 for x in [2, 3, 4, 5, 6, 7]]) # loop can be used in print to show # squares of elements of lists # lists - built in functions list6 = [1, 2, 3, "Machine Learning"] list6.append("Richard") # add item to the end of the list print(list6) list6.extend(['g', 'j']) # insert many items at the end of list print(list6) list6.insert(3, 'Scripting') # insert an item at a given position print(list6) list6.remove(1) # removes an item from the list print(list6) list7 = ['Python', 'Neko', 'Abiola', 'Ola'] print(sorted(list7)) # sorted list print(list7[::-1]) # reverses the list # A tuple in a list list8 = [(1, 2, 3), ("Python", "Mather", "Rage")] # tuples in a list print(list8) print(len(list8)) # count of tuples in a list print(list8[1][0:1]) # slicing # list8[0][1] = 50 # using a tuple makes the list immutable TypeError: 'tuple' object does not support item assignment print(list8) # Dictionaries - this is an unordered collection of key value pairs. Used when you have # a huge amount of data dict1 = {1: 'Heroku', 2: 'Java'} # creating a dictionary print(dict1) print(dict1[1]) # accessing values in dictionaries # Updating elements dict1[1] = "Javascript" print(dict1) del (dict1[2]) # deleting elements print(dict1) # Built in functions of dictionaries dict2 = {1: 'Python', 2: 'Android'} print(len(dict2)) # returns the length of the dictionary # print(str(dict2)) # returns the dictionary as String print(type(dict2)) # returns type rec = {'name': {'first': 'Bob', 'last': 'Smith'}, 'jobs': ['dev', 'mgr'], 'age': 40.5} print(rec.get('name')) # returns the value of the key passed print(dict2.items()) # returns items in dictionary in the form of tuples print(dict2.keys()) # returns keys in dictionary print(dict2.values()) # returns values in dictionary print(dict2.setdefault(1, 4)) # Methods of dictionaries dict6 = {1: "Prada", 2: "Gucci"} print(dict6.copy()) # creates copy of dictionary dict6.clear() # deletes all the emelemts in dictionary print(dict6) # Sorting Keys for Loops dic = {3: 'Rosku', 1: 'Python', 2: 'Night'} ks = list(dic.keys()) # return dictionary keys as a list print(ks) sk = sorted(ks) # sk sorts the keys of the dictionary print(sk) for key in sk: print(key, '=>', dic[key]) # prints sorted keys with their respective values # Tuple and List in Dictionary # tuple in set dic1 = {1: (1, 2, 3), 2: (3, 4, 5, 6)} # tuples are given as elements in dictionary print(dic1) print(dic1[1][1]) # return index 1 in the dict and the index 1 in the value of key 2 # list in set dic2 = {1: ('Python', 'Java'), 2: [1, 2, 3, 4]} print(dic2) print(dic2[1][0]) # Set is an unordered collection of unique items, Set is defined by values separated by comma # inside braces() # Set can also be created by calling the inbuilt in set function: x = set("Welcome to hell") # unique values are the rule..duplicates will be removed print(type(x)) print(x) # set operation - union a = {1, 2, 3, 4, 5} b = {4, 5, 6, 7, 9, 10} print(a | b) # it will join but remove duplicates print(a & b) # intersection: return common elements in the two sets only print(a - b) # difference - join and return elements in a but not b print(b - a) # difference - join and return elements in b but not a # more set examples set1 = {'a', 'b', 'c', 'd'} set2 = {'a', 'c', 'e', 'd'} print(set1 | set2) # union print(set1 & set2) # intersection print(set1 - set2) # difference s = {1, 2, 3, 'a', 't'} set1 = {1, 'a', 'b'} print(1 in s) # testing if 1 is in s set print(set1.issubset(s)) # Returns true if set 1 is a subset of s print(5 not in s) print(s.issuperset(set1)) # returns true if s is a super set of set1 print(s.union(set1)) print(s.intersection(set1)) print(s.difference(set1)) print(s.symmetric_difference(set1)) s.add('c') # add elements to set print(s) s.remove(3) # removes element from set print(s) s.discard(9) # removes element from set if present print(s) s.pop() # removes and returns an arbitrary element from list print(s) s.clear() # removes all element from set print(s) # conditional statements # if x = 9 y = 23 if (x < y): print("X is less than Y") elif (x > y): print("X is greater than Y") else: print("X equals Y") # While condition will keep running until a condition is met count = 0 while (count <= 10): print(count) count = count + 1 print("Testing done") # for will repeat a group of statements a specified amount of types for x in (1, 2, 3, 4, 6): counter = x * 2 print(counter) # we do not know the number of iterations in while loop but in for loop we do. fruits = ['Banana', 'Rice', 'Apple'] for index in range(len(fruits)): print(fruits[index]) # factorial x = 10 for x in range(10): print(x * x) # Nested Loops # count=1 # for i in range(10): # print(str(i) * i) # # for j in range(10): # count=count + 1 # # Loop Control Statements # break statement - terminates the loop process and transfers to statement immediately following the loop statement # continue = causes the loop to skip the remainder of its body and immediately retest # its condition prior to reiterating # pass statement - the pass statement in python is used when a statement is required # syntactically but you do not want any command or code to execute for i in range(10, 50): print(i) if(i==30): #return 10 to 50 but break at 30 break for j in range(1, 11): print(j) if(j==5):#return 1 to 11 if j = 5 then retest whether j is between 1 to 11 continue k = 4 for k in range(1, 3): pass # if k is between 1 to 3 then pass(do not run this loop) print("Do not run this loop") #Input - Reading Keyboard Input inputStr = input("Enter your input") print("Your input is "+ inputStr) #Opening and Closing Files #Opening a file #To manipulate a file in python you need top open it spec_char = [] for i in range(35, 65): spec_char.append(chr(i)) print(spec_char)
from decimal import Decimal, getcontext import os getcontext().prec = 10 def line(): print() print("-=" * 30) print() def header(msg): line() print(f"{msg:^60}") line() def showMenu(): header("MENU PRINCIPAL") print("""[1] Calcular Frete [2] Calcular Preço de Venda [Com Frete Grátis] [3] Calcular Preço de Venda [Sem Frete Grátis] [9] Opções [0] Sair""") def baixoPreço(p): if p < 0.5: return 47.90 elif 0.5 <= p < 1: return 52.90 elif 1 <= p < 2: return 61.90 elif 2 <= p < 5: return 75.90 elif 5 <= p < 9: return 97.90 elif 9 <= p < 13: return 140.90 elif 13 <= p < 17: return 187.90 elif 17 <= p < 23: return 209.90 elif 23 <= p < 29: return 219.90 else: return 229.90 def altoPreco(p): if p < 0.5: return 35.93 elif 0.5 <= p < 1: return 39.68 elif 1 <= p < 2: return 46.43 elif 2 <= p < 5: return 56.93 elif 5 <= p < 9: return 73.43 elif 9 <= p < 13: return 105.68 elif 13 <= p < 17: return 140.93 elif 17 <= p < 23: return 157.43 elif 23 <= p < 29: return 164.93 else: return 172.43 def number(msg): while True: num = input(msg) try: num = float(num.replace(",", ".")) return num except: print(f"\n'{num}' não é um valor reconhecido. Tente novamente.\n") class Options: embalagem = 3 adicionalML = 5 taxaML = 16.5 / 100 imposto = 15 / 100 lucro = 20 / 100 multInicial = 1.01 def show(self): header("OPÇÕES") print(f"""- Todos - Multiplicador Inicial Embalagem Imposto Lucro Mínimo - Mercado Livre - Adicional ML (Aplicado caso o preço de venda for menos que R$ 99,00) Taxa ML\n""") def showAtivo(self): os.system('cls') header("OPÇÕES") print(f"""- Todos - Multiplicador Inicial (X) [Não pode ser desativado] Embalagem = (X) Imposto = (X) Lucro Mínimo = (X) - Mercado Livre - Adicional ML = (X) Taxa ML = (X)""") print("\nWIP") line() input("Pressione ENTER para continuar.") os.system('cls') def showChange(self): header("OPÇÕES") emb = f"{self.embalagem:.2f}" aML = f"{self.adicionalML:.2f}" print(f"""- Todos - [1] Multiplicador Inicial = {str(self.multInicial).replace(".", ",")}x [2] Embalagem = R$ {emb.replace(".", ",")} [3] Imposto = {str(self.imposto * 100).replace(".", ",")}% [4] Lucro Mínimo = {str(self.lucro * 100).replace(".", ",")}% - Mercado Livre - [5] Adicional ML = R$ {aML.replace(".", ",")} [6] Taxa ML = {str(self.taxaML * 100).replace(".", ",")}%\n""") def change(self): while True: os.system('cls') self.showChange() print("Qual opção deseja alterar?\n'0' (zero) para voltar.\n") escolha = number("> ") if escolha == 0: os.system('cls') break elif escolha == 1: self.multInicial = number("\nValor inicial do multiplicador\n> ") elif escolha == 2: self.embalagem = number("\nCusto da embalagem\n> R$ ") elif escolha == 3: self.imposto = number("\nPorcentagem de imposto\n> ") / 100 elif escolha == 4: self.lucro = number("\nPorcentagem de lucro\n> ") / 100 elif escolha == 5: self.adicionalML = number("\nCusto adicional do ML\n> ") elif escolha == 6: self.taxaML = number("\nPorcentagem da taxa adicional do ML\n> ") / 100 else: print("\nOpção Inválida.\n") continue class Produto: def __init__(self, op): self.opcao = op frete = 0 custo = 0 def calcFrete(self): print("""Para calcular o frete, precisamos do peso volumétrico do produto.\n\nInsira os valores pedidos:\n""") lar = number("Largura [cm]: ") alt = number("Altura [cm]: ") comp = number("Comprimento [cm]: ") pesoFis = number("\nPeso Físico [kg]: ") pesoVol = round(lar * alt * comp / 6000, 2) if pesoVol <= 5: peso = pesoFis else: peso = max([pesoVol, pesoFis]) frete = [baixoPreço(peso), altoPreco(peso)] self.lar, self.alt, self.comp, self.pesoFis, self.pesoVol, self.frete = lar, alt, comp, pesoFis, pesoVol, frete return frete def calcPreco(self, freteGratis = True): multLocal = self.opcao.multInicial if freteGratis: while True: if bool(self.frete): while True: os.system("cls") header("PREÇO COM FRETE") vF0 = f"{self.frete[0]:.2f}" vF1 = f"{self.frete[1]:.2f}" print(f"""Caso o preço de venda seja abaixo de R$ 99,00.\nFrete: R$ {vF0.replace('.', ',')}\n\nCaso o preço de venda seja acima de R$ 99,00.\nFrete: R$ {vF1.replace('.', ',')}""") line() resp = number(f"Dos valores de frete calculados, digite qual deles deseja usar.\n\n[1] R$ {vF0.replace('.', ',')}\n[2] R$ {vF1.replace('.', ',')}\n[3] Calcular um novo frete.\n\n> ") print() if resp == 1: frete = self.frete[0] elif resp == 2: frete = self.frete[1] elif resp == 3: os.system("cls") header("PREÇO COM FRETE") self.frete = self.calcFrete() continue else: print("\nOpção inválida.\n") continue break else: print("Para prosseguir é necessario calcular o frete do produto:") frete = self.calcFrete() self.frete = frete line() continue break custo = number("Digite o valor de custo do produto.\n> R$ ") self.custo = custo while True: vLucro = 0 valorFinal = self.custo + self.opcao.embalagem if freteGratis: valorFinal += frete vLucro -= frete valorFinal *= multLocal if valorFinal <= 99: valorFinal += self.opcao.adicionalML vLucro -= self.opcao.adicionalML vImposto = round(valorFinal * self.opcao.imposto, 2) vTaxaML = round(valorFinal * self.opcao.taxaML, 2) vLucro += valorFinal - vImposto - vTaxaML - self.opcao.embalagem - self.custo vLucro = round(vLucro, 2) multLocal = float(f"{Decimal(multLocal) + Decimal(0.01):.2f}") if vLucro >= self.custo * self.opcao.lucro: porLucro = round(vLucro / self.custo, 4) * 100 lNomes = ["Custo", "Lucro", "Imposto", "Taxa ML", "Embalagem"] lValores = [self.custo, vLucro, vImposto, vTaxaML, self.opcao.embalagem] if valorFinal <= 99: lNomes.append("Adicional ML") lValores.append(self.opcao.adicionalML) if freteGratis: lNomes.insert(2, "Frete") lValores.insert(2, frete) return valorFinal, porLucro, dict(zip(lNomes, lValores))
import xml.etree.ElementTree as ET from airline import Airline class AirlineParser(object): """ Utility for parsing airline information from an XML files. """ @staticmethod def parse_airlines(xml_file): """ Parses airline information from an XML file. Returns a list of airlines. """ tree = ET.XML(xml_file) airlines = [] for node in tree.getiterator('airlineName'): code = node.attrib.get("code") name = node.attrib.get("name") airlines.append(Airline(code, name)) return airlines
import xml.etree.ElementTree as ET from flightstatus import FlightStatus class FlightStatusParser(object): """ Utility for parsing messages from a given XML file. """ @staticmethod def parse_statuses(xml_file): """ Parses the status messages from a given XML file. Returns a list of the statuses. """ tree = ET.XML(xml_file) statuses = [] for node in tree.getiterator('flightStatus'): code = node.attrib.get("code") text = node.attrib.get("statusTextEn") statuses.append(FlightStatus(code, text)) return statuses
from math import sin, cos, radians, atan2, sqrt, asin class Position(object): def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude def compute_distance_to(self, p): # geometric mean from wikipeda earth_radius = 6371.0 # convert degrees to radians p1 = (radians(self.latitude), radians(self.longitude)) p2 = (radians(p.latitude), radians(p.longitude)) diff = (p1[0] - p2[0], p1[1] - p2[1]) d = 2 * asin(sqrt((sin(diff[0] / 2.0))**2 + cos(p1[0]) * cos(p2[0]) * (sin(diff[1] / 2.0))**2)) return earth_radius * d
""" Tipe data dictionary sekedar menghubungkan antara KEY dan Value KVP = Key Value Pair dictionary = kamus """ kamus_ind_eng = {'anak': 'son', 'istri': 'wife', 'ayah': 'father', 'ibu': 'mother'} print(kamus_ind_eng) print(kamus_ind_eng['ayah']) print(kamus_ind_eng['ibu']) print('\nData ini dikirimkan oleh server Gojek, untuk memberikan info driver disekitar pemakai aplikasi') data_dari_server_gojek = { 'tanggal': '2021-07-03', 'driver_list': [ {'nama': 'Eka', 'jarak': 10}, {'nama': 'Dwi', 'jarak': '30'}, {'[nama': 'Tri', 'jarak': '100'}, {'nama': 'Catur', 'jarak': '1000'}] } print(data_dari_server_gojek) print(f"\nDriver disekitar sini {data_dari_server_gojek['driver_list']}") print(f"Driver #1 {data_dari_server_gojek['driver_list'][0]}") print(f"Driver #4 {data_dari_server_gojek['driver_list'][3]}") print (f"Driver terdekat berjarak {data_dari_server_gojek['driver_list'][0]['jarak']} meter")
'''Todo e-mail é formado por duas partes: o login do usuário e o domínio do provedor. Veja o exemplo abaixo: E-mail: antonio.silva@ifpb.edu.br Login: antonio.silva Domínio: ifpb.edu.br Escreva um programa que leia o login de um usuário e o domínio do seu provedor e mostre o seu e-mail completo.''' login = input('Informe seu login: ') dominio = input('Informe o domínio: ') print(login, dominio, sep='@')
'''5. Escreva um programa para determinar as raízes de uma equação de segundo grau, dados os seus coeficientes. Fórmulas: Obs: se Δ for negativo, não existem as raízes da equação. Dica: use a função sqrt do módulo math.''' from math import sqrt print('Resolução de uma equação de segundo grau!') a = int(input('Informe o valor de a: ')) b = int(input('Informe o valor de b: ')) c = float(input('Informe o valor de c: ')) delta = b ** 2 - 4 * a * c x1 = (- b + sqrt(delta)) / (2 * a) x2 = (- b + sqrt(delta)) / (2 * a) print('Valor de delta:',delta) if delta < 0: print('As raízes da equação não existem pois o delta é negativo') else: print(f'As raízes da equação são {x1:.1f} e {x2:.1f}')
'''Escreva um programa que leia o peso (kg) e a altura (m) de uma pessoa, determine e mostre o seu grau de obesidade, de acordo com a tabela seguinte. O grau de obesidade é determinado pelo índice de massa corpórea, cujo cálculo é realizado dividindo-se o peso da pessoa pelo quadrado da sua altura.''' altura = float(input('Entre com sua altura: ')) peso = float(input('Entre com seu peso: ')) imc = peso / altura ** 2 print(f'Seu índice de massa corporal é {imc:.2f}') if imc < 26: print('Seu IMC está normal.') elif imc >= 26 and imc < 30: print('Você está obeso.') elif imc >= 30: print('Você está com obesidade mórbida.')
'''Faça um programa que leia um número inteiro N, calcule e mostre o maior quadrado perfeito menor ou igual a N. Por exemplo, se N for igual a 38, o resultado é 36.''' import math maior = 0 n = int(input('Informe um número: ')) for i in range(1, n + 1): raiz = math.sqrt(i) if raiz == int(raiz) and i > maior: maior = i print('Maior quadrado perfeito:', maior)
'''Faça um programa que, para um grupo de N pessoas (obs: N será lido): • Leia o sexo (M ou F) de cada pessoa; • Calcule e escreva o percentual de homens; • Calcule e escreva o percentual de mulheres.''' cont_mulher = 0 cont_homem = 0 n = int(input('Informe a quantidade de pessoas que participarão do teste: ')) for i in range(n): sexo = input('Informe o sexo: (M ou F) ').upper() if sexo == 'F': cont_mulher += 1 else: cont_homem += 1 porcent_mulher = (cont_mulher / n) * 100 porcent_homem = 100 - porcent_mulher print(f'{n} pessoas foram cadastradas.') print(f'{porcent_mulher:.0f}% são mulheres e {porcent_homem:.0f}% são homens.')
'''3. Faça um programa que leia vários números, determine e mostre o maior e o menor deles. Obs: a leitura do número 0 (zero) encerra o programa.''' flag = 0 print('A entrada do número 0 (zero) encerrará o programa.') num = int(input()) maior = num menor = num while num != flag: if num > maior: maior = num if num < menor: menor = num num = int(input()) print('O maior é:', maior) print('O menor é:', menor)
'''Faça um programa para ler o nome e o salário bruto dos 100 funcionários de uma determinada empresa. Para cada funcionário lido, o programa deverá emitir o respectivo contracheque, que deverá conter: O nome do funcionário; O valor do salário bruto; O valor do desconto do INSS (12% do Salário Bruto) O valor do salário líquido (Salário Bruto - Desconto INSS) Ao final, o programa deverá mostrar: A soma total dos salários brutos; A soma total dos descontos do INSS; A soma total dos salários líquidos.''' total_bruto = 0 total_desconto = 0 total_liquido = 0 for i in range(3): nome = input('Nome: ') salario = float(input('Salário: R$')) desconto = (salario * (12 /100)) salario_liquido = salario - desconto print(f'Nome: {nome}') print(f'Salário bruto: R${salario:.2f}') print(f'Desconto do INSS: R${desconto:.2f}') print(f'Salário líquido: R${salario_liquido:.2f}') print('--' * 20) if salario > 0: total_bruto += salario total_desconto += desconto total_liquido += salario_liquido print(f'Soma total dos salários brutos: R${total_bruto:.2f}') print(f'Soma total dos descontos do INSS: R${total_desconto:.2f}') print(f'Soma total dos salários líquidos: R${total_liquido:.2f}')
'''5. Escreva um programa para ler o nome e o sobrenome de uma pessoa e escrevê- los na seguinte forma: sobrenome seguido por uma vírgula e pelo nome''' nome = input('Nome: ') sobrenome = input('Sobrenome: ') print(f'{sobrenome}, {nome}')
import random x = input("What is your name? ") print("Hello, " + x + "!") y = str(random.randint(-10000, 10000)) print("Your lucky number is: " + y) avg = 0 for x in range(1000): found = 0 for i in range(10000): if random.randint(-100, 100) == 0: found = found + 1 print("Percentage " + str(x) + ": " + str(found / 10000 * 100) + "%!") avg = avg + found / 10000 * 100 avg = avg / 1000 print("Percentage Average: " + str(avg))
# ----------------------------------------------------------------------------- # Calculator with English words and numbers. # Oscar Rubio Pons, oscar.rubio.pons@gmail.com # 16 Sept 2013, Hamburg, Germany # ----------------------------------------------------------------------------- import sys sys.path.insert(0,"../..") if sys.version_info[0] >= 3: raw_input = input #Import words to numbers import w2n # Make a calculator function def make_calculator(): import ply.lex as lex import ply.yacc as yacc # ------- Internal calculator state variables = { } # Dictionary of stored variables # ------- Calculator tokenizing rules tokens = ( 'NAME', 'NUMBER','PLUS', 'MINUS', 'DIVIDE', 'TIMES', 'one', 'two', 'three', ) literals = ['=','+','-','*','/', '(',')'] t_ignore = " \t" t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' t_one = 'one' t_two = 'two' t_three = 'three' #expression # def t_NUMBER(t): r'\d+' t.value = int(t.value) return t def t_newline(t): r'\n+' t.lexer.lineno += t.value.count("\n") def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1) # Build the lexer lexer = lex.lex() # ------- Calculator parsing rules precedence = ( ('left','+','-'), ('left','*','/'), ('right','UMINUS'), ) # Alternative to the expresion can be +,- * and / def p_expression_binop(p): '''expression : NUMBER '+' NUMBER | NUMBER PLUS NUMBER | NUMBER '-' NUMBER | NUMBER '*' NUMBER | NUMBER '/' NUMBER | TXTNUMBER PLUS TXTNUMBER | TXTNUMBER DIVIDE TXTNUMBER | TXTNUMBER '/' TXTNUMBER''' if p[2] == '+' : p[0] = p[1] + p[3] elif p[2] == PLUS: p[0] = p[1] + p[3] elif p[2] == PLUS_text: p[0] = p[1] + p[3] elif p[2] == '-': p[0] = p[1] - p[3] elif p[2] == '*': p[0] = p[1] * p[3] elif p[2] == '/': p[0] = p[1] / p[3] def p_binary_operators(p): '''expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression''' if p[2] == '+': p[0] = p[1] + p[3] elif p[2] == '-': p[0] = p[1] - p[3] elif p[2] == '*': p[0] = p[1] * p[3] elif p[2] == '/': p[0] = p[1] / p[3] def p_expression_uminus(p): "expression : '-' expression %prec UMINUS" p[0] = -p[2] def p_expression_group(p): "expression : '(' expression ')'" p[0] = p[2] def p_expression_number(p): '''expression : NUMBER | TXTNUMBER ''' p[0] = p[1] def p_expression_name(p): "expression : NAME" try: p[0] = variables[p[1]] except LookupError: print("Undefined name '%s'" % p[1]) p[0] = 0 def p_error(p): if p: print("ERROR at '%s'" % p.value) else: print("ERROR at EOF") def p_txtnumber(p): '''TXTNUMBER : one | two | three ''' p[0] = w2n.w2n(p[1]) #Check the complete implementation for Words to numbers #http://stackoverflow.com/questions/493174/is-there-a-way-to-convert-number-words-to-integers-python for a complete implementation def w2n(s): if s == 'one': return 1 elif s == 'two': return 2 elif s == 'three': return 3 assert(False) # Build the parser parser = yacc.yacc() # ------- Input function def input(text): result = parser.parse(text,lexer=lexer) return result return input # Make a calculator object and use it calc = make_calculator() while True: try: s = raw_input(" Enter your input, Calc: > ") except EOFError: break r = calc(s) if r: print(r)
from structure import Structure class SandCastle (Structure): # inheritance '''Defines a sand castle.''' __num_castles = 0 # private class field purpose = 'fun' # public class field # Constructor: def __init__(self, name, size): self.name = name self.size = size SandCastle.__num_castles += 1 # Destructor: def __del__(self): class_name = self.__class__.__name__ SandCastle.__num_castles -= 1 print class_name, self.name, "destroyed" # Serialize this object to evaluatable code: def __repr__(self): return # Serialize this object to printable string: def __str__(self): return "Castle. Name: %s, size: %s." % (self.name, str(self.size)) # Custom comparator: def __cmp__(self, other): if self.size < other.size: return -1 elif self.size > other.size: return 1 else: return 0 # Overload the '+' operator for sand castles: def __add__(self, other): # also __sub__, __mul__, __div__, etc. # for a list see https://docs.python.org/2/library/operator.html return # Override the parent method: def get_greeting(self): return "Welcome to castle %s!\nWe have %d more castles!" % (self.name, SandCastle.__num_castles - 1) @staticmethod # we need a decorator in order to make a static method def static(): return "I am a static method." c = SandCastle('SandyBurg', 'small') print c.get_greeting() print SandCastle.static() del c.size # WE CAN DELETE ATTRIBUTES! WTF!??!?! print 'age:', getattr(c, 'age', 0) # default to 0 if 'age' does not exist setattr(c, 'age', 2) print 'has attribute?', hasattr(c, 'age') delattr(c, 'age') # another way to delete an attribute print 'Is subclass?', issubclass(SandCastle, Structure) print 'Is instance?', isinstance(c, SandCastle) del c # destroy the object
def is_palindrome(n): return str(n) == str(n)[::-1] result = 0 for i in range(1000000): if is_palindrome(i) and is_palindrome("{:b}".format(i)): result += i print(result)
#Challenge 3 x = int(input("Please enter an integer: ")) y = int(input("Please enter a larger integer: ")) def sumOddNumbersInRange(x, y): """A function to calculate the sum of odd numbers from x (including x) to y (excluding y) return the result e.g. if x = 4 and y = 9 then the result is 5 + 7 = 12 """ assert y > x # Check the input arguments to the function is okay z = 0 for i in range(x, y): if i % 2 == 1: z+=i return z print("The sum of odd integers from: ", x, " up to: ", y, " is: ", sumOddNumbersInRange(x, y))
""" Zihao Li Class: CS 521 - Fall 2 Date: Wed Dec 11, 2019 Final Project Description: Recognize face method """ import face_recognition from PIL import Image, ImageDraw def recognize_face(filename): """This is a method to recognize a face in a group photo.""" # Load the jpg file into a numpy array image = face_recognition.load_image_file("pictures/group.jpg") unknown_image = face_recognition.load_image_file(filename) # Find all faces' encodings in images face_locations = face_recognition.face_locations(image) unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0] # Initialization ori_image = Image.fromarray(image) pil_image = Image.fromarray(image) d = ImageDraw.Draw(pil_image) faces_number = 0 # Compare the target face with all the faces in the group photo for i in range(len(face_locations)): top, right, bottom, left = face_locations[i] face_image = image[top:bottom, left:right] face_encoding = face_recognition.face_encodings(face_image) result = face_recognition.compare_faces(face_encoding, unknown_face_encoding, 0.35) if True in result: faces_number += 1 # Draw rectangles on the face d.rectangle(((left-10, top-10), (right+10, bottom+10)), outline=(255, 0, 0), width=10) d.rectangle(((left-20, top-20), (right+20, bottom+20)), outline=(0, 0, 255), width=10) print("A face is located at pixel location Top: {}, Left: {}, " "Bottom: {}, Right: {}".format(top, left, bottom, right)) print("Recognizing {} face(s) in this group photo.".format(faces_number)) # Display the results ori_image.show() pil_image.show() if __name__ == '__main__': recognize_face("pictures/Horus.jpg") exit()
import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1+np.exp(-x)) x = np.arange(-5, 5, 0.1) y = sigmoid(x) print(x.shape, y.shape) plt.plot(x, y) plt.grid() plt.show() # activation 은 가중치 값을 한정시킴
#1. 데이터 import numpy as np x=np.array([range(1, 101), range(311, 411), range(100)]) y=np.array([range(101, 201), range(711, 811),range(100)]) print(x.shape) #(3,100) #행과 열을 바꾸는 함수 (3,100)--->(100,3) x = np.transpose(x) y = np.transpose(y) print(x.shape) #(100,3) print(y.shape) #x=np.swapaxes(x,0,1) #x=np.arange(300).reshape(100,3) # print("x = ", x) # print("y = ", y) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) #train (80,3) test(20,3) #x_val, x_test, y_val, y_test = train_test_split(x_test, y_test, random_state=66, test_size=0.66) #x, y, random_state=99, shufle=True, test_size=0.4 #x_test, y_test, random_state=99, test_size=0.5 # x_train = x[:60] #0~59 # x_val = x[60:80] #60~79 # x_test = x[80:] #80~66 # y_train = x[:60] # y_val = x[60:80] # y_test = x[80:] # print("x_train = \n", x_train) # print("y_train = \n", y_train) # print("x_test = \n", x_test) # print("y_test = \n", y_test) # print("x_val = ", x_val) # print("y_val = ", y_val)''' # 2. 모델구성 from keras.models import Sequential from keras.layers import Dense # Sequential 함수를 model 로 하겠다. model = Sequential() model.add(Dense(5, input_dim=3)) #1~100의 한 덩어리? model.add(Dense(10)) model.add(Dense(10)) model.add(Dense(10)) model.add(Dense(10)) model.add(Dense(3)) # 3. 훈련 model.compile(loss='mse', optimizer='adam', metrics=['mse']) model.fit(x_train, y_train, epochs=10, batch_size=1, validation_split=0.25) # x_train : (60,3) x_val :(20,3), x_test :(20,3) #훈련용 데이터로 훈련 , # validation_data = (x_test, y_test), # 4. 평가, 예측 loss, mse = model.evaluate(x_test, y_test, batch_size=1) #훈련용 데이터와 평가용 데이터를 분리해야함 print("loss : ", loss) print("mse = ", mse) y_predict = model.predict(x_test) print("y_predict : \n", y_predict) from sklearn.metrics import mean_squared_error def RMSE(y_test, y_predict): return np.sqrt(mean_squared_error(y_test, y_predict)) print("RMSE : ", RMSE(y_test, y_predict)) # R2 구하기 from sklearn.metrics import r2_score r2 = r2_score(y_test, y_predict) print("r2 : ", r2) #회귀모형'''
import matplotlib.pyplot as plt import numpy as np # 사진 데이터 읽어들이기 photos = np.load('myproject/photos.npz') x = photos['x'] y = photos['y'] # 시작 인덱스 --( 1) idx = 0 #pyplot로 출력하기 plt.figure(figsize=(10, 10)) for i in range(9): plt.subplot(3, 3, i+1) plt.title(y[i+idx]) plt.imshow(x[i+idx]) plt.show()
import pandas as pd titanic_df = pd.read_csv(r'C:\Users\bitcamp\Desktop\titanic\train.csv') titanic_df['Child_Adult']=titanic_df['Age'].apply(lambda x : 'Child' if x <= 15 else 'Adult') print(titanic_df[['Age', 'Child_Adult']].head(8)) titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : 'Child' if x<=15 else('Adult' if x <= 60 else 'Elderly')) print(titanic_df['Age_cat'].value_counts()) # 나이에 따라 세분화된 분류를 수행하는 함수 생성. def get_category(age): cat='' if age<=5: cat='Baby' elif age <= 12: cat = 'Child' elif age <= 18: cat = 'Teenager' elif age <= 25: cat = 'Student' elif age <= 35: cat = 'Young Adult' elif age <= 60: cat = 'Adult' else : cat = 'Elderly' return cat # get_category(x) 입력값으로 'Age' 칼럼 값을 받아서 해당하는 cat 반환 titanic_df['Age_cat']= titanic_df['Age'].apply(lambda x : get_category(x)) print(titanic_df[['Age', 'Age_cat']].head())
# 1. 데이터 import numpy as np x_train = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y1_train = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y2_train = np.array([1, 0, 1, 0, 1, 0, 1, 0, 1, 0]) # 2. 모델 구성 from keras.models import Sequential, Model from keras.layers import Dense, Input input1 = Input(shape=(1,)) x1 = Dense(100)(input1) x1 = Dense(100)(x1) x1 = Dense(100)(x1) x2 = Dense(50)(x1) output1 = Dense(1)(x2) # linear 들어가 있음 x3 = Dense(70)(x1) x3 = Dense(70)(x3) output2 = Dense(1, activation='sigmoid')(x3) model = Model(inputs = input1, outputs=[output1, output2]) model.summary() # 3. 컴파일, 훈련 model.compile(loss=['mse', 'binary_crossentropy'], optimizer='adam', metrics=['mse', 'acc']) model.fit(x_train, [y1_train, y2_train], epochs=100, batch_size=1) # 평가 예측 loss = model.evaluate(x_train, [y1_train, y2_train]) print("loss : ", loss) x1_pred = np.array([11, 12, 13, 14]) y_pred = model.predict(x1_pred) print(y_pred)
#1. R2를 0,5 이하 2. 레이어 5개이상 인풋아웃풋포함 3. 노드의 개수 10개 이상 4. EPOCHS 30개 이상 5. BATCHI_SIZE = 8 이하 #1. 데이터 import numpy as np x=np.array([range(1, 101), range(311, 411), range(100)]) y=np.array(range(711, 811)) print("x.shape : ", x.shape) print("y.shape : ", y.shape) #행과 열을 바꾸는 함수 x = np.transpose(x) y = np.transpose(y) #x=np.swapaxes(x,0,1) #x=np.arange(300).reshape(100,3) print("x : \n", x) print("y : \n ", y) print("x.shape : ", x.shape) print("y.shape : ", y.shape) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y,shuffle=False, test_size=0.855) # train x = (80,3) test (20,3) # 2. 모델구성 from keras.models import Sequential from keras.layers import Dense # Sequential 함수를 model 로 하겠다. model = Sequential() model.add(Dense(100, input_dim=3)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(100)) model.add(Dense(1)) # 3. 훈련 model.compile(loss='mse', optimizer='adam', metrics=['mse']) model.fit(x_train, y_train, epochs=12, batch_size=8, validation_split=0.01, verbose=3) # train (60.3), val(20.3),test(20,3) # 4. 평가, 예측 loss, mse = model.evaluate(x_test, y_test, batch_size=8) print("loss : ", loss) print("mse = ", mse) y_predict = model.predict(x_test) print("y_predict : \n", y_predict) from sklearn.metrics import mean_squared_error def RMSE(y_test, y_predict): return np.sqrt(mean_squared_error(y_test, y_predict)) print("RMSE : ", RMSE(y_test, y_predict)) # R2 구하기 from sklearn.metrics import r2_score r2 = r2_score(y_test, y_predict) print("r2 : ", r2)
a = {'name' : 'yun', 'phone':'010', 'birth' : '0511'} '''a = 0 for(i=1, i=100, i++){ a= i + a } print(a) for i in 100: a i 결과a 0 1 1 1 2 3 3 3 6 6 4 10 213 100''' for i in a.keys(): print(i) a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in a: i = i*i print(i) # print('melong') melong 이 10번출력됨 #print('melong') melong 이 1번만 출력됨 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in a: print(i) ## while 문 ''' while 조건문 : #참일 동안 계속 돈다 수행할 문장 ''' ### if 문 if 1: print('True') else: print('False') if 3: print('True') else: print('False') if 0: print('True') else: print('False') if -1: print('True') else: print('False') '''비교 연산자 >, <, ==, !=, >=, <= ''' a = 1 if a == 1: print('출력잘되') money = 10000 if money >= 30000: print('한우먹자') else: print('라면먹자') ###조건 연산자 #and, or, not money = 20000 card = 1 if money >= 30000 or card == 1: print("한우먹자") else: print('라면먹자') ################################################## # break, continue print("=============================") jumsu = [90, 25, 67, 45, 80] number = 0 for i in jumsu: if i >= 60: print("경] 합격 [축") number = number+1 print("합격인원 : ", number, "명") print("=============================") jumsu = [90, 25, 67, 45, 80] number = 0 for i in jumsu: if i < 30: break if i >= 60: print("경] 합격 [축") number = number+1 print("합격인원 : ", number, "명") print("=============================") jumsu = [90, 25, 67, 45, 80] number = 0 for i in jumsu: if i < 60: continue #25면 그 하단부분 실행하지 않고 다시 for 문으로 돌아감 if i >= 60: print("경] 합격 [축") number = number+1 print("합격인원 : ", number, "명")
import numpy as np from Layer import Layer from losses import * class NeuralNetwork: """Multi layer network. Parameters ---------- loss: string ("mean_squared_error") Specifies loss to train the function on Attributes ---------- layers: list list contaning all layers within network. """ def __init__(self, loss, momentum): #Initialize list of layers to empty list aritificial_layer = Layer(0,0, "relu") self.layers = [aritificial_layer] self.loss_name = loss self.loss = LOSSES[loss] self.b_loss = B_LOSSES[loss] self.momentum = momentum def add(self, layer): """ Function used to add layer to network: Parameters ---------- layer: Layer, layer which will be added to network. Returns ------- None """ assert isinstance(layer, Layer) self.layers.append(layer) def single_forward_pass(self, X): for layer in self.layers[1:]: X = layer.forward_pass(X) return X def forward_pass(self, X): """ Forward pass of X through layers """ y = np.zeros((X.shape[0], self.layers[-1].units)) for i in range(X.shape[0]): X_ = X[i, :].reshape(-1,1) y[i,:] = self.single_forward_pass(X_).reshape(1, self.layers[-1].units) return y def calculate_loss(self, X, y): """ loss of the function """ return self.loss(self.forward_pass(X), y) def calculate_b_loss(self, X, y): return self.b_loss(self.forward_pass(X), y) def backward_pass(self, X, y): "first computeted manualy, next computed in the loop" for i in range(X.shape[0]): X_ = X[i, :].reshape(-1,1) y_ = y[i, :] if y_.shape[0] > 1: y_ = y_.reshape(-1,1) self.single_forward_pass(X_) self.layers[0].forward = X_ last_layer = self.layers[-1] if self.loss_name == "mse": last_layer.semi_grad = ((self.layers[-1].forward - y_) * self.layers[-1].backward_activation_function(self.layers[-1].Z)).sum(axis=1, keepdims=True) if self.loss_name == "cross_entropy": last_layer.semi_grad = (((1-y_)/(1-self.layers[-1].forward) - y_/self.layers[-1].forward) * self.layers[-1].backward_activation_function(self.layers[-1].Z)).sum(axis=1, keepdims=True) last_layer.DB += last_layer.semi_grad / X.shape[0] last_layer.DW += np.dot(last_layer.semi_grad, self.layers[-2].forward.reshape(1, -1)) / X.shape[0] semi_grad = last_layer.semi_grad for i in range(2, len(self.layers)): deriv = self.layers[-i].backward_activation_function(self.layers[-i].Z) semi_grad = np.dot(self.layers[-i+1].W.reshape(self.layers[-i+1].W.shape[1], self.layers[-i+1].W.shape[0]), semi_grad) * deriv self.layers[-i].DB += (self.layers[-i].last_grad_B * self.momentum + (1-self.momentum) * semi_grad) / X.shape[0] self.layers[-i].DW += (self.layers[-i].last_grad_W * self.momentum + (1-self.momentum) * np.dot(semi_grad, self.layers[-i-1].forward.T)) / X.shape[0] def zero_gradients(self): for layer in self.layers: layer.DW = np.zeros_like(layer.DW) layer.DB = np.zeros_like(layer.DB) def train(self, X, y, X_test=None, y_test=None, epochs = 1, learning_rate = 0.01, momentum = 0.99, verbose=True): """ Method to train the network Momentum is not implemented yet. """ train_loss = [0] * epochs test_loss = [0] * epochs grad_norm = [0] * epochs for i in range(epochs): self.zero_gradients() self.backward_pass(X, y) for layer in self.layers: layer.W -= layer.DW * learning_rate grad_norm[i] += np.linalg.norm(layer.DW, ord="fro") layer.last_grad_W = layer.DW layer.B -= layer.DB * learning_rate layer.last_grad_B = layer.DB if verbose: print("\r%d" % i, end="") train_loss[i] = self.loss(y, self.forward_pass(X)).sum() / X.shape[0] if X_test is not None and y_test is not None: test_loss[i] =self.loss(y_test, self.forward_pass(X_test)).sum() / X_test.shape[0] return train_loss, test_loss, grad_norm
#number = input("number : ") def iterate(n): i=0 n = int(n) while i <= n: print(i) i += 1 def fibonnaci(n): list = [0] i = 0 n = int(n) while i < n-1 : if list[i] == 0: list.append(1) else: list.append(list[i]+list[i-1]) i += 1 return list # print(fibonnaci(number)) def isValueInList(value, list): value = int(value) #str to int return value in list # value = ie, gunput("Devinez une valeur dans le tableau : ") # # guesslist = [1,2,3] # # if isValueInList(valuesslist): # print("la valeur est dans le tableau" ) # else: # print("Ah bah non dommage !") def isIndexOf(v, list): index=0 listindex = [] for i in list : if i == v: listindex.append(index) index += 1 return listindex # print(isIndexOf(int(value), guesslist)) def isPalindrome(str) : str_reverse = "" for i in range(len(str)-1, -1, -1): str_reverse += str[i] return str_reverse == str if isPalindrome("kayak"): print("c'est un palindrome") else: print("ce n'est pas un palindrome")
#coding: utf-8 from Tkinter import *#Importation de l'outil ,comme pour Turtle from random import * from time import sleep fen1 = Tk() #Creation de la fenetre principale fen1.attributes('-fullscreen', 1)#Fenetre en plein écran #---------------Definitions---------------# #Initialisation def initMainTableau() : global T T = [] L = [] for i in range(40) :#initialisation du tableau à 2 dimensions T.append(L) for j in range(40): if i == 0 or i == 40-1 or j == 0 or j == 40-1: L.append(0) #on remplit les bords de vides else : L.append(randint(0,1)) #On place aléatoirement des arbres ou du vide L = [] return T def initTabCendre(): global U U = [] E = [] for i in range(40): U.append(E) for j in range (40): E.append(3) E = [] def feu(): global T x=randint(0,40-1) y=randint(0,40-1) while T[y][x] != 2: #On cherche un arbre pour l'enflammer if T[y][x] == 1: T[y][x]=2 else: #Si ce n'est pas un arbre on cherche une autre case x=randint(0,40-1) y=randint(0,40-1) return T #Propagation def temps(): global T for i in range(40): for j in range (40): if T[i][j] == 2: #On cherche les cases "feu" if T[i][j+1]==1: T[i][j+1]=4 #on modifie les cases adjacentes if T[i][j-1]==1: T[i][j-1]=4 if T[i+1][j]==1: T[i+1][j]=4 if T[i-1][j]==1: T[i-1][j]=4 for i in range(40): for j in range (40): if T[i][j] == 4: T[i][j] = 2 return T def TimCendre(): for i in range(40): for j in range (40): if T[i][j] == 2: U[i][j] = U[i][j] - 1 if U[i][j] == 0 : T[i][j] = 3 return U def avancement() :#Boucle permettant la propagation automatique du feu pions() TimCendre() temps() #Interface graphique def quadrillage() : xl=0 for i in range(40):#Boucle de creation des traits de lignes et colonnes can.create_line(xl, 0, xl, 800, fill ='black') can.create_line(0, xl, 800, xl, fill ='black') xl=xl+20 def pions() : global T x=0 #Initialisation du coordonées de départ y=0 n=0 c=0 for i in range(40): #Double boucles afin de generer les pions de depart dans une grille for j in range(40): if T[i][j] == 0 : can.create_rectangle(x,y,x+20,y+20,fill='white') #Canvas générant les pions if T[i][j] == 1 : can.create_rectangle(x,y,x+20,y+20,fill='green') #Canvas générant les pions if T[i][j] == 2 : can.create_rectangle(x,y,x+20,y+20,fill='red') #Canvas générant les pions n=n+1#Détection du nombre de cases en feu if T[i][j] == 3 : can.create_rectangle(x,y,x+20,y+20,fill='grey') #Canvas générant les pions c=c+1#Détection du nombre de cases en cendre if T[i][j] == 4 : can.create_rectangle(x,y,x+20,y+20,fill='red') #Canvas générant les pions n=n+1 x=x+20 x=0 y=y+20 if n==0 and c>=1:#Si il n'y a plus de feu mais présence de cendre win()#Fonction de fin de partie else : fen1.after(500,avancement)#Sinon on continue la propagation def win() : win = Tk() winm = Message(win, width=200, justify =CENTER,font ="Century",text ='La simulation est terminée').pack()#Effacement de la fenêtre après 2 secondes fen1.after(3000,Recommencer) #La partie recommence #Lancements def boutonla():#Bouton de lancement du jeu global bouton bouton = Button(fen1, text='Lancer la Partie', command = lancement) bouton.pack() def lancement() :#On lance la boucle ,on supprime le bouton et on initialise les tableaux can.delete('all')#On supprime ce qu'il y a sur le canevas quadrillage() initMainTableau() initTabCendre() feu() avancement() bouton.destroy() def Recommencer() : #On réinitialise le programme boutonla() #Menus def Apropos(): info = Tk()#New fenetre w = Message(info,width=200, justify =CENTER,font ="Century",text ='Projet ISN 2016 Simulation Incendie , ROBIN Tangui , DUMAS Clément, Sous Python 2.7 avec Tkinter').pack() #Creation d'un message de taille 200, centre #---------------Menu deroulant---------------# mainmenu = Menu(fen1)#Creation d'un menu menuJeu = Menu(mainmenu) #Menu deroulant menuJeu.add_command(label = "A propos" , command = Apropos) menuJeu.add_separator()#Ligne separatrice menuJeu.add_command(label = "Quitter" , command = fen1.destroy) mainmenu.add_cascade(label = "Jeu", menu = menuJeu)#Menu cascade Button(fen1, text ='Quitter', command = fen1.destroy).pack(side=BOTTOM, padx=5, pady=5) fen1.config(menu = mainmenu) #---------------Creation du Jeu---------------# n=0 can = Canvas(fen1, width =800, height =800, bg ='ivory')#Creation d'un caneva dans la fenetre can.pack(side =TOP, padx =5, pady =5)#Affichage du caneva dans la fenetre boutonla()#Bouton de lancement fen1.mainloop()#Boucle de la fenetre
from itertools import permutations def create_matchups(teams): return list(permutations(teams, 2)) class Team: def __init__(self, name, abbreviation): self.name = name self.abbreviation = abbreviation.upper() # stores points gained for win or draw self.points = 0 # records goal difference self.goal_diff = 0 # stores the results of a team's latest game self.single_game_points_holder = 0 mun = Team("Manchester United", "MUN") che = Team("Chelsea", "CHE") tot = Team("Tottenham Hotspurs", "TOT") liv = Team("Liverpool", "LIV") ars = Team("Arsenal", "ARS") mci = Team("Manchester City", "MCI") eve = Team("Everton", "EVE") lci = Team("Leicester", "LCI") whu = Team("West Ham United", "WHU") all_teams = [mun, che, tot, liv, ars, mci, eve, lci, whu]