text
stringlengths
37
1.41M
""" 1052.爱生气的老板 今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。 在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。 书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 X 分钟不生气,但却只能使用一次。 请你返回这一天营业下来,最多有多少客户能够感到满意的数量。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/grumpy-bookstore-owner 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ def maxSatisfied(customers, grumpy, X): """ :type customers: List[int] :type grumpy: List[int] :type X: int :rtype: int """ n = len(customers) tmp = 0 for i in range(n): if grumpy[i] == 0: tmp += customers[i] i = 0 profit = 0 for j in range(i + X): if grumpy[j] == 1: profit += customers[j] i += 1 maxnum = profit while i + X - 1 < n: if grumpy[i + X - 1] == 1: profit += customers[i + X - 1] if grumpy[i-1] == 1: profit -= customers[i-1] maxnum = max(maxnum, profit) i += 1 return tmp + maxnum customers=[1,0,1,2,1,1,7,5] grumpy =[0,1,0,1,0,1,0,1] X= 3 print(maxSatisfied(customers,grumpy,X))
""" 95.不同的二叉搜索树II 给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树 """ class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def generateTrees(n): if n == 0: return def solve(l, r): res =[] if l > r: res.append(None) return res for i in range(l, r + 1): left = solve(l, i - 1) right = solve(i + 1, r) for lr in left: for rr in right: cur = TreeNode(i) cur.left = lr cur.right = rr res.append(cur) return res return solve(1,n)
import unittest from attribute_injection import MinimalClass class TestMinimalClass(unittest.TestCase): __uut = None def setUp(self): self.__uut = MinimalClass() def test_get_the_list_fails_when_it_doesnt_exist(self): try: theList = self.__uut.theList except Exception as ex: self.assertTrue(True) else: self.assertFalse(True) @unittest.expectedFailure def test_get_the_list_fails_when_it_doesnt_exist_at_expectedFailure(self): theList = self.__uut.theList def test_get_the_list(self): # inject the list attribute into __uut self.__uut.__dict__.__setitem__("theList", list()) theList = self.__uut.theList self.assertIsNotNone(theList) def test_get_the_list_checking_content(self): # inject the list into __uut self.__uut.__dict__.__setitem__("theList", list('listItem')) theList = self.__uut.theList item = theList[0] self.assertEqual('l',item) def test_alternate_creation_of_attribute(self): self.__uut.theList = list('ListItems') aList = self.__uut.theList self.assertIsNotNone(aList) self.assertEqual('I', aList[4])
from Book import Book from datetime import datetime def create_book(year): if year == 1: return Book("Harry Potter e la pietra filosofale","J. K. Rowling","Salani Editore",1997, 294, 8877827025) elif year == 2: return Book("Harry Potter e la camera dei segreti","J. K. Rowling","Salani Editore",1998, 289, 8877827033) elif year == 3: return Book("Harry Potter e il prigioniero di Azkaban","J. K. Rowling","Salani Editore",1999, 341, 8877828528) elif year == 4: return Book("Harry Potter e il calice di fuoco","J. K. Rowling","Salani Editore",2000, 571, 8884510490) elif year == 5: return Book("Harry Potter e l'ordine della fenice","J. K. Rowling","Salani Editore",2003, 738, 8884513448) elif year == 6: return Book("Harry Potter e il principe mezzosangue","J. K. Rowling","Salani Editore",2005, 486, 8884516374) elif year == 7: return Book("Harry Potter e i doni della morte","J. K. Rowling","Salani Editore",2007, 557, 9788884518781) def test_title(): harry_potter = create_book(1) assert harry_potter.title == "Harry Potter e la pietra filosofale" def test_author(): harry_potter = create_book(1) assert harry_potter.author == "J. K. Rowling" def test_publisher(): harry_potter = create_book(1) assert harry_potter.publisher == "Salani Editore" def test_year(): harry_potter = create_book(1) assert harry_potter.year == 1997 def test_pages(): harry_potter = create_book(5) assert harry_potter.pages == 738 def test_isbn(): harry_potter = create_book(1) assert harry_potter.isbn == 8877827025 def test_bulky_1(): # se il libro ha più di 500 pagine, è ingombrante (bulky) harry_potter = create_book(1) assert harry_potter.is_bulky == False def test_bulky_2(): harry_potter = create_book(5) assert harry_potter.is_bulky == True def test_bulky_3(): harry_potter = create_book(6) assert harry_potter.is_bulky == False def test_valuable_1(): # Un libro è pregiato (valuable) se ha più di 20 anni o meno di un anno harry_potter = create_book(1) # is valuable prende in input l'anno presente # in python per prendere l'anno corrente, si può usare # la libreria datetime come segue assert harry_potter.is_valuable(datetime.now().year) == True def test_valuable_2(): harry_potter = create_book(7) assert harry_potter.is_valuable(datetime.now().year) == False def test_valuable_3(): harry_potter = create_book(6) assert harry_potter.is_valuable(2005) == True def test_valuable_4(): harry_potter = create_book(7) assert harry_potter.is_valuable(2030) == True def test_isbn_1(): # Assuming the digits are "abcdefghi-j" where j is the check digit. Then the check digit is computed by the following formula: # j = ( [a b c d e f g h i] * [1 2 3 4 5 6 7 8 9] ) mod 11 harry_potter = create_book(1) assert harry_potter.is_isbn_valid() == True def test_isbn_2(): # Assuming the digits are "abcdefghi-j" where j is the check digit. Then the check digit is computed by the following formula: # j = ( [a b c d e f g h i] * [1 2 3 4 5 6 7 8 9] ) mod 11 harry_potter = create_book(4) assert harry_potter.is_isbn_valid() == False
from bs4 import BeautifulSoup import requests, json, time, re, csv, time def subtitle_clean(str_input): str_input = str(str_input) str_input = str_input.strip('<span class="subtitle">') str_input = str_input.strip('</span>') return str_input #create empty list for books subtitle_info_list = [] #create empty list for book urls url_list = [] with open('new_classics.csv','r', encoding="utf-8") as f: reader = csv.reader(f) #instruct python to ignore headers when reading the data within the csv file headers = next(reader) for row in reader: # how do we assign the rows to be the url variable used in the get request? url_list.append(row[3]) count = 0 for url in url_list: print("scraping!" + url + " " + str(count)) nyrb_classics_book = requests.get(url) #setting the variable for the HTML of the page page_html = nyrb_classics_book.text #parsing our HTML with BeautifulSoup to give a BeautifulSoup object soup = BeautifulSoup(page_html, "html.parser") #identifying the parent span that holds the subtitle element we want to scrape all_info = soup.find_all("div", attrs={"class":"span8"}) #looping through to pull out the elements we want for item in all_info: subtitle = item.find("span", attrs={"class":"subtitle"}) print(subtitle) #adding a count variable so that it counts each loop count = count + 1 #setting up dictionary subtitle_info = {} #defining keys and values in dictionary subtitle_info["id"] = count subtitle_info["subtitle"] = subtitle_clean(subtitle) # print(subtitle_info) #appending our dictionary to our list of books subtitle_info_list.append(subtitle_info) time.sleep(3) # print(subtitle_info_list) # #dumping our list of dictionaries into a JSON file json.dump(subtitle_info_list, open("14_subtitles.json", "w"), indent=2) #prints the number of titles to command line (not included in JSON file) print(len(subtitle_info_list))
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Genre, Base, Movie, User engine = create_engine('sqlite:///movieswithusers.db') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() user1 = User(name="Bria", email="email@email.com") session.add(user1) session.commit() # Movies for romantic comedy genre genre1 = Genre(name="Romantic Comedy", user=user1) session.add(genre1) session.commit() movie1 = Movie(name="27 Dresses", description="Woman who is the very " + "definition of \"always the bridesmaid but never the bride\" " + "has to deal with being the maid of honor for the wedding of " + "her sister to the man she's in love with.", rating="PG-13", score="40", genre=genre1, user=user1) session.add(movie1) session.commit() movie2 = Movie(name="Pretty Woman", description="An unlikely pair fall in " + "love with each other after she's introduced to life off the " + "streets and he learns how to live life carelessly.", rating="R", score="62", genre=genre1, user=user1) session.add(movie2) session.commit() movie3 = Movie(name="How to Lose a Guy in 10 Days", description="She makes a " + "bet that she can get rid of any man in 10 days. He makes a " + "bet that he can make any girl fall in love with him in 10 " + "days. Who will win?", rating="PG-13", score="42", genre=genre1, user=user1) session.add(movie3) session.commit() movie4 = Movie(name="Hitch", description="Hitch is a successful love doctor " + "and certified ladies man, but suddenly he finds himself " + "struggling to help his newest client and maintain his " + "anonymity all while juggling his own love life.", rating="PG-13", score="40", genre=genre1, user=user1) session.add(movie4) session.commit() movie5 = Movie(name="13 Going on 30", description="After suffering " + "humiliation by the cool kids in school at her 13th birthday " + "party, teenage Jenna wished to be 30, flirty, and thriving. " + "Her wished come true, but is it everything she hoped it " + "would be?", rating="PG-13", score="65", genre=genre1, user=user1) session.add(movie5) session.commit() # Movies for drama genre genre2 = Genre(name="Drama", user=user1) session.add(genre2) session.commit() movie1 = Movie(name="The Devil Wears Prada", description="Budding journalist " + "Andy takes a job as second assistant for the infamous " + "Miranda Priestly to jumpstart her writing career.", rating="PG-13", score="75", genre=genre2, user=user1) session.add(movie1) session.commit() movie2 = Movie(name="Menace II Society", description="Caine tries to leave " + "his violent, gang-affiliated lifestyle behind but escaping " + "the hood proves to be harder than planned.", rating="R", score="84", genre=genre2, user=user1) session.add(movie2) session.commit() movie3 = Movie(name="The Help", description="A brave author decides to " + "examine and share the heart-wrenching tales of the " + "courageous, hard working Mississipi maids of the Jim " + "Crow south.", rating="PG-13", score="76", genre=genre2, user=user1) session.add(movie3) session.commit() movie4 = Movie(name="The Social Network", description="The story of Facebook's" + " inception and the lawsuits that followed are depicted in " + "this 2010 drama.", rating="PG-13", score="95", genre=genre2, user=user1) session.add(movie4) session.commit() movie5 = Movie(name="Creed", description="An unknown boxer tries to make a " + "name for himself without using his famous father's name.", rating="PG-13", score="95", genre=genre2, user=user1) session.add(movie5) session.commit() # Movies for horror genre genre3 = Genre(name="Horror", user=user1) session.add(genre3) session.commit() movie1 = Movie(name="Us", description="Adelaide and her family return to " + "Adelaide's childhood home and discover that a stranger has " + "been awaiting Adelaide's return.", rating="R", score="94", genre=genre3, user=user1) session.add(movie1) session.commit() movie2 = Movie(name="Get Out", description="A man travels with his " + "girlfriend to meet her family, but he soon realizes that " + "their intentions are quite different from his.", rating="R", score="98", genre=genre3, user=user1) session.add(movie2) session.commit() movie3 = Movie(name="The Conjuring", description="A team of paranormal " + "investigators are called to help a family who is currently " + "dealing with their house's supernatural manifestations.", rating="R", score="85", genre=genre3, user=user1) session.add(movie3) session.commit() movie4 = Movie(name="Devil", description="Five strangers in a stuck elevator " + "soon realize that one of the occupants is the devil himself " + "as he seeks terror on the passengers.", rating="PG-13", score="52", genre=genre3, user=user1) session.add(movie4) session.commit() movie5 = Movie(name="Insidious", description="A couple seek the help of a " + "demonologist to get their son out of an apparent comatose " + "state leaving his body as an open vessel for demons to " + "inhabit.", rating="PG-13", score="66", genre=genre3, user=user1) session.add(movie5) session.commit() # Movies for action genre genre4 = Genre(name="Action", user=user1) session.add(genre4) session.commit() movie1 = Movie(name="Jack Reacher", description="An ex-military investigator " + "comes back on the grid to help clear the name of an " + "ex-military sniper suspected of murdering 5 people.", rating="PG-13", score="63", genre=genre4, user=user1) session.add(movie1) session.commit() movie2 = Movie(name="Marvel's Black Panther", description="A scorned relative " + "to Wakandan royalty comes to challenge the current Black " + "Panther and king of Wakanda for the rights to the throne.", rating="PG-13", score="97", genre=genre4, user=user1) session.add(movie2) session.commit() movie3 = Movie(name="The Dark Knight", description="The emergence of The " + "Joker in the city of Gotham forces Batman to toe the line " + "between heroism and vigilantism.", rating="PG-13", score="94", genre=genre4, user=user1) session.add(movie3) session.commit() movie4 = Movie(name="Edge of Tomorrow", description="William Cage is " + "mysteriously thrown into a time loop and forced to relive " + "the same battle over and over again during a war between " + "Earth and a seemingly invincible alien species.", rating="PG-13", score="90", genre=genre4, user=user1) session.add(movie4) session.commit() movie5 = Movie(name="Mad Max: Fury Road", description="Furiosa and Mad Max " + "escape the tyrant Immortan Joe's desert fortress with the " + "tyrant's five wives and lead Immortan Joe and his henchmen " + "on a deadly chase through the Wasteland.", rating="R", score="97", genre=genre4, user=user1) session.add(movie5) session.commit() # Movies for musical genre genre5 = Genre(name="Musical", user=user1) session.add(genre5) session.commit() movie1 = Movie(name="Dreamgirls", description="Follow the journey of a " + "3-woman singing group as they try to make it to the top of " + "the charts and the music world.", rating="PG-13", score="78", genre=genre5, user=user1) session.add(movie1) session.commit() movie2 = Movie(name="Into the Woods", description="A baker and his wife meet " + "countless fairytale characters as they venture into the " + "woods for spell ingredients to deliver to a wicked witch.", rating="PG", score="71", genre=genre5, user=user1) session.add(movie2) session.commit() movie3 = Movie(name="Les Miserables", description="A prison officer vows to " + "bring a freed criminal, who broke parole, back to prison " + "despite the criminal's reinvention of himself and his " + "adoption of an orphan.", rating="PG-13", score="69", genre=genre5, user=user1) session.add(movie3) session.commit() movie4 = Movie(name="Hairspray", description="An overweight teen becomes an " + "overnight celebrity on a popular dance show and fights to " + "break normal beauty standards and racial segregation.", rating="PG", score="91", genre=genre5, user=user1) session.add(movie4) session.commit() movie5 = Movie(name="La La Land", description="A pianist and an actress fall " + "in love but their aspirations threaten to end their " + "romance.", rating="PG-13", score="91", genre=genre5, user=user1) session.add(movie5) session.commit()
""" >>> parser0.print_help() # doctest: +ELLIPSIS usage: PROG [-h] [--foo FOO] ... optional arguments: -h, --help show this help message and exit --foo FOO foo help >>> parser1.print_help() # doctest: +ELLIPSIS usage: PROG [--foo FOO] ... optional arguments: --foo FOO foo help >>> parser2.print_help() # doctest: +ELLIPSIS usage: PROG [+h] ... optional arguments: +h, ++help show this help message and exit """ import argparse # standard way # ################ parser0 = argparse.ArgumentParser(prog='PROG') parser0.add_argument('--foo', help='foo help') # do not show the help # ######################## parser1 = argparse.ArgumentParser(prog='PROG', add_help=False) parser1.add_argument('--foo', help='foo help') # change help prefix # ###################### parser2 = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
# Abra una imagen y aplíquele diferentes tipos de filtros pasa bajos. Visualice el resultado # y observe qué ocurre cuando se modifican los coeficientes (kernel 3x3) import cv2 import matplotlib.pyplot as plt import numpy as np import tkinter as tk from tkinter import filedialog def file_read(): ''' Abro una ventana Tkinter y obtengo path de la imagen ''' file_path = filedialog.askopenfilename() return file_path def low_pass_filtering(image, radius): ''' Low pass filter function :param image: input image :param radius: radius :return: filtering result ''' # Fourier transform the image, fft is a three-dimensional array, fft[:, :, 0] is the real part, fft[:, :, 1] is the imaginary part fft = cv2.dft(np.float32(image), flags=cv2.DFT_COMPLEX_OUTPUT) # Centralize fft, the generated dshift is still a three-dimensional array dshift = np.fft.fftshift(fft) # Get the center pixel rows, cols = image.shape[:2] mid_row, mid_col = int(rows / 2), int(cols / 2) # Build mask, 256 bits, two channels mask = np.zeros((rows, cols, 2), np.float32) mask[mid_row - radius:mid_row + radius, mid_col - radius:mid_col + radius] = 1 # Multiply the Fourier transform result by a mask fft_filtering = dshift * mask # Inverse Fourier transform ishift = np.fft.ifftshift(fft_filtering) image_filtering = cv2.idft(ishift) image_filtering = cv2.magnitude(image_filtering[:, :, 0], image_filtering[:, :, 1]) # Normalize the inverse transform results (generally normalize the last step of image processing, except in special cases) cv2.normalize(image_filtering, image_filtering, 0, 1, cv2.NORM_MINMAX) return image_filtering def ploteo(original, result): fig, axes = plt.subplots(ncols=2, nrows=1, figsize=(6, 2.5)) ax = axes.ravel() ax[0] = plt.subplot(121) # Imagen original ax[1] = plt.subplot(122) # Imagen resultado ax[0].imshow(cv2.cvtColor(original, cv2.COLOR_BGR2RGB)) ax[0].set_title('Original') ax[1].imshow(cv2.cvtColor(result, cv2.COLOR_BGR2RGB)) ax[1].set_title('Filtro pasa bajos') # Inicio Tkinter root = tk.Tk() root.withdraw() try: image = cv2.imread(file_read(), 0) img_filter = low_pass_filtering(image=image, radius=50) ploteo(original=image, result=img_filter) plt.show() except: print('Fin del codigo') root.destroy()
import sys if __name__=="__main__": n=input("Enter an number: ") n=int(n) i=0 sum=0 for i in range (0,n+1): sum+=i print("Sum of first "+ str(n) +" numbers is: "+ str(sum)) else: print("Something does not work. :/")
class Solution: def twoSum(self, nums, target): num_set = {} for index,num in enumerate(nums): if target-num in num_set: return [num_set[target-num],index] num_set[num]=index print(num_set)
class Solution: def isPalindrome(self, s): string = [] for char in s: if char.isalnum(): string.append(char.lower()) lens = len(string) for i in range(lens): lens = lens - 1 if string[i] != string[lens]: return False return True valid = Solution() print(valid.isPalindrome("A man, a plan, a canal: Panama"))
def solution(array, commands): answer = [] for i in commands: # [2, 5, 3] -> [4, 4, 1] -> [1, 7, 3] temp_arr = [] for j in range(i[0] - 1, i[1]): # temp_arr 만들기 temp_arr.append(array[j]) # temp_arr 채우기 temp_arr.sort() answer.append(temp_arr[i[2] - 1]) temp_arr.clear() return answer
loop = [1,2,3] for item in loop: print(item) tuple = [(1,2), (3,4), (5,6)] for a, b in tuple: print(a, b) dict = {'k1':1, 'k2':2, 'k3':3} for key, value in dict.items(): print(key) x = 1 while x < 5: print('this is True') x+=1 else: print('this is False') word = 'hello' for index, char in enumerate(word): print(index, char) mylist1 = [1,2,3] mylist2 = ['a', 'b', 'c'] mylist3 = [100, 200, 300] for item in zip(mylist1, mylist2, mylist3): print(item) # list comprehension serves as a forEach or .map (returns a new array of objects with logic performed on each) celcius = [0, 10, 20, 34.5] fahrenheit = [( (9/5)* temp + 32) for temp in celcius] conditional_fahrenheit = [( (9/5)* temp + 32) for temp in celcius if temp > 0] print(fahrenheit) print(conditional_fahrenheit) def myfunc(*args): for item in args: print(item) myfunc(40,10,20,30) def random(**kwargs): print(kwargs) print(random(shoe = 1,man = 2, wow = 'cat'))
class Node: def __init__(self, value): self.value = value self.nextnode = None def reverse(head): current = head prev = None next = None while current: nextnode = current.nextnode current.nextnode = prev prev = current current = next return prev
unsorted_array = [99,88,33,11,4,6,77] def insertion_sort(arr): for i in range(0, len(arr)): j = i while j != 0 and arr[j] < arr[j - 1]: arr[j], arr[j - 1] = arr[j - 1], arr[j] j -= 1 return arr print(insertion_sort(unsorted_array))
av = 3 x=int(input("enter no of candies you want :")) i=1 while i<=x: if i>av: print("out of stock") break print("candy") i=i+1 print("Bye")
import math # simple program practicing methods of Number a = 120 b = 20.5 #checking type of a and b print(type(a)) print(type(b)) # type conversion c = int(b) print(c) # some functions print(abs(-40)) print(math.ceil(b)) print(math.floor(b)) print(math.log(a)) print(math.log10(a)) print(max(2,4,10,20,4.5)) print(min(2,4,10,20,4.5)) print(math.sqrt(b))
# Largest sublist with 0 sum list = [15,-2,2,-8,1,7,10,23] def subList(list) : sum = 0 len = 0 dict = {} for item in list : sum = sum + item if sum == 0 and len == 0 : len = 1 if sum == 0 : len = list.index(item) + 1 if sum not in dict : dict[sum] = list.index(item) else : ''' if the same value appears twice in the list, it will be guaranteed that the particular list will be a zero-sum sub-list ''' len = max(len,list.index(item) - dict[sum]) return len print(subList(list))
''' count all the triplets such that sum of two elements equals the third element. ''' #taking input list_input = [] no_of_element = int(input("Enter no. of element in list\n")) i = 0 while i < no_of_element : element = int(input("Enter number\n")) list_input.append(element) i+=1 def countTriplet(list) : dict = {} count = 0 for item in list : dict[item] = 1 i = 0 while i < len(list) - 1 : j = i +1 while j < len(list) : sum = list[i] + list [j] if sum in dict : count+=1 j+=1 i+=1 return count print(countTriplet(list_input))
# tWo strings are anagram or not ''' task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. ''' str1 = input("Enter 1st string\n") str2 = input("Enter 2nd string\n") def checkAnagram(str1,str2) : dict = {} for item in str1 : if item in dict : dict[item] = dict[item] + 1 else : dict[item] = 1 for item in str2 : if item in dict : if dict[item] == 1 : del dict[item] else : dict[item] = dict[item] - 1 if len(dict) == 0 : return "Both string are anagrams" else : return "Both string are not anagrams" print(checkAnagram(str1,str2))
# Program to chcek You are underWeight overWeight or fit ''' Formula to calculate BMI : weight (kg) / [height (m)]2 ''' def takeInput() : #function to take input from users weight = float(input('Enter your weight in kg\n')) height_in_feet = float(input("Enter Your height in feet\n")) calculateBMI(weight,height_in_feet) def calculateBMI(weight,height_in_feet) : #function to calculate BMI # converting height in meter height_in_m = height_in_feet/3.2808 # calculating BMI bmi = weight/height_in_m**2 checkFitOrNot(bmi) def checkFitOrNot(bmi) : ''' function to check is user is overWight underWeight or fit If your BMI is less than 18.5, it falls within the underweight range. If your BMI is 18.5 to 24.9, it falls within the normal or Healthy Weight range. If your BMI is 25.0 to 29.9, it falls within the overweight range. If your BMI is 30.0 or higher, it falls within the obese range. ''' if bmi < 18.5 : print("UnderWeight") elif bmi >= 18.5 and bmi <= 24.9 : print("Healthy Weight") elif bmi >= 25.0 and bmi <= 29.9 : print("OverWeight") elif bmi >= 30.0 : print("Obese") takeInput()
class Student: """ Student class contains student id, first name and last name""" def __init__(self, f_name, l_name, id_num): """Create a new Student """ self.firstName = f_name self.lastName = l_name self.idNum = id_num def getFirst(self): """get the first name of the Student""" return self.firstName def getLast(self): """get the last name of the Student""" return self.lastName def getIdNum(self): """get the ID number of the Student""" return self.idNum def prompt_student(): """Prompts user for info and saves it as a student object""" first = input("Please enter your first name: ") last = input("Please enter your last name: ") num = int(input("Please enter your id number: ")) studentInfo = Student(first, last, num) return studentInfo def display_student(student): """ function displays student info from Student object""" print("") print("Your information:") print("{} - {} {}" .format(student.getIdNum(), student.getFirst(), student.getLast())) def main(): user = prompt_student() display_student(user) #used to call the main function if __name__ == "__main__": main()
class Rational(): """Rational class holds rational numbers with a top number/ numerator and a bottom number/ denominatior""" def __init__(self): self.top = 0 self.bottom = 1 def display(self): if(int(self.bottom) > int(self.top)): print("{}/{}".format(int(self.top), int(self.bottom))) else: whole = int(self.top)/int(self.bottom) remainder = int(self.top)%int(self.bottom) if (remainder > 0): print("{} {}/{}".format(int(whole), int(remainder), self.bottom)) else: print(int(whole)) def prompt(self): self.top = input("Enter the numerator: ") self.bottom = input("Enter the denominator: ") def decimal(self): print(int(self.top)/int(self.bottom)) def reduceNum(self): #if(int(self.top) >= int(self.bottom)): i = 1 divisable = 0 while (i<=int(self.bottom)): redTop = int(self.top)%i redBot = int(self.bottom)%i if (int(redBot) == 0 and int(redTop) == 0): divisable = i i += 1 if (int(divisable) > 1): self.top = int(self.top)/int(divisable) self.bottom = int(self.bottom)/int(divisable) def multiply_by(firstNumber): secondNumber = Rational() secondNumber.prompt() newTop = int(firstNumber.top) * int(secondNumber.top) newBottom = int(firstNumber.bottom) * int(secondNumber.bottom) return newTop, newBottom def main(): number = Rational() number.display() number.prompt() number.display() number.decimal() number.reduceNum() number.display() multipled = Rational() mTop, mBottom = multiply_by(number) multipled.top = mTop multipled.bottom = mBottom multipled.display() #used to call the main function if __name__ == "__main__": main()
""" File: rock.py Author: Ali Cope Contains Rock class and three derived Rocks to be used as asteroids: LargeRock, MediumRock and SmallRock """ import arcade import math import random from flying import Flying # These are Global constants to use throughout the game SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 BIG_ROCK_SPIN = 1 BIG_ROCK_SPEED = 1.5 BIG_ROCK_RADIUS = 15 MEDIUM_ROCK_SPIN = -2 MEDIUM_ROCK_RADIUS = 5 SMALL_ROCK_SPIN = 5 SMALL_ROCK_RADIUS = 2 class Rock(Flying): """ Creates a rock class with the following spin : int +__init__() +hit() : none it will inheriate from flying: center : Point velocity : Velocity alive : Boolean radius : float +is_off_screen(screen_width, screen_height) : Boolean +draw() : None and will override the following inherited from flying +advance() : None """ def __init__(self): #call the base class to set up our point and velocity super().__init__() #add radius self.radius = 0.0 #start the asteroid randomly on the top half of the screen self.center.y = random.uniform(SCREEN_HEIGHT/2, SCREEN_HEIGHT) #start the asteroid randomly on the horizontal axis self.center.x = random.uniform(0, SCREEN_WIDTH) #create spin for asteroid rotation self.spin = 0 #TODO Turn into abstract class def hit(self): """ hit method abstract for what happens when the astroid is hit """ def advance(self): """ advance function moves the center along the velocity """ # set x equal to x plus dx self.center.x += self.velocity.dx # set y equal to y plus dy self.center.y += self.velocity.dy #rotate the asteroid self.angle += self.spin class LargeRock(Rock): """ Creates a large asteroid class with the following +__init__() it will inheriate from flying: center : Point velocity : Velocity alive : Boolean radius : float spin : int +is_off_screen(screen_width, screen_height) : Boolean +advance() : None and will override the following inherited from flying +hit() : none +draw() : None """ def __init__(self): #call the base class to set up our point and velocity super().__init__() #add radius self.radius = BIG_ROCK_RADIUS #create spin for asteroid rotation self.spin = BIG_ROCK_SPIN #set initial velocity for large asteroid #set a random direction for the rock direction = random.uniform(0,4) if direction <=1: self.velocity.dx = 1.5 self.velocity.dy = 1.5 elif direction <=2: self.velocity.dx = -1.5 self.velocity.dy = 1.5 elif direction <=3: self.velocity.dx = 1.5 self.velocity.dy = -1.5 else: self.velocity.dx = -1.5 self.velocity.dy = -1.5 def hit(self): """ hit method abstract for what happens when the astroid is hit """ med1 = MediumRock(self.center.x, self.center.y, self.velocity.dx, self.velocity.dy+2) med2 = MediumRock(self.center.x, self.center.y, self.velocity.dx, self.velocity.dy-2) small = SmallRock(self.center.x, self.center.y, self.velocity.dx+5, self.velocity.dy) rocks = [med1, med2, small] return rocks def draw(self): """ override the draw function in flying class """ img = "images/meteorGrey_big1.png" texture = arcade.load_texture(img) width = texture.width height = texture.height alpha = 255 # For transparency, 1 means not transparent x = self.center.x y = self.center.y angle = self.angle arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha) class MediumRock(Rock): """ Creates a medium asteroid class with the following +__init__() it will inheriate from flying: center : Point velocity : Velocity alive : Boolean radius : float spin : int +is_off_screen(screen_width, screen_height) : Boolean +advance() : None and will override the following inherited from flying +hit() : none +draw() : None """ def __init__(self, x, y, dx, dy): #call the base class to set up our point and velocity super().__init__() #add radius self.radius = MEDIUM_ROCK_RADIUS #create spin for asteroid rotation self.spin = MEDIUM_ROCK_SPIN self.center.x = x self.center.y = y self.velocity.dx = dx self.velocity.dy = dy def hit(self): """ hit method abstract for what happens when the astroid is hit """ small1 = SmallRock(self.center.x, self.center.y, self.velocity.dx+1.5, self.velocity.dy+1.5) small2 = SmallRock(self.center.x, self.center.y, self.velocity.dx-1.5, self.velocity.dy-1.5) rocks = [small1, small2] return rocks def draw(self): """ override the draw function in flying class """ img = "images/meteorGrey_med1.png" texture = arcade.load_texture(img) width = texture.width height = texture.height alpha = 255 # For transparency, 1 means not transparent x = self.center.x y = self.center.y angle = self.angle arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha) class SmallRock(Rock): """ Creates a medium asteroid class with the following +__init__() it will inheriate from flying: center : Point velocity : Velocity alive : Boolean radius : float spin : int +is_off_screen(screen_width, screen_height) : Boolean +advance() : None and will override the following inherited from flying +hit() : none +draw() : None """ def __init__(self, x, y, dx, dy): #call the base class to set up our point and velocity super().__init__() #add radius self.radius = MEDIUM_ROCK_RADIUS #create spin for asteroid rotation self.spin = MEDIUM_ROCK_SPIN self.center.x = x self.center.y = y self.velocity.dx = dx self.velocity.dy = dy def hit(self): """ hit method abstract for what happens when the astroid is hit """ #no new rocks are created rocks = [] return rocks def draw(self): """ override the draw function in flying class """ img = "images/meteorGrey_small1.png" texture = arcade.load_texture(img) width = texture.width height = texture.height alpha = 255 # For transparency, 1 means not transparent x = self.center.x y = self.center.y angle = self.angle arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha) class Ufo(Rock): """ Creates a Ufo class with the following +__init__() it will inheriate from flying: center : Point velocity : Velocity alive : Boolean radius : float spin : int +is_off_screen(screen_width, screen_height) : Boolean +advance() : None and will override the following inherited from flying +hit() : none +draw() : None """ def __init__(self): #call the base class to set up our point and velocity super().__init__() #add radius self.radius = 10 self.center.x = random.uniform(0, SCREEN_WIDTH) self.center.y = random.uniform(0, SCREEN_HEIGHT) self.velocity.dx = random.uniform(-2, 2) self.velocity.dy = random.uniform(-2, 2) def hit(self): """ hit method abstract for what happens when the astroid is hit """ #eject two aliens alien1 = Alien(self.center.x, self.center.y, self.velocity.dx+1.5, self.velocity.dy+1.5) alien2 = Alien(self.center.x, self.center.y, self.velocity.dx-1.5, self.velocity.dy-1.5) aliens = [alien1, alien2] return aliens def draw(self): """ override the draw function in flying class """ img = "images/ufo.png" texture = arcade.load_texture(img) width = texture.width height = texture.height alpha = 255 # For transparency, 1 means not transparent x = self.center.x y = self.center.y angle = self.angle arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha) class Alien(Rock): """ Creates a medium asteroid class with the following +__init__() it will inheriate from flying: center : Point velocity : Velocity alive : Boolean radius : float spin : int +is_off_screen(screen_width, screen_height) : Boolean +advance() : None and will override the following inherited from flying +hit() : none +draw() : None """ def __init__(self, x, y, dx, dy): #call the base class to set up our point and velocity super().__init__() #add radius self.radius = 7 #create spin for asteroid rotation self.spin = -2 self.center.x = x self.center.y = y self.velocity.dx = dx self.velocity.dy = dy def hit(self): """ hit method abstract for what happens when the astroid is hit """ #no new rocks are created rocks = [] return rocks def draw(self): """ override the draw function in flying class """ img = "images/Alien.png" texture = arcade.load_texture(img) width = texture.width height = texture.height alpha = 255 # For transparency, 1 means not transparent x = self.center.x y = self.center.y angle = self.angle arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)
""" File: ds07.py Author: Ali Cope This purpose of this program is to use recursion to calculate the fibonacci number. The function will take just the nth number that we are looking for in fibonacci and return the result """ #first fibonacci number def fib(nth): """ fib function takes an index and returns the fibonacci number using recursion """ if (nth <= 1): return 1 return fib(nth-1) + fib(nth-2) def main(): """ main function will prompt user for index and print result """ #get nth number from user index = int(input("Enter a Fibonacci index:")) print("The Fibonacci number is: {}".format(fib(index-1))) if __name__ == "__main__": main()
import unittest from tests.system_tests.code_runner import run_code class VariablesTester(unittest.TestCase): def test_simple_var_declaration(self): code = """ void main() { int x; } """ target_output = "" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_simple_var_Assignment(self): code = """ void main() { int x; x = 3; } """ target_output = "" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_simple_var_Assignment_in_Declaration(self): code = """ void main() { int x = 3; } """ target_output = "" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_simple_var_Use(self): code = """ void main() { int x = 3; printf("%i",x); } """ target_output = "3" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_multiple_inline_declarations(self): code = """ void main() { int x,y; } """ target_output = "" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_multiple_inline_declarations_and_Assignment(self): code = """ void main() { int x = 2,y = 3; } """ target_output = "" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_multiple_inline_declarations_and_Assignment_different(self): code = """ void main() { int x,y = 3; } """ target_output = "" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_multiple_inline_declarations_and_Assignment_and_Use(self): code = """ void main() { int x = 2,y = 3; printf("%i %i",x,y); } """ target_output = "2 3" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_nested_if_scope_Access_to_outside_scope(self): code = """ void main() { int x = 99; if(x){ printf("%d",x); } } """ target_output = "99" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_nested_scope_access_to_scope_variables(self): code = """ void main() { int x = 122; { printf("%i",x); } } """ target_output = "122" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_access_to_global_variables(self): code = """ int x; void main() { if(1){ x = 2; printf("%i",x); } } """ target_output = "2" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_access_of_multiple_scopes(self): code = """ void main() { int z=1; if(1){ int x = 2; printf("%i ",x); } if(1){ int y=7; printf("%i %i",y,z); } } """ target_output = "2 7 1" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_shadowing(self): code = """ void main() { int x = 1; if(1){ int x = 2; printf("%i",x); } printf("%i",x); } """ target_output = "21" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_double_scopes(self): code = """ void main() { int x = 0; {} } """ target_output = "" scc_output = run_code(code) self.assertEquals(target_output, scc_output) def test_variable_assignment_in_inner_scope(self): code = """ void main() { int x = 12; printf("%d ",x); { x = 3; printf("%d ",x); } printf("%d",x); } """ target_output = "12 3 3" scc_output = run_code(code) self.assertEquals(target_output, scc_output) if __name__ == "__main__": unittest.main()
from unittest import TestCase from main import GameEngine game = GameEngine() class TestGameEngine(TestCase): def test_is_invalid_letter_is_numeric(self): self.assertTrue(game.is_invalid_letter("1")) def test_is_invalid_letter_is_special(self): self.assertTrue(game.is_invalid_letter("!")) def test_is_invalid_letters(self): self.assertTrue(game.is_invalid_letter("gh")) def test_is_valid_letter(self): self.assertFalse(game.is_invalid_letter("a")) def test_is_valid_letter_capital(self): self.assertFalse(game.is_invalid_letter("a")) def test_play_right_guess(self): game.secret_word = "apple" right_guess = 0 for ch in "apple": letter_found = game.find_indexes(ch) if letter_found: right_guess += 1 self.assertEqual(right_guess, len(game.secret_word)) def test_play_wrong_guess(self): game.secret_word = "apple" right_guess = 0 for ch in "orange": letter_found = game.find_indexes(ch) if letter_found: right_guess += 1 self.assertNotEqual(right_guess, len(game.secret_word))
import numpy as np import matplotlib.pyplot as plt from matplotlib.image import imread """ How to use Matplotlib ver. python3.5 author y-ok """ # データ準備 x = np.arange(0, 6, 0.1) # 0から6まで0.1刻みでデータ生成 y1 = np.sin(x) y2 = np.cos(x) # グラフ描画 plt.subplot(2, 1, 1) plt.plot(x, y1, label="$\sin$") plt.plot(x, y2, linestyle = "--", label="$\cos$") plt.xlabel("x") plt.ylabel("y") plt.title("$\sin(x)$ & $\cos(x)$") # グラフに凡例をつける plt.legend() """ Matplotlib.py実行時、以下のエラーが発生 ================================================================================================================== RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are Working with Matplotlib in a virtual enviroment see 'Working with Matplotlib in Virtual environments' in the Matplotlib FAQ ================================================================================================================== 対処法は、http://qiita.com/Kodaira_/items/1a3b801c7a5a41c9ce49に記載通り。 以下のファイルを修正し、対応 ~/.pyenv/versions/anaconda3-4.1.1/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc """ img = imread('./data/img/Lenna.png') plt.subplot(2, 1, 2) plt.imshow(img) plt.show()
fileLines = open("input.txt", "r") freq = 0 for line in fileLines: print (line) freq = freq + int(line) print(freq)
from tkinter import * root = Tk() my_label = Label(root, text = 'I am l label') my_button = Button(root, text = 'I am a button') my_label.pack() my_button.pack() root.mainloop()
import numpy as np import matplotlib.pylab as plt def my_gaussian(x_points, mu, sigma): """ from: https://github.com/NeuromatchAcademy/course-content/blob/master/tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_aeeeaedf.py Returns normalized Gaussian estimated at points `x_points`, with parameters: mean `mu` and std `sigma` Args: x_points (numpy array of floats): points at which the gaussian is evaluated mu (scalar): mean of the Gaussian sigma (scalar): std of the gaussian Returns: (numpy array of floats) : normalized Gaussian evaluated at `x` """ px = np.exp(- 1/ 2 / sigma ** 2 * (mu - x_points) ** 2) px = px / px.sum() # this is the normalization: this part ensures the sum of # the individual probabilities at each `x` add up to one. # It makes a very strong assumption though: # That the `x_points` cover the big portion of # probability mass around the mean. # Please think/discuss when this would be a dangerous # assumption. # E.g.: What do you think will happen to the values on # the y-axis # if the `x` values (x_point) range from -1 to 8 instead # of -8 to 8? return px def get_mixture_of_random_gaussians(number_of_gaussians, x_points): mixture = np.zeros(len(x_points)) for component in range(number_of_gaussians): random_mu = np.random.uniform(0, len(x_points)) random_sigma = np.random.uniform(0, len(x_points)/4) new_gauss = my_gaussian(x_points, random_mu, random_sigma) new_gauss = new_gauss / np.linalg.norm(new_gauss) mixture += new_gauss return mixture def moving_average(x, window): return np.convolve(x, np.ones(window), 'valid') / window def main(): mix = get_mixture_of_random_gaussians(15, np.arange(250)) plt.plot(mix) plt.show() if __name__ == '__main__': main()
# Complete the solution so that it reverses the string value passed into it. # # solution('world') # returns 'dlrow' # This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off # and specifying a step of -1, it reverses a string. def solution(string): return string[::-1]
# IMPORTEER BELANGRIJKE BIBLIOTHEKEN import simpleaudio as sa import time import random """ An example project in which a rhythmical sequence (one measure, 1 sample) is played. - Sixteenth note is the smallest used note duration. - One meassure, time signature: 3 / 4 Instead of using steps to iterate through a sequence, we are checking the time. We will trigger events based on a timestamp. ------ HANDS-ON TIPS ------ - Run the code, read the code and answer the following question: - This script transforms a list of 'sixteenth notes timestamps' into a list of regular timestamps. In the playback loop, the time difference (currentTime minus startTime) is compared to the upcomming timestamp. Why is this a more accurate method then the methods used in the examples "04_randomNoteDuration.py" and "05_oneSampleSequenceSteps.py"? Notate your answer below this line (Dutch is allowed)! --> Omdat dat je een discrete tijdfactor geeft die ritmisch onderverdeeld is in tijdseenheden. Vertragingstijd (latency) van de code zelf speelt geen rol meer. - Alter the code: Currently one sample is played. Add another sample to the script. When a sample needs to be played, choose one of the two samples randomly. (See the hint about the random package in script "02_timedPlayback".) - Alter the code: Currently the sequence is only played once. Alter the code to play it multiple times. hint: The timestamps list is emptied using the pop() function. (multiple possible solutions) """ #setting the global variables # INIT DE SAMPLE, load sample from computer samples = [sa.WaveObject.from_wave_file("snare.wav"), sa.WaveObject.from_wave_file("kick.wav"), sa.WaveObject.from_wave_file("pop.wav"),] notelengthvalues = [] timestamps = [] #------------------------------------------------------- #PART 1: BPM CALCULATONS ------------------------------- #SET the standard BPM bpm = 120 print("the standard bpm is now: " + str(bpm) ) #set bpm function (ASK TO CHANGE BPM) # if yes: set new bpm, if no leave at standard bpm = 120 # Als gebruiker in de BPM een random ding invoert komt er nu een foutmelding # googlen op TRy catch! def setBpm(): print("do you want to enter new bmp? y or n") answer = input() answer = str(answer) #while the answer is not n or y repeat question while answer != "n" and answer != "y": print("Please enter y or n ") answer = input() answer = str(answer) if answer == "y": global bpm bpm = input("set bpm: ") bpm = int(bpm) print("bpm has been set to: " + str(bpm)) if answer == "n": print("okay then, leave it at: " + str(bpm)) setBpm() #------------------------------------------------------- #------------------------------------------------------- #PART 2: Calculating the time in seconds from 16th notes with the BPM #DEFINE THE FUNCTION THAT CALCULATES TIMEDURATIONS FROM THE TIMESTAMPS def durationsToTimestamps16th(): quarterNoteDuration = 60 / bpm #Calculate the duration of a sixteenth note #Setting it global because we need it in later functions # the sixteenthnoteduration is the duration of a quarternote devided by for # we need the 16thnote because we are building a grid with 1616thnotes global sixteenthNoteDuration sixteenthNoteDuration = quarterNoteDuration / 4.0 sixteenthNoteDuration = float(sixteenthNoteDuration) #ask the user how many notes to play.. print("how many notes?") global aantalnoten aantalnoten = input("please enter how many notes?") aantalnoten = int(aantalnoten) #1 timestamp = 1 16thnote durarion --> the actual time depends on BPM #0.25*4 = 1 = 1 * 16thnote = 1 16thnote playtime in seconds #the actual playtime of the quarternote depends on the BMP. print("please enter note duration..") print("0.25 = 16th") print("0.5 = 8th") print("1 = 4th") print("2 = 2h") print("4 = 1") #1 16e is (60/bpm)/4 for i in range(int(aantalnoten)): if i == 0: notelengthvalues.append(0) container = input() container = float(container) notelengthvalues.append(container * 4) print(notelengthvalues) #the first time timeadd is 0 so the pprogram does not crash # the timeadd variable is ment to add the next notevalue in millseconds # to the totaltime.. this will then become the new totaltime (all the #notevalue's combined. This number is to be subtracted from equal time) timeAdd = 0 for timestamp in notelengthvalues: totalTime = timestamp * sixteenthNoteDuration timestamps.append(totalTime + timeAdd) timeAdd = timestamps[-1] # CALL THE FUNCTION WITH THE GIVEN INPUT durationsToTimestamps16th() #------------------------------------------------------- # please enter the number of loops and store int loops = input("enter number of loops: ") loops = int(loops) #FUNCTION THAT PLAYS THE SAMPLE WITH THE INDEX def playAndloopSample(): # i = 0 = get the first index of the timestamps list i = 0 for loop in range(0, loops): #look at the first value in timestamps lst (0) timestamp = timestamps[i] # start the clock startTime = time.time() keepPlaying = True # while keepplaying is true: run the whileloop that plays the timestamps list # play the sequence while keepPlaying: # retrieve current time currentTime = time.time() # check if the timestamp's time is passed #check if currenttime is equal to the current item in the timestamps list if(currentTime - startTime >= timestamp): #play a random sample from the samples list samples[random.randint(0,1)].play() print(timestamp) # make the index run trough the timestamps list each itteration one position i = i+1 if i > aantalnoten: # if this point in the code is reached set keepPlaying to false and the sequence is compleet #start new loop if loop int is not full yet keepPlaying = False #the i = 1 is used so the 0 in the durations lst get used only the first loop i = 1 # retrieve the next timestamp else: # if not.. take next item from the durations list timestamp = timestamps[i] else: # wait for a very short moment time.sleep(0.001) playAndloopSample()
import sys # Algoritmo tradicional de fibonacci def fibonacci_recursivo(n): if n == 0 or n == 1: return 1 return fibonacci_recursivo( n - 1 ) + fibonacci_recursivo( n - 2 ) # Algoritmo fibonacci pero inyectado con programación dinámica. En esta ocasión, guardamos en # valores en memoria los cálculos ya hechos para que en vez de volver a calcular, el algoritmo los # re-utilice y optimice el tiempo de ejecución total de la función. def fibonacci_dinamico(n, memo = {}): if n == 0 or n == 1: return 1 try: return memo[n] except KeyError: resultado = fibonacci_dinamico(n-1, memo) + fibonacci_dinamico(n-2, memo) memo[n] = resultado return resultado if __name__ == "__main__": sys.setrecursionlimit(10002) n = int(input('Escoge un número: ')) #resultado = fibonacci_recursivo(n) resultado = fibonacci_dinamico(n) print(resultado)
idades = 0 dividir = 0 while(True): idade = int(input()) if idade<0: break else: idades+=idade dividir+=1 media = float(idades/dividir) print("{:.2f}".format(media))
x = int(input()) b = x z = int(input()) if z <= x: while True: z = int(input()) if z>x: break cont = 1 while True: cont+=1 a = x b+=1 x = a+b if x >z: break print(cont)
n = float(input()) if n > 100.01: print('Fora de intervalo') elif n >= 0 and n <= 25.00: print('Intervalo [0,25]') elif n >= 25.01 and n <= 50.00 : print('Intervalo (25,50]') elif n >= 50.01 and n <= 75.00: print('Intervalo (50,75]') elif n >= 75.01 and n <= 100.00: print('Intervalo (75,100]') else: print('Fora de intervalo')
quant = int(input()) for quantidade in range(1,quant+1): s,r = input().split() #1 if s == "tesoura" and r == "papel": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "tesoura" and s == "papel": print("Caso #{}: Raj trapaceou!".format(quantidade)) #2 elif s == "papel" and r == "pedra": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "papel" and s == "pedra": print("Caso #{}: Raj trapaceou!".format(quantidade)) #3 elif s == "pedra" and r == "lagarto": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "pedra" and s == "lagarto": print("Caso #{}: Raj trapaceou!".format(quantidade)) #4 elif s == "lagarto" and r == "Spock": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "lagarto" and s == "Spock": print("Caso #{}: Raj trapaceou!".format(quantidade)) #5 elif s == "Spock" and r == "tesoura": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "Spock" and s == "tesoura": print("Caso #{}: Raj trapaceou!".format(quantidade)) #6 elif s == "tesoura" and r == "lagarto": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "tesoura" and s == "lagarto": print("Caso #{}: Raj trapaceou!".format(quantidade)) #7 elif s == "lagarto" and r == "papel": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "lagarto" and s == "papel": print("Caso #{}: Raj trapaceou!".format(quantidade)) #8 elif s == "papel" and r == "Spock": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "papel" and s == "Spock": print("Caso #{}: Raj trapaceou!".format(quantidade)) #9 elif s == "Spock" and r == "pedra": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "Spock" and s == "pedra": print("Caso #{}: Raj trapaceou!".format(quantidade)) #10 elif s == "pedra" and r == "tesoura": print("Caso #{}: Bazinga!".format(quantidade)) elif r == "pedra" and s == "tesoura": print("Caso #{}: Raj trapaceou!".format(quantidade)) elif s == r: print("Caso #{}: De novo!".format(quantidade))
n = int(input()) if n % 2 == 0: n = n + 1 else: n = n print("%d"% n) for i in range(1,6): n += 2 print("%d"% n)
ho = int(input()) lista = [] for i in range(ho): lista.append("Ho") lista[-1] = "Ho!" print(" ".join(lista))
# A list is a collection which is ordered and changeable. In Python lists are written with square brackets. thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist) # You access the list items by referring to the index number # Print the second item of the list print("The second element of list are:" + thislist[1]); # Negative indexing means beginning from the end, -1 refers to the last item, # -2 refers to the second last item etc. # Print the last item of the list print("The last element of list are:" + thislist[-1] ); # You can specify a range of indexes by specifying where to start and where to end the range. # When specifying a range, the return value will be a new list with the specified items. # Return the third, fourth, and fifth item print("The 3rd 4th and 5th item of list are:"); print(thislist[2:5]); # This example returns the items from the beginning to "orange" print(thislist[:4]); # This example returns the items from "cherry" and to the en print(thislist[2:]); # Specify negative indexes if we want to start the search from the end of the list print(thislist[-4:-1]); # To change the value of a specific item, refer to the index number thislist[1] = "blackcurrant"; print(thislist); # You can loop through the list items by using a for loop for item in thislist: print(item); # To determine if a specified item is present in a list use the in keyword if "apple" in thislist: print("Yes, 'apple' is in the fruits list") else: print("No, 'apple' is not in the fruits list") #To determine how many items a list has, use the len() function txt = "The length of list are {}"; length = len(thislist); print(txt.format(length)); # To add an item to the end of the list, use the append() method thislist.append("pineapple"); print(thislist); # To add an item at the specified index, use the insert() method thislist.insert(0,"Delicious Apple"); print(thislist); # The remove() method removes the specified item thislist.remove("orange"); print(thislist); # The pop() method removes the specified index, (or the last item if index is not specified thislist.pop(); print(thislist); # The del keyword removes the specified index thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist) # The del keyword can also delete the list completely del thislist; # print(thislist); # The clear() method empties the list thislist = ["apple", "banana", "cherry"]; thislist.clear(); print(thislist); # You cannot copy a list simply by typing list2 = list1, # because: list2 will only be a reference to list1, # and changes made in list1 will automatically also be made in list2. # There are ways to make a copy, one way is to use the built-in List method copy(). # Make a copy of a list with the copy() method thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist) # Another way to make a copy is to use the built-in method list() # Make a copy of a list with the list() method mylist = list(thislist) print(mylist) # There are several ways to join, or concatenate, two or more lists in Python. # One of the easiest ways are by using the + operator. list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) # Another way to join two lists are by appending all the items from list2 into list1, one by one: list1 = ["a", "b" , "c"] list2 = [5, 6, 7] for x in list2: list1.append(x) print(list1) # you can use the extend() method, which purpose is to add elements from one list to another list list1 = ["a", "b" , "c"] list2 = [8, 9, 10] list1.extend(list2) print(list1) # It is also possible to use the list() constructor to make a new list thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist) # we can sort the list using the sort() method print(thislist.sort());
a = """This is a multi line string example"""; print(a); # Strings are Arrays a = "Hello, World!" print('The character at position 2 is ' + a[1]) # Slicing # we can return a range of characters by using the slice syntax. b = "Hello, World!" print("The characters of string b from position 2 - 5 excluding 5th position , starting from begining are : "+ b[2:5]); # we can use negative indexes to start the slice from the end of the string: print("The characters of string b from position 2 - 5 excluding 5th position , starting from end are : "+ b[-5:-2]); # To get the length of a string, use the len() function. length = len(b); text = "The lengt of string b is {}"; print(text.format(length)); # The strip() method removes any whitespace from the beginning or the end z = " Hello, World! " print(z.strip()) # returns "Hello, World!" # The lower() method returns the string in lower case: print("Print string z in lower case :" + z.lower()); # The upper() method returns the string in upper case: print("Print string z in upper case :" + z.upper()); # The replace() method replaces a string with another string: print("Replacing the letter h to j in string z"+ z.replace("H","J")); # The split() method splits the string into substrings if it finds instances of the separator print(a.split(",")) # returns ['Hello', ' World!']
''' Exercise 5.1: Fill lists with function values ''' import matplotlib.pyplot as plt from math import exp, pi,sqrt def f(x): y=(1/sqrt(2*pi))*exp(-0.5*x**2) return y initial=-4 h=8./40 xlist=[initial+i*h for i in range(41)] ylist=[f(x) for x in xlist] for x,y in zip(xlist,ylist): print(round(x,2),"\t",round(y,2)) plt.plot(xlist,ylist) plt.show()
import re from datetime import datetime class Average(object): def __init__(self, lst): self.lst = lst def average(self): """ Function calculates the average of numbers stored in list lst """ # average avg = float(sum(self.lst)) / len(self.lst) if avg < 6: print "Low Average" elif avg > 12: print "High Average" else: print "Medium Average" @classmethod def initWithString(cls): s_str = raw_input ("Enter a string of mixed letters and numbers: ") return cls([int(x) for x in re.findall("\d+",s_str)]) #create and return an instance of cls i.e. Average def article(s_str): lst = s_str.split("/") date_string = lst[3]+"-"+lst[2]+"-"+lst[1] article_date = datetime.strptime(date_string, "%d-%m-%Y") d = datetime.today() diff = d - article_date return (lst[4],date_string,diff.days) #d=article("articles/2010/10/21/my_summer") #print d #lst=[2,5,10,16] #a=Average(lst) #a.average() #a=Average.initWithString() #a.average()
""" Bar and Tick Chart ------------------ How to layer a tick chart on top of a bar chart. """ # category: bar charts import altair as alt source = alt.pd.DataFrame( { "project": ["a", "b", "c", "d", "e", "f", "g"], "score": [25, 57, 23, 19, 8, 47, 8], "goal": [25, 47, 30, 27, 38, 19, 4], } ) bar = ( alt.Chart(source) .mark_bar() .encode(x="project", y="score") .properties(width=alt.Step(40)) # controls width of bar. ) tick = ( alt.Chart(source) .mark_tick( color="red", thickness=2, size=40 * 0.9, ) # controls width of tick. .encode(x="project", y="goal") ) bar + tick
# -*- coding: utf-8 -*- """ Created on Tue Oct 17 21:14:09 2017 @author: Isik """ class Reader_Writer(): """ A helper class that contains all the necessary tools for reading and writing text or binary files. Attributes: ifs: Input File Stream. ofs: Output File Stream. """ ifs = None ofs = None def __init__(self): """ Default Constructor """ pass def set_ifs(self, InputFileName = "DEFAULT.txt", ReadFormat = 'r'): """ A useful function to set the input file stream. Arguments: InputFileName: The the name of the file to be read from. ReadFormat: The python-interpreted argument for reading files. """ try: self.ifs = open(InputFileName, ReadFormat) except OSError: InputFileName = str(InputFileName) self.ifs = open(InputFileName, ReadFormat) def set_ofs(self, OutputFileName = "DEFAULT.txt", WriteFormat = 'w'): """ A useful function to set the output file stream. Arguments: InputFileName: The the name of the file to write to. WriteFormat: The python-interpreted argument for writing files. """ try: self.ofs = open(OutputFileName, WriteFormat) except OSError: OutputFileName = str(OutputFileName) self.ofs = open(OutputFileName, WriteFormat) def open_files(self, InputFileName = "DEFAULT.txt", OutputFileName = "DEFAULT.txt", ReadFormat = 'r', WriteFormat = 'w' ): """ Opens Input and Output files Arguments: ReadFormat: The python-interpreted argument for reading files WriteFormat: The python-interpreted argument for writing files """ self.set_ifs(InputFileName, ReadFormat) self.set_ofs(OutputFileName, WriteFormat) def close_files(self): """ Closes Input and Output files """ self.ifs.close() self.ofs.close()
import numpy as np a = np.array([1,2,3,4,5,6]) print(a) print("*************************") print(a.ndim) print("*************************") #making an matrix with dtype = int16 b = np.array([[1,2,3],[11,33,55], [88,99,66],[45,55,77]],dtype='int16') #Dimensions of array print(b,b.ndim) print("*************************") #getting shape of the array print (b.shape) print("*************************") #getting type print(b.dtype) print("*************************") #getting size of elements in numpy array print(b.itemsize) print(a.itemsize) print("*************************") #getting number of elements in (a,b) array print(a.size,b.size) #getting number of bytes print("*************************") print(a.nbytes,b.nbytes) print("*************************") c = np.array([1.0,2.0,3.0]) print(c.nbytes)
''' Tic Tac Toe is a game for two players, X and O, who take turns marking the spaces in a 3x3 grid. The player who succeds in placing three of their marks in a horizontal, vetical, or diagonal row wins the game. ''' positons = ['0', '1', '2', '3', '4', '5', '6', '7', '8'] print ("Player 1 insert your name") player01 = input() print ("Player 2 insert your name") player02 = input() winCondition = False while winCondition != True : print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player01 + " choose the position: from 0 to 8") line = int(input()) positons[line] = "O"; if positons[0] == positons[1] == positons[2] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player01 + " is the Winner!!") break elif positons[0] == positons[4] == positons[8] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player01 + " is the Winner!!") break elif positons[0] == positons[3] == positons[6] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player01 + " is the Winner!!") break elif positons[1] == positons[4] == positons[7] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player01 + " is the Winner!!") break elif positons[2] == positons[4] == positons[6] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player01 + " is the Winner!!") break elif positons[2] == positons[5] == positons[8] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player01 + " is the Winner!!") break elif positons[3] == positons[4] == positons[5] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player01 + " is the Winner!!") break elif positons[6] == positons[7] == positons[8] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player01 + " is the Winner!!") break print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player02 + " choose the position: from 0 to 8") line = int(input()) positons[line] = 'X'; if positons[0] == positons[1] == positons[2] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player02 + " is the Winner!!") elif positons[0] == positons[4] == positons[8] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player02 + " is the Winner!!") elif positons[0] == positons[3] == positons[6] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player02 + " is the Winner!!") elif positons[1] == positons[4] == positons[7] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player02 + " is the Winner!!") elif positons[2] == positons[4] == positons[6] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player02 + " is the Winner!!") elif positons[2] == positons[5] == positons[8] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player02 + " is the Winner!!") elif positons[3] == positons[4] == positons[5] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player02 + " is the Winner!!") elif positons[6] == positons[7] == positons[8] : winCondition = True print ('|{pos11}|{pos12}|{pos13}|\n|{pos21}|{pos22}|{pos23}|\n|{pos31}|{pos32}|{pos33}|'.format(pos11 = positons[0], pos12 = positons[1], pos13 = positons[2], pos21 = positons[3], pos22 = positons[4], pos23 = positons[5], pos31 = positons[6], pos32 = positons[7], pos33 = positons[8])) print (player02 + " is the Winner!!")
import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web style.use('ggplot') #validate the date #validate the symbol company_name = input ('please enter the company\'s symbol: ') startdate_entry = input('please choose your start date (YYYY,MM,DD): ').split(',') enddate_entry = input('please choose your end date (YYYY,MM,DD): ').split(',') start = dt.datetime(int(startdate_entry[0]),int(startdate_entry[1]),int(startdate_entry[2])) end = dt.datetime(int(enddate_entry[0]),int(enddate_entry[1]),int(enddate_entry[2])) df = web.DataReader(company_name, 'yahoo', start, end) print (df.head()) def date_validation:
# Comment print "Okay" # YaCmnt print "Test" print 25 + 30 / 6 print 100 - 25 * 3 % 4 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print 3 + 2 < 5 - 7 print "" cars = 100 space_in_a_car = 4.0 drivers = 30 passangers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passangers_per_car = passangers / cars_driven print "Cars :", cars print "Drivers :", drivers print "Non-driven :", cars_not_driven print "Capacity", carpool_capacity print "Passangers", passangers tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print tabby_cat print persian_cat print backslash_cat print fat_cat print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % ( age, height, weight)
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] fruit = set(basket) print(fruit) a = set('abracadabra') print(a) b = set('alacazam') res1 = a - b # letters in a but not in b print(res1) res2 = a | b # letters in either a or b print(res2) res3 = a & b # letters in both a and b print(res3) res4 = a ^ b # letters in a or b but not both print(res4) #set comprehension a1 = {x for x in 'abracadabra' if x not in 'abc'} print(a1)
class Queue: def __init__(self): self.queue = list() def enqueue(self, value): self.queue.append(value) def dequeue(self): return self.queue.pop(0) def isEmpty(self): return len(self.queue) == 0 def size(self): return len(self.queue) #driver code queue = Queue() queue.enqueue(4) queue.enqueue(5) queue.enqueue(6) queue.enqueue(57) queue.enqueue(45) queue.enqueue(10) while not queue.isEmpty(): print(queue.dequeue())
''' Leetcode problem 3 : Longest Substring Without Repeating Characters difficulty level : medium Given a string s, find the length of the longest substring without repeating characters. Example 1: # Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. Example 4: Input: s = "" Output: 0 Constraints: 0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces.''' class Solution: def lengthOfLongestSubstring(self, s: str) -> int: l = [0] d ={} for i,j in enumerate(s): if j not in d : l.append(l[-1] + 1) else : l.append(min(l[-1]+ 1,i-d[j] )) d[j] = i print(l) return max(l)
""""""""""""""""""""""""""" 여러 줄 문자열 """"""""""""""""""""""""""" number = int(input("정수 입력> ")) # if 조건문과 여러 줄 문자열(1) if number % 2 == 0: print("""\ 입력한 문자열은 {}입니다. {}는 짝수입니다.""".format(number, number)) else: print("""\ 입력한 문자열은 {}입니다. {}는 홀수입니다.""".format(number, number)) # if 조건문과 여러 줄 문자열(2) if number % 2 == 0: print("""입력한 문자열은 {}입니다. {}는 짝수입니다.""".format(number, number)) else: print("""입력한 문자열은 {}입니다. {}는 홀수입니다.""".format(number, number)) # if 조건문과 여러 줄 문자열(2) if number % 2 == 0: print("입력한 문자열은 {}입니다.\n{}는 짝수입니다.".format(number, number)) else: print("입력한 문자열은 {}입니다.\n{}는 홀수입니다.".format(number, number)) # if 조건문과 여러 줄 문자열(3) if number % 2 == 0: print(( "입력한 문자열은 {}입니다.\n" "{}는 짝수입니다." ).format(number, number)) else: print(( "입력한 문자열은 {}입니다.\n" "{}는 홀수입니다." ).format(number, number)) # 문자열의 join() 함수 if number % 2 == 0: print("\n".join([ "입력한 문자열은 {}입니다.", "{}는 짝수입니다." ]).format(number, number)) else: print("\n".join([ "입력한 문자열은 {}입니다.", "{}는 홀수입니다." ]).format(number, number)) # textwrap 모듈의 dedent 함수 import textwrap number = int(input("정수 입력> ")) if number % 2 == 0: print(textwrap.dedent("""\ 입력한 문자열은 {}입니다. {}는 짝수입니다.""").format(number, number)) else: print(textwrap.dedent("""\ 입력한 문자열은 {}입니다. {}는 홀수입니다.""").format(number, number)) # 괄호로 문자열 연결하기 test = ( "이렇게 입력해도 " "하나의 문자열로 연결되어 " "생성된답니다." ) print("test:", test) print("type(test):", type(test))
""""""""""""""""""""""" 복합 대입 연산자 """"""""""""""""""""""" # 숫자 복합 대입 연산자 number = 100 number += 10 # number = number + 10 number += 20 number += 30 print("number:", number) # 숫자 계산 후 대입 # 문자열 복합 대입 연산자 string = "안녕하세요" string += "!" string += "?" print("string:", string) # 문자열 연결 후 대입 string = "안녕하세요" string *= 3 print("string:", string) # 문자열 반복 후 대입
""""""""""""""""""""""""""" 코드에 이름 붙이기 """"""""""""""""""""""""""" # 주석이 붙어 있는 코드 number_input = input("숫자 입력> ") radius = float(number_input) print(2 * 3.14 * radius) # 원의 둘레 print(3.14 * radius * radius) # 원의 넓이 # 함수를 횔용한 코드 PI = 3.14 def number_input(): output = input("숫자 입력> ") return float(output) def get_circumference(radius): return 2 * PI * radius def get_circle_area(radius): return PI * radius * radius radius = number_input() print(get_circumference(radius)) print(get_circle_area(radius))
""""""""""""""""""""""" while 반복문 """"""""""""""""""""""" # for i in range(10) i = 0 while i < 10: print("{}번째 반복입니다.".format(i)) i += 1 # 해당하는 값 모두 제거하기 ls = [1, 2, 1, 2, 5, 8, 9] value = 2 # list 내부에 value 가 있다면 반복 while value in ls: ls.remove(value) print(ls) # 시간을 기반으로 반복하기 import time unix_time = time.time() # UNIX time : 1970년 1월 1일 0시 0초 기준으로 몇 초 # 5초 동안 반복 output = 0 target_tick = unix_time + 5 while unix_time < target_tick: output += 1 print("5초 동안 {}번 반복했습니다.".format(output))
list1 = [12,-75, 64,-14] for i in list1: if i > 0: print (i) list2 =[ 12,14,-95, 3] for i in list2: if i <=0: list2.remove(i) print (list2)
#!/bin/python3 import sys def designerPdfViewer(h, word): #Calculate the ASCII value of character in the word. For [a - z], the ASCII value is [97 - 122]. Subtract 97 from the obtained ##value and substitute it as the index of array h stating height of each character alphabetically. ##Calculate the width of the word. width_of_the_word = len(word) width_of_a_character = 1 ##Calculate the maximum possible height of the word maximum_height_of_word = 1 for index in range(0, width_of_the_word, 1): if h[ord(word[index]) - 97] > maximum_height_of_word: maximum_height_of_word = h[ord(word[index]) - 97] ##The time complexity is O[N]. Space complexity is O[N] ##Calculate the area of the highlighted word area = width_of_the_word * width_of_a_character * maximum_height_of_word return(area) if __name__ == "__main__": h = list(map(int, input().strip().split(' '))) word = input().strip() result = designerPdfViewer(h, word) print(result)
#!/bin/python3 import sys def findDigits(n): numberString = str(n) result = 0 for i in range(0, len(numberString), 1): digit = int(numberString[i]) if digit!= 0: if n % digit == 0: result = result + 1 return(result) if __name__ == "__main__": t = int(input().strip()) for a0 in range(t): n = int(input().strip()) result = findDigits(n) print(result)
print('DAY 4 TASK') a=b=c=300 print('data type of a,b,c :',type(a)) print('divide a value by 10') print(a,'/','10','=',a/10) print('multiply b value by 50') print(b,'*','50','=',b*50) print('add c value by 60') print(c,'+','60','=',c+60) code='143js' print('Sting:',code) print('length of the string:',len(code)) s1='3' s2='G' c1=code.replace(s1,s2) print('New string:',c1) a,b=13,5.9 print('a=',a,'b=',b) print('data type of a :',type(a)) print('data type of b :',type(b)) a=float(a) b=int(b) print('value of a and b after type converstion:') print('a=',a,'b=',b) print('data type of a after type conversion:',type(a)) print('data type of b after type conversion:',type(b)) print('****TASK COMPLETED*****')
from utils import morse_dict, get_morse_key from morse_functions import morse_to_audio def text_to_morse(text): morse_text = '' text = text.upper() for char in text: if morse_dict.get(char) == None and char != ' ' and char != '\n': print('Caracter \"' + char + '\" eh invalido. Abortando.\n') exit(1) if char != ' ' and char != '\n': morse_text += morse_dict[char] morse_text += '000' else: morse_text += '0000' morse_text = morse_text[:-3] return morse_text def text_to_audio(text): morse_to_audio(text_to_morse(text))
def evaluate_tests(func, tests): '''Evaluate func against tests. Test example: tests = [{'input': {'nums': [34, 1]}, 'output': 1}] ''' print('Evaluating tests') for i in range(len(tests)): if func(tests[i]['input']['nums']) == tests[i]['output']: result = 'PASS' else: result = 'FAILED' print('TEST:', i, result)
import abc class PacketPayload(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def bytes(self) -> bytes: """Get packet payload in bytes format""" @abc.abstractmethod def __len__(self): """Get packet payload length""" @staticmethod @abc.abstractmethod def parse_bytes(data: bytes): """From bytes create a object payload"""
import sys class Graph(object): """ A simple undirected, weighted graph """ def __init__(self): self.nodes = set() self.edges = {} self.distances = {} def add_node(self, value): self.nodes.add(value) def add_edge(self, from_node, to_node, distance): self._add_edge(from_node, to_node, distance) self._add_edge(to_node, from_node, distance) def _add_edge(self, from_node, to_node, distance): self.edges.setdefault(from_node, []) self.edges[from_node].append(to_node) self.distances[(from_node, to_node)] = distance def get_source(): edge_count = 0 edge_weights = dict() line_count = 0 node_count = 0 node_set = set() node_finish = 0 node_start = 0 result = dict() for line in sys.stdin: line = line.replace('\n', '') if line_count == 0: node_count, edge_count = line.split(' ') else: try: node_from, node_to, weight = line.split(' ') edge_weights.update({(int(node_from), int(node_to)): int(weight)}) node_set.add(int(node_from)) node_set.add(int(node_to)) except ValueError: node_start, node_finish = line.split(' ') line_count += 1 result.update({'edge_weights': edge_weights}) result.update({'node_set': node_set}) result.update({'node_count': node_count}) result.update({'edge_count': edge_count}) result.update({'node_start': node_start}) result.update({'node_finish': node_finish}) return result def dijkstra(graph, initial_node): visited = {initial_node: 0} path = {} nodes = set(graph.nodes) while nodes: min_node = None for node in nodes: if node in visited: if min_node is None: min_node = node elif visited[node] < visited[min_node]: min_node = node if min_node is None: break nodes.remove(min_node) cur_wt = visited[min_node] for edge in graph.edges[min_node]: wt = cur_wt + graph.distances[(min_node, edge)] if edge not in visited or wt < visited[edge]: visited[edge] = wt path[edge] = min_node return visited, path def shortest_path(graph, initial_node, goal_node): distances, paths = dijkstra(graph, initial_node) route = [goal_node] while goal_node != initial_node: route.append(paths[goal_node]) goal_node = paths[goal_node] route.reverse() return route def node_check(data): node_set = data.get('node_set') node_start = data.get('node_start') node_finish = data.get('node_finish') if (int(node_start) in node_set) and (int(node_finish) in node_set): return 0 else: return -1 def count_distance(path, edge_weights): summarize = 0 for i in range(len(path)): try: node_first = path[i] node_second = path[i + 1] summarize += edge_weights.get((node_first, node_second)) except IndexError: break return summarize if __name__ == '__main__': source = get_source() error = node_check(source) if error == -1: print(error) sys.exit(0) g = Graph() g.nodes = set(range(1, int(source.get('node_count')) + 1)) for r in source.get('edge_weights'): g.add_edge(r[0], r[1], source.get('edge_weights').get(r)) try: shortest_path = shortest_path(g, int(source.get('node_start')), int(source.get('node_finish'))) except KeyError: error = -1 print(error) sys.exit(0) print(count_distance(shortest_path, source.get('edge_weights')))
from display import Display import font from keyboard import Keyboard from linked_list import LinkedList from memory import Memory from random import randint from typing import List SPEED = 10 class Cpu: def __init__(self, memory: Memory, display: Display, keyboard: Keyboard): self.memory = memory font.load(self.memory) self.display = display self.keyboard = keyboard """ Two special purpose 8-bit registers used as delay and sound timers. When these registers are non-zero they auto decrement at 60Hz. """ self.delay_timer: int = 0 self.sound_timer: int = 0 # 16-bit program counter that stores the currently executing address. self.program_counter: int = self.memory.offset """ A linked-list that stores 16-bit addresses that the interpreter should return to when finished with a subroutine. CHIP-8 allows for up to 16 levels of nested subroutines, but for simplicity we will allow for unlimited. """ self.stack: LinkedList = LinkedList() self.is_paused: bool = False self.waiting_for_key: bool = False def cycle(self): for _ in range(SPEED): if not self.is_paused and not self.waiting_for_key: instruction = self.fetch_instruction() self.decode_instruction(instruction) # TODO: Sound if not self.is_paused and not self.waiting_for_key: self.update_timers() self.keyboard.process_keys() self.display.update() def update_timers(self): if self.delay_timer > 0: self.delay_timer -= 1 if self.sound_timer > 0: self.sound_timer -= 1 def fetch_instruction(self) -> int: left = self.memory.read_ram(self.program_counter) right = self.memory.read_ram(self.program_counter + 1) instruction = left << 8 | right print(str(self.program_counter) + ": " + str(hex(instruction))) # An instruction is 2 bytes, so ready the counter for the next instruction. self.program_counter += 2 return instruction def decode_instruction(self, instruction: int): x = (instruction & 0x0F00) >> 8 y = (instruction & 0x00F0) >> 4 if instruction == 0x000: print(f"Hit instruction: {hex(instruction)}; Pausing.") return self.PAUSE() if instruction & 0xF000 == 0x0000: if instruction == 0x00E0: return self.CLS() elif instruction == 0x00EE: return self.RET() elif instruction & 0xF000 == 0x1000: return self.JP(instruction & 0x0FFF) elif instruction & 0xF000 == 0x2000: return self.CALL(instruction & 0x0FFF) elif instruction & 0xF000 == 0x3000: return self.SE_byte(x, instruction & 0x00FF) elif instruction & 0xF000 == 0x4000: return self.SNE_byte(x, instruction & 0x00FF) elif instruction & 0xF000 == 0x5000: if instruction & 0x000F == 0x0000: return self.SE(x, y) elif instruction & 0xF000 == 0x6000: return self.LD_byte(x, instruction & 0x00FF) elif instruction & 0xF000 == 0x7000: return self.ADD_byte(x, instruction & 0x00FF) elif instruction & 0xF000 == 0x8000: if instruction & 0x000F == 0x0000: return self.LD(x, y) elif instruction & 0x000F == 0x0001: return self.OR(x, y) elif instruction & 0x000F == 0x0002: return self.AND(x, y) elif instruction & 0x000F == 0x0003: return self.XOR(x, y) elif instruction & 0x000F == 0x0004: return self.ADD(x, y) elif instruction & 0x000F == 0x0005: return self.SUB(x, y) elif instruction & 0x000F == 0x0006: return self.SHR(x) elif instruction & 0x000F == 0x0007: return self.SUBN(x, y) elif instruction & 0x000F == 0x000E: return self.SHL(x) elif instruction & 0xF000 == 0x9000: if instruction & 0x000F == 0x0000: return self.SNE(x, y) elif instruction & 0xF000 == 0xA000: return self.LD_I(instruction & 0x0FFF) elif instruction & 0xF000 == 0xB000: return self.JP_V0(instruction & 0x0FFF) elif instruction & 0xF000 == 0xC000: return self.RND(x, instruction & 0x00FF) elif instruction & 0xF000 == 0xD000: return self.DRW(x, y, instruction & 0x000F) elif instruction & 0xF000 == 0xE000: if instruction & 0x00FF == 0x009E: return self.SKP(x) elif instruction & 0x00FF == 0x00A1: return self.SKNP(x) elif instruction & 0xF000 == 0xF000: if instruction & 0x00FF == 0x0007: return self.LD_Vx_DT(x) elif instruction & 0x00FF == 0x000A: return self.LD_Vx_K(x) elif instruction & 0x00FF == 0x0015: return self.LD_DT(x) elif instruction & 0x00FF == 0x0018: return self.LD_ST(x) elif instruction & 0x00FF == 0x001E: return self.ADD_I(x) elif instruction & 0x00FF == 0x0029: return self.LD_F(x) elif instruction & 0x00FF == 0x0033: return self.LD_B(x) elif instruction & 0x00FF == 0x0055: return self.LD_I_Vx(x) elif instruction & 0x00FF == 0x0065: return self.LD_Vx_I(x) print(f"Invalid Instruction: {hex(instruction)} at pc: {self.program_counter}") self.PAUSE() # Close the program. def PAUSE(self): self.is_paused = True # Clear the display. def CLS(self): self.display.clear() # Return from a subroutine. def RET(self): self.program_counter = self.stack.pop() # Jump to address. def JP(self, address: int): self.program_counter = address # Call subroutine at address. def CALL(self, address: int): self.stack.push(self.program_counter) self.program_counter = address # Skip next instruction if Vx == byte. def SE_byte(self, x: int, byte: int): if self.memory.V(x) == byte: self.program_counter += 2 # Skip next instruction if Vx != byte. def SNE_byte(self, x: int, byte: int): if self.memory.V(x) != byte: self.program_counter += 2 # Skip next instruction if Vx == Vy. def SE(self, x: int, y: int): if self.memory.V(x) == self.memory.V(y): self.program_counter += 2 # Set byte to Vx. def LD_byte(self, x: int, byte: int): self.memory.set_V(x, byte) # Add byte to Vx. def ADD_byte(self, x: int, byte: int): sum = self.memory.V(x) + byte self.memory.set_VF(sum > 255) self.memory.set_V(x, sum & 0x00FF) # Set Vy to Vx. def LD(self, x: int, y: int): self.memory.set_V(x, self.memory.V(x) + self.memory.V(y)) # Or Vy with Vx. def OR(self, x: int, y: int): self.memory.set_V(x, self.memory.V(x) | self.memory.V(y)) # And Vy with Vx. def AND(self, x: int, y: int): self.memory.set_V(x, self.memory.V(x) & self.memory.V(y)) # XOR Vy with Vx. def XOR(self, x: int, y: int): self.memory.set_V(x, self.memory.V(x) ^ self.memory.V(y)) # Add Vy to Vx. def ADD(self, x: int, y: int): sum = self.memory.V(x) + self.memory.V(y) self.memory.set_VF(sum > 255) self.memory.set_V(x, sum & 0x00FF) # Subtract Vy from Vx. def SUB(self, x: int, y: int): self.memory.set_VF(self.memory.V(x) > self.memory.V(y)) # TODO: Check to see if this works if negative self.memory.set_V(x, (self.memory.V(x) - self.memory.V(y)) & 0x00FF) # Shift Vx right by 1. def SHR(self, x: int): self.memory.set_VF(self.memory.V(x) & 0b00000001 == 1) self.memory.set_V(x, self.memory.V(x) >> 1) # Subtract Vx from Vy def SUBN(self, x: int, y: int): self.memory.set_VF(self.memory.V(y) > self.memory.V(x)) # TODO: Check to see if this works if negative self.memory.set_V(x, (self.memory.V(y) - self.memory.V(x)) & 0x00FF) # Shift Vx left by 1. def SHL(self, x: int): self.memory.set_VF(self.memory.V(x) & 0b10000000 == 0b10000000) self.memory.set_V(x, self.memory.V(x) << 1) # Skip next instruction if Vx != Vy. def SNE(self, x: int, y: int): if self.memory.V(x) != self.memory.V(y): self.program_counter += 2 # Set I to address. def LD_I(self, address: int): self.memory.I = address # Jump to location address + V0. def JP_V0(self, address: int): self.JP(address + self.memory.V(0x0)) # Set Vx to (random number [0, 255] anded with byte). def RND(self, x: int, byte: int): self.memory.set_V(x, randint(0, 255) & byte) # Display n-byte sprite starting at memory location I at (Vx, Vy). def DRW(self, x: int, y: int, n: int): sprite: List[int] = [] for i in range(n): sprite.append(self.memory.read_ram(self.memory.I + i)) collision: bool = self.display.draw_sprite(self.memory.V(x), self.memory.V(y), sprite) self.memory.set_VF(collision) # Skip next instruction if key of Vx is pressed. def SKP(self, x: int): print("TODO: SKP - Keyboard") # Skip next instruction if key of Vx is not pressed. def SKNP(self, x: int): print("TODO: SKNP - Keyboard") # Set Vx to delay timer. def LD_Vx_DT(self, x: int): self.memory.set_V(x, self.delay_timer) # Wait for a key press, store the value of the key in Vx. def LD_Vx_K(self, x: int): print("TODO: LD_Vx_K - Keyboard") # Set delay timer = Vx. def LD_DT(self, x: int): self.delay_timer = self.memory.V(x) # Set sound timer = Vx. def LD_ST(self, x: int): self.sound_timer = self.memory.V(x) # Add Vx to I. def ADD_I(self, x: int): self.memory.I += self.memory.V(x) # Set I to the location of the sprite for digit Vx. def LD_F(self, x: int): self.memory.I = self.memory.V(x) * 5 # Each sprite is 5 bytes long. # Set memory locations I, I+1, and I+2 to BCD representation of Vx. def LD_B(self, x: int): value = self.memory.V(x) hundreds, value = divmod(value, 100) tens, value = divmod(value, 10) ones, value = divmod(value, 1) self.memory.write_ram(self.memory.I + 0, hundreds) self.memory.write_ram(self.memory.I + 1, tens) self.memory.write_ram(self.memory.I + 2, ones) # Store registers v0 through Vx in memory starting at location I. def LD_I_Vx(self, x: int): for i in range(x + 1): self.memory.write_ram(self.memory.I + i, self.memory.V(i)) # Read registers V0 through Vx from memory starting at location I. def LD_Vx_I(self, x: int): for i in range(x + 1): self.memory.set_V(i, self.memory.read_ram(self.memory.I + i))
# -*- coding: utf-8 -*- from config import * import showing as sh from random import randrange as rndt class Barrier: """ этот класс связан со всем, что связано с преградами """ def __init__(self, name, race, health, force, x, y): self.x = x self.y = y self.health = health self.race = race self.force = force self.color = "orange" self.rect_id = sh.Entity(x, y, self.color) def coords(self): self.coordinates = self.rect_id.coords() list_of_barriers = [] a = 0 b = 0 for i in map: for j in i: if a == WIDTH: a = 0 b += step if j == "*": temp = Barrier("b" + str(3), "barrier", 1, 0, a, b) temp.coords() list_of_barriers.append(temp) a += step #for barrier in range(count_of_barriers): # temp = Barrier("b" + str(barrier), "barrier", 1, 0, rndt(0, WIDTH, step), rndt(0, HEIGHT, step)) # temp.coords() # list_of_barriers.append(temp)
n=int(input()) while (n != 0): px=input() py=input() while (n): x=input() y=input() if (x == px or y == py): print("divisa") elif (x < px and y > py): print("NO") elif (x > px and y > py): print("NE") elif (x > px and y < py): print("SE") else (x < px and y < py): print("SO") n-=1
# Implement a class to hold room information. This should have name and # description attributes. class Room: def __init__(self, name, desc, items): self.name = name self.desc = desc self.items = items def __str__(self): return f"\nYou are here -> {self.name}\n\n {self.desc}\n\n Items in this room: {self.items}" def remove_item(self, item): self.items.remove(item) def add_item(self, item): self.items.append(item)
from abc import ABC class Weapon(ABC): def __init__(self, name): self.name = name class Bow(Weapon): def __init__(self): super().__init__(name='bow') self.arrows = 5 class Sword(Weapon): def __init__(self): super().__init__(name='sword')
import click from flask.cli import with_appcontext def register_commands(app): """Add commands to the line command input. Parameters: app (flask.app.Flask): The application instance. """ app.cli.add_command(add_user_command) @click.command('user') @click.argument('username') @click.argument('password') @with_appcontext def add_user_command(username: str, password: str) -> None: """This function is executed through the 'user' line command. e.g.: flask user demo demo Parameters: username (str): The username of the user. password (str): The password of the user. """ add_user(username, password) def add_user(username: str, password: str) -> None: """Create a new user. Parameters: username (str): The username of the user. password (str): The password of the user. """ from app.model import User from app.model import UserRepository user_repository = UserRepository() user = User(username=username, password=password) is_invalid = user_repository.is_invalid(user) if not is_invalid: user_repository.save(user) click.echo('User created.') else: click.echo('Could not validate the user:') for i in is_invalid: key = list(i.keys())[0] click.echo("{}: {}".format(key, i[key]))
# __author__ = 'Vlad' # l = [] # a = 1,2,"3",4,"5" # for item in a: # l.append(int(item)*3) # print l[int(item)-1]+10 largest = 0 smallest = 0 while True: try: num = (raw_input("Enter a number: ")) if num == "done": break elif num == 'a': raise ValueError if num > largest: largest = num elif num<smallest: smallest = num print num except ValueError: print "Invalid input" print "Maximum is", largest print "Minimum is", smallest
# -*- coding: utf-8 -*- """ Utilises the power of matplotlib / seaborn to visualise data sets @author: A00209408 """ import matplotlib.pyplot as plt import matplotlib.dates as mdates import calculationFunctions as stat def apply_boxplot(ax: plt.Axes, data: [], title, y_label) -> plt.Axes: """ Creates and returns a boxplot of the data for the user to show or save at his leisure Parameters ---------- ax : TYPE The Axes to draw on data : [] The data to visualise title : TYPE Title of the visualisation y_label : TYPE Title for the Y label Returns ------- ax : Axis with the new box plot created """ x_offset = .2 y_offset = 1.5 ax.set_title(title) ax.set_ylabel(y_label) box_plot = ax.boxplot(data) for i, line in enumerate(box_plot['medians']): x, y = line.get_xydata()[1] text = ' Median = {:.2f}\n '.format(stat.calculate_median(data)) ax.annotate(text, xy=(x + .05, y)) q1 , q3 = stat.calculate_quartiles(data) for line in box_plot['boxes']: # Right top corner x, y = line.get_xydata()[4] text = x,y, '%.2f' % x, text = ' Q1 = {:.2f}\n '.format(q1) ax.annotate(text, xy=(x+ x_offset, y - y_offset)) # Right bottom corner x, y = line.get_xydata()[3] text = ' Q3 = {:.2f}\n '.format(q3) ax.annotate(text, xy=(x + x_offset, y-y_offset)) return ax def visualise_by_time(ax: plt.Axes, data_time: list(), data_values: list(), title, y_label) -> plt.Axes: """ Visualises the data_values by the timeline month minor year major X axis Parameters ---------- ax : plt.Axes The Axes to draw on. data_time : list() Time values for the diagram. data_values : list() Values to map. title : TYPE title of the diagram. y_label : TYPE y axis label description for the mapped data. Returns ------- ax : Axis with the new box plot created """ ax.set_title(title) # Set up dates for X axis dates = mdates.datestr2num(data_time) months = mdates.MonthLocator() ax.xaxis.set_minor_locator(months) ax.set_xlabel("Timeline") # Set up Y axis values ax.set_ylabel(y_label) #Plot the data ax.plot_date(dates, list(data_values), marker = ",", linestyle="-") return ax def visualise_scatter_plot_correlation(ax: plt.Axes, data_values_x: list(), data_values_y: list(), title, x_label, y_label) -> plt.Axes: """ Visualises the correlation between two parameters Parameters ---------- ax : plt.Axes The Axes to draw on. data_values_x : list() value for the x axis data_values_y : list() value for the y axis title : TYPE title for the graph x_label : TYPE label for the x axis y_label : TYPE label for the y axis Returns ------- ax : axes """ ax.set_title(title) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.scatter(data_values_x, data_values_y, marker =".") return ax
import copy def find_empty_cell(board: list): # self-explanatory? for y in range(9): for x in range(9): if board[y][x] == 0: return x, y return -1 def print_board(board: list): # print-board in console print(" ", end="") for i in range(9): print(i, end=" ") print("") for i, row in enumerate(board): print(i, "", row) # check if current board is solvable? def can_solve(board: list): # ok so this algorithm looks messy because I wanted to reuse the is_possible() function instead of # reinventing the wheel, fuk for y in range(9): for x in range(9): if board[y][x] != 0: result = None val = board[y][x] # store value at cell board[y][x] = 0 # clear the cell if is_possible(board, val, x, y): # check if value at cell would be valid result = True else: result = False board[y][x] = val # restore the cell's value if not result: # if that value would've been illegal, return fase return (x, y) return None # check if putting val at (x, y) cell is possible def is_possible(board: list, val: int, x: int, y: int): # check row for val for row in range(9): if board[row][x] == val: return False # check column for col in range(9): if board[y][col] == val: return False # calculate offsets for sub-grid # a neat little trick exploiting truncating division, I hate that Python uses // for this x_off = (x // 3) * 3 y_off = (y // 3) * 3 # finally check the sub-grid for y in range(3): for x in range(3): if board[y_off + y][x_off + x] == val: return False return True def solve_sudoku(board: list): # find current empty position... pos = find_empty_cell(board) # if there is no empty cell, YAY! board is solved! if pos == -1: return True # ...else get empty cell position (x, y) = pos for val in range(1, 10): # check each value for possibility... if is_possible(board, val, x, y): # ...if possible, set the value board[y][x] = val # please ignore these, not part of algorithm... solve_sudoku.engine.render(x, y, (0, 255, 0, 255)) solve_sudoku.engine.handle_input() # continue algorithm.. # ...recursively call the function again if solve_sudoku(board): return True board[y][x] = 0 # ignore... solve_sudoku.engine.render(x, y, (255, 0, 0, 255)) solve_sudoku.engine.handle_input() # --- # if no value is valid at position, return False, go to previous stack frame.. # hence triggering backtracking... return False
from datetime import datetime import csv,EmpObject def writeToFile(startDate,endDate): ''' Reads the data from Employee table based on the inputs (startDate & endDate), writes to the CSV file. ''' empf=open('Employee_'+ datetime.now().strftime("%y%m%d%H%M%S") + '.csv','w') writer=csv.writer(empf) writer.writerow(('Employee_Id','Employee_Name','Employee_Age', 'Employee_Designation','Hired_On')) for instance in EmpObject.empSession.query(EmpObject.Employee).filter(EmpObject.Employee.hired_on.between(startDate,endDate)): try: writer.writerow((instance.id,instance.employee_name,instance.employee_age,instance.employee_designation,instance.hired_on)) except ValueError as err: print('Bad Row : ',instance) print('Reason : ',err) continue # Skips to the next row empf.close() startDate=input("Enter the Start date : ") endDate=input("Enter the End date : ") writeToFile(startDate,endDate)
# -*- coding: utf-8 -*- """ Created on Thu Jun 29 11:50:30 2017 @author: Moondra """ import threading import time total = 4 def creates_items(): global total for i in range(10): time.sleep(2) print('added item') total += 1 print('creation is done') def creates_items_2(): global total for i in range(7): time.sleep(1) print('added item') total += 1 print('creation is done') def limits_items(): #print('finished sleeping') global total while True: if total > 5: print ('overload') total -= 3 print('subtracted 3') else: time.sleep(1) print('waiting') creator1 = threading.Thread(target = creates_items) creator2 = threading.Thread(target = creates_items_2) limitor = threading.Thread(target = limits_items, daemon = True) print(limitor.isDaemon()) creator1.start() creator2.start() limitor.start() creator1.join() creator2.join() print('our ending value of total is' , total)
#juan gines ramis vivancos practica 2 ejercicio 3 #saber si un numero es par o inpar print('introduce tu numero') numero = int (input()) mod = numero%2 if mod == 1: print('tu numero es inpar') else: print('tu numero es par')
#Escribe un programa que lea el nombre de una persona y un carácter, le pase estos # datos a una función que comprobará si dicho carácter está en su nombre. # El resultado de dicha función lo imprimirá el programa principal por pantalla. def contar(nombre,carater): if carater in nombre: return(caracter, 'esta en tu nombre') else: return(caracter, 'no esta en tu nombre') nombre=str(input('dime tu nombre')) caracter=str(input('dime un caracter')) print(contar(nombre,caracter))
#juan gines ramis vivancos #Escribe un programa que te pida palabras y las guarde en una lista. #Para terminar de introducir palabras, simplemente pulsa Enter. #El programa termina escribiendo la lista de palabras. palabras=[] print('introduce una palabra') palabra=str(input()) palabras.append(palabra) while palabra !='': print('introduce otra palabra') palabra=str(input()) palabras.append(palabra) palabras.remove('') print(palabras)
#juan gines ramis vivancos p6ej2 #Escribe un programa que te pida números #y los guarde en una lista. Para terminar de introducir número,simplemente #escribe “Salir”.El programa termina escribiendo la lista de números. print('introduce un numero') numero=int(input()) numeros=[] numeros.append(numero) while numero!=('salir'): print('introduce otro numero') numero=str(input()) if numero!=('salir'): numeros.append(numero) print(numeros)
print('introduce el dia') dia = int(input()) print('introduce el mes') mes = int(input()) print('introduce el año') año = int(input()) if año>=0: if 0<mes<=12: if mes == 1 or 3 or 5 or 7 or 8 or 10 or 12: if 0<dia<=31: print('fecha correcta') else: print('fecha incorrecta') elif mes == 4 or 6 or 9 or 11: if 0<dia<=30: print('fecha correcta') else: print('fecha incorrecta') elif mes == 2: if 0<dia<=29: print('fecha correcta') else: print('fecha incorrecta') else: print('fecha incorrecta') else: print('fecha incorrecta')
#Escribe un programa que lea una frase, y la pase como parámetro a un procedimiento. #El procedimiento contará el número de vocales (de cada una) que aparecen, #y lo imprimirá por pantalla. def contar_vocal(frase): vocales=['a','e','i','o','u'] contador=[0,0,0,0,0] for i in range(len(vocales)): for j in range(len(frase)): if frase[j]==vocales[i]: contador[i]+=1 print('hay',contador[0],'a') print('hay',contador[1],'e') print('hay',contador[2],'i') print('hay',contador[3],'o') print('hay',contador[4],'u') frase=str(input('dame una frase: ')) contar_vocal(frase)
#juan gines ramis vivancos P4ej5 #Pida al usuario un importe en euros y diga si el cajero automático le #puede dar dicho importe utilizando el mismo billete y el más grande print('introduce la cantidad que quieres sacar') cantidad = int(input()) if cantidad%500 == 0: (billete) = cantidad/500 print('te doy' ,billete, 'billetes de 500') elif cantidad%200 == 0: billete = cantidad/200 print('te doy' ,billete, 'billetes de 200') elif cantidad%100 == 0: (billete) = cantidad/100 print('te doy' ,billete, 'billetes de 100') elif cantidad%50 == 0: (billete) = cantidad/50 print('te doy' ,billete, 'billetes de 50') elif cantidad%20 == 0: (billete) = cantidad/20 print('te doy' ,billete, 'billetes de 20') elif cantidad%10 == 0: (billete) = cantidad/10 print('te doy' ,billete, 'billetes de 10') elif cantidad%5 == 0: (billete) = cantidad/5 print('te doy',billete, 'billetes de 5') else: print('no puedo darte esta cantidad')
import turtle as t n = 50 t.bgcolor("black") t.color("green") t.speed(0) for x in range(n): t.circle(80) t.lt(360/n)
print ("Today we will start the installation fase.") answer = input ("Starting the installation. Do you confirm?") if answer == " start": print ("OK! Starting installation.") else: quit() print ("0%...................100%") "/n" print("Installing questions...") "/n" print("Installing question 1/6...") "/n" print("Installing question 6/6...") "/n" print ("Installation over. You will be redirected to the setup page.") answer = input ("Do you confirm the setup process starting?") if answer == " start": print ("Redirecting...") else: quit() answer = input ("To confirm the terms of services, say accept.") if answer == " accept": print("Redirecting......") else: quit() print("Nice!") name = input ("Insert your name here.") if name == name: print() print("Lets start!") answer = input ("What does .py mean?") if answer == " python file": print() else: print("Incorrect!") answer = input ("What is JS?") if answer == " JavaScript": print() print("Congrats you got the 2nd one right!") print() else: print() print("Incorrect.") print() answer = input ("What is the meaning for C# (how do you say it)?") if answer == " C Sharp": print("You are better than 29 percent of players. This will get harder and harder.") else: print("Incorrect, sorry!") answer = input ("What is the new version of python?") if answer == " 3.6": print("Only 2 left!") else: print ("Incorrect, sorry.") answer = input ("What is the new version of the coding software HTML?") if answer == " 5": print("Amazing") print("Question 5/6") else: print ("Incorrect, sorry!") answer = input ("Last question, how many people exist in the world?") if answer == " 7.8 bilion": print("WOW! You got all six!") else: print ("Incorrect, sorry.") answer = input ("Here are the credits. Say start to start the credits.") if answer == " start": print("Developer: Spooky Eleven#8872") "/n" print("Question maker: Spooky Eleven#8872") "/n" print("Copyright owner: Spooky Eleven#8872") "/n" print("Spooky Eleven#8872's channel: www.youtube.com/c/IsabelRibeiro2021") "/n" print("Spooky Eleven#8872 is not plausible for any damages to your computer.") "/n" print("For support message Spooky Eleven#8872 on discord, or shoot an email to fakeeurovisionsongcontest@gmail.com")
import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument("--x", type=int, help="the base") parser.add_argument("--y", type=int, help="the exponent") args = parser.parse_args() print(args.x**args.y) print(args.x + args.y) if __name__ == "__main__": main()
# -*- coding: utf-8-*- import xlrd def readExcel(filename,sheetname=''): #文件位置 ExcelFile=xlrd.open_workbook(filename) #获取目标EXCEL文件sheet名 # print(ExcelFile.sheet_names()) #若有多个sheet,则需要指定读取目标sheet例如读取sheet2 #sheet2_name=ExcelFile.sheet_names()[1] #获取sheet内容【1.根据sheet索引2.根据sheet名称】 #sheet=ExcelFile.sheet_by_index(1) if not sheetname=='': sheet=ExcelFile.sheet_by_name(sheetname) else: sheet=ExcelFile.sheet_by_index(0) #打印sheet的名称,行数,列数 # print(sheet.name,sheet.nrows,sheet.ncols) return sheet
answer = input("How old are you?") print(answer, "years old!") for i in (a, b, c, d, e): print(i)
poem=("Roses are red, violets are blue, I am really cute, but you look like poo;)") no=("idc", poem) answer = input("Hello!") player = 1 WW = 1 power = "Yes" or "No" choice = "Yes" or "No" op=input("How are you?") if not op.isnumeric(): print("Interesting!") elif op.isnumeric(): print("Wow") response=input("What school do you go to?") print("I've heard of", response) option=input("Would you like to hear a poem?") print("Idc!", poem) age=input("How old am I?") if not age.isnumeric(): print("Correct!") elif age.isnumeric(): print("Nope...HAHAH!") tanswer=input("Let's play a game!") if player == 1: name = input("Im going on a new mission and I need back-up!!What is your name?") if name.isnumeric (): print("That's not a name. Type your name.") else: print("Hi," ,name) age =input("How old are you?") if not age.isnumeric(): print("That's not your age. Type your age.") age = int(age) else: print(age, "years old!") place =input("Where are you from?") if place.isnumeric(): print("That's not a place! What city or state are you from?") else: print("I've been to", place) power = input("Do you have any superpowers! Yes or No") if power.isnumeric(): print("Answer Yes or No!") if power == "No": print("Sorry, I couldn't use you during the trip") if power == "Yes": answer =input("What is it?") print(answer, "could really help me during my mission!") if answer.isnumeric(): print("That's not a super power!Bye") exit() else: power= input(answer, "could be very useful during my mission!Would you like to come? Yes or No?") if power == "Yes": print("Let's go!") exit() if power == "No": print("Oh well") print("My favorite is.... ") def myname(): name= "Z.I.O.N" print(name) myname() print("Bye!")
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Use Twitter API to grab user information from list of organizations; export text file Uses Twython module to access Twitter API """ import csv import sys import string import simplejson from twython import Twython #WE WILL USE THE VARIABLES DAY, MONTH, AND YEAR FOR OUR OUTPUT FILE NAME import datetime now = datetime.datetime.now() day=int(now.day) month=int(now.month) year=int(now.year) #FOR OAUTH AUTHENTICATION -- NEEDED TO ACCESS THE TWITTER API t = Twython(app_key='5HeBOrYw4NpLLSTSBNizTIrXe', #REPLACE 'APP_KEY' WITH YOUR APP KEY, ETC., IN THE NEXT 4 LINES app_secret='0frgT45TSKtNFZrIptXFs0ENWRUbANfDqevI9hudeUPOpnqeRL', oauth_token='127840133-7sVWM3NgWXSpnGPcniKn645DHCUUz6R9O0rLxeOB', oauth_token_secret='MdEb6NlaRqeGarBob7VY7QbQ3W93vJNcfzXlfUD2jhkqf') #NAME OUR OUTPUT FILE - %i WILL BE REPLACED BY CURRENT MONTH, DAY, AND YEAR outfn = "twitter_user_data_%i.%i.%i.csv" % (now.month, now.day, now.year) #NAMES FOR HEADER ROW IN OUTPUT FILE fields = ["id","screen_name","name","created_at","url","followers_count","description","location"] #INITIALIZE OUTPUT FILE AND WRITE HEADER ROW outfp = csv.writer(open(outfn, "wb")) outfp.writerow(fields) #REPLACE WITH YOUR LIST OF TWITTER USER IDS with open('twitter_following2.csv', 'rb') as csvfile: row_count = sum(1 for row in csvfile)-1 quotient=row_count/100 reste=row_count-quotient*100 print(row_count) if reste!=0: last_range=quotient+1 else: last_range=quotient for i in range(1,last_range+1): ids='' count_init=1+(i-1)*100 count_last=i*100 if count_last > row_count: count_last=row_count count=0 csvfile.seek(0) print("Process "+str(count_init)+" to "+str(count_last)+" out of "+str(row_count)) for row in csv.reader(csvfile): if count >=count_init and count <=count_last: ids+=row[0]+"," count+=1 #ACCESS THE LOOKUP_USER METHOD OF THE TWITTER API -- GRAB INFO ON UP TO 100 IDS WITH EACH API CALL #THE VARIABLE USERS IS A JSON FILE WITH DATA ON THE 32 TWITTER USERS LISTED ABOVE users = t.lookup_user(user_id = ids) #THE VARIABLE 'USERS' CONTAINS INFORMATION OF THE 32 TWITTER USER IDS LISTED ABOVE #THIS BLOCK WILL LOOP OVER EACH OF THESE IDS, CREATE VARIABLES, AND OUTPUT TO FILE for entry in users: row=[] for f in fields: row.append(entry[f]) outfp.writerow([unicode(s).encode("utf-8") for s in row]) print("Done!")
#!/usr/bin/env python #-*-coding:utf-8-*- ''' 给定一个整数数组 nums 和一个目标值 target, 请你在该数组中找出和为目标值的那 两个 整数, 并返回他们的数组下标 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] ''' #解法一 #解题思路:用字典模拟哈希求解,把索引序列添加到字典里["value":"index"] class Solution(): def twoSum(self,nums,target): dic = dict() for index,value in enumerate(nums): sub = target - value if sub in dic: return dic[sub],index else: dic[value]=index if __name__ == '__main__': nums = [2, 11, 7, 15] target = 9 s = Solution() print(s.twoSum(nums,target)) ''' 补充知识点 enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列, 同时列出数据和数据下标,一般用在 for 循环当中 ''' #对一个列表,既要遍历索引又要遍历元素时 #方法一,使用for循环 seq1 = ['one','two','three'] for i in range(len(seq1)): print(i,seq1[1]) #方法二,使用enumerate seq = ['one','two','three'] for i,element in enumerate(seq): print(i,element) #要统计文件的行数 #文件大时比较缓慢 count1 = len(open(filepath,'r').readlines()) #使用enumerate() count = 0 for index,line in enumerate(open(filepath,'r')): count+=1
from pychallenge.sort.bubble import bubble_sort def test_bubble_sort(): assert bubble_sort([]) == [] assert bubble_sort([0]) == [0] assert bubble_sort([-1, 0, 1]) == [-1, 0, 1] assert bubble_sort([1, 0, -1]) == [-1, 0, 1] assert bubble_sort(["a", "c", "b"]) == ["a", "b", "c"] assert bubble_sort(["aardvark", "cat", "banana"]) == ["aardvark", "banana", "cat"] assert bubble_sort('aardvark') == sorted('aardvark')
from enum import Enum from random import random, randrange class PrimeTest(Enum): TRIAL_DIVISION = 0 MILLER_RABIN = 1 class PrimeGenerator: def __init__(self): pass def __del__(self): pass @staticmethod def is_prime(number: int, algorithm: PrimeTest = PrimeTest.MILLER_RABIN) -> bool: if algorithm == PrimeTest.MILLER_RABIN: return PrimeGenerator._miller_rabin(number) elif algorithm == PrimeTest.TRIAL_DIVISION: return PrimeGenerator._trial_division(number) @staticmethod def _trial_division(number: int): i: int = 2 while i < number: if number % i == 0: return False i += 1 return True @staticmethod def _miller_rabin(number: int, iterations: int = 10): if number == 2 or number == 3: return True if not number & 1: return False def _check(a, s, d, n): x = pow(a, d, n) if x == 1: return True for i in range(s - 1): if x == n - 1: return True x = pow(x, 2, n) return x == n - 1 s = 0 d = number - 1 while d % 2 == 0: d >>= 1 s += 1 for i in range(iterations): a = randrange(2, number - 1) if not _check(a, s, d, number): return False return True @staticmethod def get_prime(digits: int = 10) -> int: number: int = round(random() * (10 ** digits)) while not PrimeGenerator.is_prime(number): number += 1 return number
#包含一个学生类 #一个sayhello的函数 #一个打印语句 class Student(): def __init__(self, name='NoName', age=18): self.name = name self.age = age def say(self): print("hello,my name is '{}'".format(self.name)) def sayHello(): print("非常高兴遇见你") # 此判断语句建议一直作为程序的入口 if __name__ == '__main__': print("我是模块p01呀,你特么的叫我干毛")
#1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. #Об окончании ввода данных свидетельствует пустая строка. def __userinfo__(): global u_inf u_inf = [] while True: u_inp = input("Print in what you think about Python: ") u_inf.append(u_inp) if not u_inp: print("End of input") break for i in u_inf: print(i) return print(f"The info you've just sent to the targeted file is: {u_inf}") print(__userinfo__()) task1 = open("Less5.txt", "w", encoding="utf-8") for line in u_inf: content = task1.write(line + '\n') task1.close() #2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, #количества слов в каждой строке. t_c = open(r"C:\Users\staln\PycharmProjects\Py_basics\engl_proverbs.txt", "r", encoding="utf-8") c = 1 for l in t_c: #length = len(l) #print(f"- row {c} has {length} bt") #c += 1 print(f"Total lines qty: {c - 1}") #3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. #Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней #величины дохода сотрудников. from statistics import mean with open("Employees.txt", "r", encoding="utf-8") as file: salaries = [] for empl in file: name, salary = empl.split(' ') salary = float(salary) if salary < 20_000: print("Salaries below the average:") print(name, salary) salaries.append(salary) print("The average salary level is: ", round(mean(salaries), 2)) ''' Создать (не программно) текстовый файл со следующим содержимым: One — 1 Two — 2 Three — 3 Four — 4 Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться в новый текстовый файл. ''' a = open('En_Ru.txt', 'r+', encoding="utf-8") c = [] for i in a: c.append(i) for i in c: c[0] = 'Один - 1\n' c[1] = 'Два - 2\n' c[2] = 'Три - 3\n' c[3] = 'Четыре - 4\n' b = open('Ru.txt', 'w', encoding="utf-8") b.writelines(c) b = open('Ru.txt', 'r', encoding="utf-8") for i in b: print(i, end='') a, b.close() #5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. #Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. with open("num.txt", 'w', encoding='utf-8') as n: arr = [] for i in range(20, 100, 10): n.write(str(i)) n.write(' ') arr.append(i) print(f"The new list which will be added to the {n} file:\n{arr}") o = open("num.txt", 'r', encoding='utf-8') con = o.readline().split() s = [] for el in con: el = int(el) s.append(el) res = sum(s) print(f"The sum of numbers in the file is: {res}") o.close() ''' 6. Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, содержащий название предмета и общее количество занятий по нему. Вывести словарь на экран. ''' with open("task6.txt", "r", encoding="utf-8") as t: my_list = [] for i in t.read().split('\n'): v = i.split(":") my_list.append(v) my_list = dict(my_list) print(my_list) #7. Создать (не программно) текстовый файл, в котором каждая строка должна содержать данные о фирме: название, #форма собственности, выручка, издержки. import json profit = {} pr = {} prof = 0 prof_aver = 0 i = 0 with open("TryJson.txt", 'r') as file: for el in file: name, firm, revenue, losses = el.split() profit[name] = int(revenue) - int(losses) if profit.setdefault(name) >= 0: prof = prof + profit.setdefault(name) i += 1 if i != 0: prof_ave = prof / i print(f'Average profit - {prof_ave:.2f}') else: print(f'Average profit is 0') pr = {'Average profit': round(prof_ave)} profit.update(pr) print(f'Companies profit each - {profit}') with open("TryJson.json", 'w') as write_js: json.dump(profit, write_js) js_str = json.dumps(profit) print(f'A file with extension ".json" has been created: \n ' f' {[js_str]}')
# -*- coding: utf-8 -*- """ Created on Fri Jun 9 14:15:48 2017 Script that runs a query on actors and genres tables and stores the result in a json format. @author: Jaya """ import json hostname = 'localhost' username = 'postgres' password = '******' database = 'movie' def doQuery( conn ) : #connect to Postgres cur = conn.cursor() movies = [] jsondata = [] mgenre, mgenreid = [], [] myear= [] tyear, tgenre = [], [] #READ actors from actor table cur.execute("SELECT distinct m.year from movies m ") for year in cur.fetchall(): myear.append(year) print(myear) #READ genres from genre table cur.execute("SELECT distinct g.genre, g.idgenres from genres g ") for genre, genreid in cur.fetchall(): mgenre.append(genre) mgenreid.append(genreid) length = len(myear) * len(mgenre) print(mgenre) print(mgenreid) i = 0 #For each actor get the list of movies he/she has acted in for x in myear: if(i==0): i = 1 else: x=str(x).strip().split('(')[1] x=str(x).strip().split(',')[0] for y in mgenre: tyear.append(x) tgenre.append(y) moviesin = [] cur.execute("Select m.title from movies m join movies_genres mg on m.idmovies = mg.idmovies join genres g on mg.idgenres=g.idgenres where g.idgenres = (select ge.idgenres from genres ge where ge.genre = %s) and m.year = %s group by m.title, m.year, g.genre order by m.year",(y,x) ) for title in cur.fetchall(): #moviesin list has all movies by a particular actor moviesin.append( str(title).strip().split('\'')[1]) #append the list for each actor into the main list movies.append(moviesin) #add the actor details and movie details to a single list- jsondata length = (len(myear)-1) * len(mgenre) print(length) for x in range(0,length): jsondata.append({"year": int(tyear[x]), "genre": tgenre[x], "movies": movies[x],"number_of_movies" : len(movies[x])}) with open('genres.json', 'w') as f: for x in jsondata: f.write("{}\n".format(json.dumps(x))) print ("Using psycopg2…") import psycopg2 myConnection = psycopg2.connect( host=hostname, user=username, password=password, dbname=database ) doQuery( myConnection ) myConnection.close()
class Dog: species = "mammal" def __init__(self,the_sound): self.sound_made = the_sound def sound(self): print(self.sound_made) def bite (self): self.sound() print("Bite") def identify_yourself(self): print("I am a" + self.species) class Bulldog(Dog): def run(self): speed = "10km/hr" print("i run at 10km/hr") my_dog = Dog("woof") my_second_dog = Dog("woooooooooooffffffff") my_bulldog = Bulldog("wooorrrf") my_bulldog.sound()
# Herencia y poliformismo class Figura: # #atributos def __init__(self, lado, tamanio): self.nLados = lado self.tLado = tamanio # metodos def mostarNlados(self): print('El numero de ', type, ' es:', self.nLados) def mostrarTlados(self): print('El tamaño del lado es:', self.tLado) def perimetro(self): print('El perimetro es:', self.nLados * self.tLado) class Rectangulo(Figura): pass class Triangulo(Figura): pass # Encapsulación class Estudiante: # Atributos __nombre = ' ' __correo = ' ' __password = ' ' def __init__(self): self.__nombre = ' ' self.__correo = ' ' self.__password = ' ' def inNombre(self, nombre): self.__nombre = nombre def inCorreo(self, correo): self.__correo = correo def inPassword(self, password): self.__password = password def mostrarNombre(self): print('El nombre es: ') return self.__nombre def mostrarCorreo(self): print(f'El correo es: ') return self.__correo def mostrarPassword(self): print(f'La contraseña es: ') return self.__password if __name__ == '__main__': r1 = Rectangulo(4,2) t1 = Triangulo(3,10) r1.perimetro() t1.perimetro() e = Estudiante() e.inNombre('Alfonso Sanchez') e.inCorreo('correo@prueba.com') e.inPassword('1234') print(e.mostrarNombre()) print(e.mostrarCorreo()) print(e.mostrarPassword())
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): if root == None: return 0 if root.left == None and root.right == None: return 1 elif root.left == None and root.right != None: return 1 + self.maxDepth(root.right) elif root.left != None and root.right == None: return 1 + self.maxDepth(root.left) else: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) node4 = TreeNode(15) node5 = TreeNode(7) node3 = TreeNode(20) node3.left = node4 node3.right = node5 node2 = TreeNode(9) node1 = TreeNode(3) node1.left = node2 node1.right = node3 s1 = Solution() print(s1.maxDepth(node1))
types_of_people = 10 x = f"There are {types_of_people} types of people" binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}" print(x) print(y) hilarious = False joke_evaluation = "Isnt the joke funny {} {}" print(joke_evaluation.format(hilarious, "Wooahh")) # the other way of printing out stuff in a pre formatted string is by this function called format... w = "This is the left side of the text" e = ".... and this is the next part" print(w+e) # hence the plus thing of java also works like in java..... print(e+w) # this is the opposite thing of it now here..