text
stringlengths
37
1.41M
numerals = { 'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1 } def roman_numeral_converter(rn): value = 0 rnLength = len(rn) indexes = set([]) for char in (x for x in range(rnLength) if not x in indexes): if (char+1) == rnLength: value += numerals[rn[char]] else: if numerals[rn[char]] < numerals[rn[char+1]]: value += (numerals[rn[char+1]] - numerals[rn[char]]) indexes.add(char) indexes.add(char+1) else: value += numerals[rn[char]] indexes.add(char) return value if __name__ == "__main__": print(roman_numeral_converter('XIV')) print(roman_numeral_converter('CCXLV'))
import random def random_not_in_list(n, l): # Find the set of numbers that are not in the list not_in_list = set(range(n)) - set(l) # If there are no numbers not in the list, return None if not not_in_list: return None # Otherwise, choose a random number from the set of numbers not in the list return random.choice(list(not_in_list)) n = 10 l = [1, 2, 3, 4, 5] if __name__ == '__main__': print(random_not_in_list(n, l))
import re allowed_characters = [ 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', ',', ';', ':' ] terminals = [ '.', '?', '!', '‽' ] def sentence_checker(sentence): for x in re.findall(r'\s+', sentence): if x != ' ': return("Invalid Sentence1") for char in sentence[1:-1]: if char not in allowed_characters[:52:2] and char not in terminals and char != ' ': return("Invalid Sentence2") if not sentence[0].isupper(): return("Invalid Sentence3") if not sentence[-1] in terminals: return("Invalid Sentence4") elif not sentence[-2] in allowed_characters[:52]: return("Invalid Sentence5") else: return(sentence) if __name__ == "__main__": print(sentence_checker("How are your balls?"))
import heapq def find_minimum_spanning_tree(pipes): edges = [] for node1, connections in pipes.items(): for node2, cost in connections.items(): edges.append((cost, node1, node2)) heapq.heapify(edges) visited = set() result = [] while edges: cost, node1, node2 = heapq.heappop(edges) if node1 in visited and node2 in visited: continue visited.add(node1) visited.add(node2) result.append((node1, node2, cost)) return result pipes = { 'plant': {'A': 1, 'B': 5, 'C': 20}, 'A': {'C': 15}, 'B': {'C': 10}, 'C': {} } if __name__ == '__main__': minimum_spanning_tree = find_minimum_spanning_tree(pipes) total_cost = sum(cost for _, _, cost in minimum_spanning_tree) print(minimum_spanning_tree) print(total_cost)
''' Exercicios propostos ''' numero = input('informe um numero ') try: numero = int(numero) if numero % 2 == 0: print('O numero digitado e par') else: print('O numero digitado nao e par') except: print('ERRO') ''' if not numero.isdigit(): print(f'{numero} não é um número inteiro') else: numero = int(numero) if not numero % 2 == 0: print(f'{numero} é ímpar') else: print(f'{numero} é par') '''
''' Tabuada e calculadora ''' sair_programa = 0 while sair_programa == 0: cal = 'Calculadora e Tabuada' print(f'{cal:=^40}') opcao = input('O programa a seguir mostra a tabuada e possui uma pequena calculadora\n' 'digite: \n(1) para calculadora \n(2) para a tabuada \n(0)para sair do programa ') if not opcao.isnumeric(): print('Você precisa digitar um número') continue opcao = int(opcao) matriz = [] soma = 0 sub = 0 mult = 0 div = 0 tamanho = 0 if opcao == 1: qtd_valores = input('Você escolheu calculadora, quantos valores prentende digitar ') if not qtd_valores.isnumeric(): print('Você precisa digitar um número') continue qtd_valores = int(qtd_valores) cont = 1 while qtd_valores > 0: valor = input(f'informe o {cont}º valor ') valor = int(valor) matriz.append(valor) cont += 1 qtd_valores -= 1 sinal = input('informe o sinal da operacao, digite: \n(+) adicao ' '\n(-) subtracao \n(*) multiplicacao \n(/) para divisao') if sinal == '+': tamanho = len(matriz) x = 0 soma = 0 while x < tamanho: soma = soma + matriz[x] x += 1 print(f'soma = {soma}') elif sinal == '-': tamanho = len(matriz) x = 0 sub = 0 while x < tamanho: if x == 0: sub = sub + matriz[x] else: sub = sub - matriz[x] x += 1 print(f'subtração = {sub}') elif sinal == '*': tamanho = len(matriz) x = 0 mult = 1 while x < tamanho: mult = mult * matriz[x] x += 1 print(f'multiplicaçao = {mult}') elif sinal == '/': tamanho = len(matriz) x = 0 div = 0 while x < tamanho: if x == 0: div = div + matriz[x] else: div = div / matriz[x] x += 1 print(f'divisão = {div}') elif opcao == 2: tab = input('informe a tabuada que pretende verificar: ') if not tab.isnumeric(): print('Você precisa digitar um número') continue if tab.isdigit(): tab = int(tab) x = 1 while x <= 12: result = tab * x print(f'{tab} * {x} = {result}') x += 1 else: if opcao == 0: sair_programa = 1
#!/usr/bin/python3 class Person: def __init__(self,firstname,lastname): self.firstname=firstname self.lastname=lastname p1=Person("zhang","bo") print(p1.firstname) print(p1.lastname)
# -*- coding: utf-8 -*- """ Created on Fri Apr 18 11:18:10 2014 Flavius Josephus February 19, 2009 Flavius Josephus was a famous Jewish historian of the first century, at the time of the destruction of the Second Temple. According to legend, during the Jewish-Roman war he was trapped in a cave with a group of forty soldiers surrounded by Romans. Preferring death to capture, the Jews decided to form a circle and, proceeding around it, to kill every third person remaining until no one was left. Josephus found the safe spot in the circle and thus stayed alive. Write a function josephus(n,m) that returns a list of n people, numbered from 0 to n-1, in the order in which they are executed, every mth person in turn, with the sole survivor as the last person in the list. What is the value of josephus(41,3)? In what position did Josephus survive? @author: Stephen """ def josephus(n, m): L = [] stack = range(n) pos = 1 while len(stack) > 1: p = stack.pop(0) if pos%m==0: #killed L.append(p) else: #not killed --> back in the stack stack.append(p) pos+=1 return L+[stack[0]] print josephus(41, 3)
class Payroll: def __init__(self, name): self.name = name self.hours = 0 self.overHours = 0 self.wage = 0 def setEarnings(self, wage): self.wage = wage def setHours(self,hours): self.hours = hours def setOvertime(self,hours = 0): self.overHours = hours def calculate(self): print(self.name , ' worked:') print(self.hours , ' normal hours @ ' , self.wage , ' for $' , self.hours * self.wage) print(self.overHours , ' overtime hours @ ' , self.wage * 1.5 , ' for $' , self.overHours * 1.5 * self.wage) print('Totalling: $' , ((self.wage*1.5*self.overHours)+ (self.wage*self.hours)) , ' for One Weeks work') alex = Payroll('Alex') alex.setEarnings(14.20) alex.setHours(4.2) alex.setOvertime(1) alex.calculate()
while True: gender = input('Gender: ') if(gender == 'M' or gender == 'm' or gender == 'f' or gender == 'F'): break else : print('Please try again') print('You are: ',gender)
#!/usr/bin/env python3 """Pluralsight Module 4 thing Usage: py Module4_Modularity <URL> """ import sys from urllib.request import urlopen def get_items_from_url(url): """Fetch a list of words from a URL. Args: url: The url of a UTF-8 text document Returns: A list of string containing the words from the document """ with urlopen(url) as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) return story_words def print_items(items): """Prints a list of items Args: items: The list of items(iterable) Returns: None """ for word in items: print(word) def main(url): """Prints each word from a text document from a URL Args: url: The url of a UTF-8 text document Returns: None """ result = get_items_from_url(url) print_items(result) #this is how we can execute our function as a script if __name__=='__main__': main(sys.argv[1])
from population import Population from chromosome import Chromosome if __name__ == '__main__': file = open("knapsack_3.txt", "r") line = file.readline() number_of_items, knapsack_capacity = map(int, line.split()) items = [] while True: line = file.readline() if not line: break items.append(list(map(int, line.split()))) number_of_generations = 100 population_size = 1000 children_size = 2000 tournament_size = 5 mutation_rate = 0.02 Chromosome.set_number_of_items(number_of_items) Chromosome.set_knapsack_capacity(knapsack_capacity) Chromosome.set_items(items) population = Population(population_size, children_size, tournament_size, mutation_rate) population.generate(number_of_generations) population.print_answer() population.show_statistics()
#1. Jeu du jackpot import random jackpot = random.randint(1,1001) essai = input("Proposer un nombre : ") for nb_essai in range(10): print("Essai n° ",nb_essai+1,":") if jackpot > int(essai): print("le jackpot est plus grand") else: print("le jackpot est plus petit") if jackpot == int(essai): print("Bravo vous avez gagné ! ") exit() else: print("Proposer un nouvel essai") essai = input("Numéro choisi : ") essai= int(essai) print("Raté ! Vous n'avez plus d'essais.. Le jackpot était : ",jackpot)
#x = int(input( " entrez un nombre : ")) #def est_pair(x): # if x%2 == 0: # return True # else: # return False #nombre = est_pair(x) #print(nombre) #def supprimer_voyelles(string): # trans = str.maketrans('', '', 'aàäâAeééèêëEiiîïIoOuUôö') # return string[0] + string[1:].translate(trans) #def calculer_vitesse(t,m): # return round((3.6*(m/t)),1) #def est_palindrome(texte): # texte = texte.lower() # a_retirer = { # 'a': ['à', 'ã', 'á', 'â'], # 'e': ['é', 'è', 'ê', 'ë'], # 'i': ['î', 'ï'], # 'u': ['ù', 'ü', 'û'], # 'o': ['ô', 'ö'], # 'y': ['ÿ'], # 'n': ['ñ'], # '' : [",", ".", ";", ":", "!", "/", "?","'",'"',"«", "»", " — ", "’", " ","-"] # } # for (cle, valeur) in a_retirer.items(): # for possibilite in valeur: # texte = texte.replace(possibilite, cle) # i = len(texte) # palindrome = "" # c = i - 1 # while c > -1: # palindrome += texte[(c-i)] # c -= 1 # if palindrome == texte: # return True # else: # return False def exchange_variables(var1,var2): var3=var2 var2=var1 var1=var3 return(var1,var2) print(exchange_variables(var2))
import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup def main(): #step 2 import the data from the site website = 'https://www.smartsheet.com/factory-manufacturing-automation' website_url = requests.get(website).text soup = BeautifulSoup(website_url, 'html.parser') #step 3 my_list = soup.find('ul') my_list2 = soup.find('ol') list_data = [] list_data2 = [] for listitem in my_list.findAll('li'): list_data.append(listitem.text) for listitem in my_list2.findAll('li'): list_data2.append(listitem.text) print(list_data) print(list_data2) ''' assessment: list items captured, but the usability is probably poor may want to find a website with actual tables to scrape ''' if __name__=="__main__": main()
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 2 + 2 4 >>> 3 * 10 30 >>> 100 - 10 90 >>> 25 / 5 5.0 >>> 10 / 3 3.3333333333333335 >>> 10 // 3 3 >>> print('Mijn naam is Elona') Mijn naam is Elona >>> naam = 'Elona' >>> print(naam) Elona >>> print(naam.upper()) ELONA >>> print(naam[0:2]) El >>> print(naam[::-1]) anolE >>> leeftijd = 20 >>> print('Hallo' + naam + 'ben je al' + str(leeftijd) + ' jaar?') HalloElonaben je al20 jaar? >>> print('Hallo ' + naam + ' ben je al' + str(leeftijd) + ' jaar?') Hallo Elona ben je al20 jaar? >>> print('Hallo ' + naam + ' ben je al ' + str(leeftijd) + ' jaar?') Hallo Elona ben je al 20 jaar? >>> leeftijd = leeftijd + 1 >>> leeftijd 21 >>> leeftijd-=1 >>> leeftijd 20 >>> if leeftijd < 18: ... hoelang_tot18jaar = 18 - leeftijd ... print('Over ' + str(hoelang_tot18jaar) + ' jaar wordt je 18') ... elif leeftijd > 18: ... hoelang_al18jaar = leeftijd - 18 ... print('Het is alweer ' + str(hoelang_al18jaar) + ' jaar geleden dat je 18 werd ;-)') ... else: ... print('Je bent precies ' + str(leeftijd) + ' jaar') ... Het is alweer 2 jaar geleden dat je 18 werd ;-) >>> from random import radint Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name 'radint' from 'random' (C:\Users\elona\AppData\Local\Programs\Python\Python38-32\lib\random.py) >>> from random import randint >>> randint(0,1000) 936 >>> willekeurig_getal = randint(0,1000) >>> willekeurig_getal 616 >>> print('Willekeurig getal tussen 0 en 1000: ' + str(willekeurig_getal)) Willekeurig getal tussen 0 en 1000: 616 >>> print('Willekeurig getal tussen 0 en 1000: ' + str(willekeurig_getal)) Willekeurig getal tussen 0 en 1000: 616 >>> willekeurig_getal 616 >>> willekeurig_getal 616 >>> randint(0,1000) 231 >>> willekeurig_getal = randint(0,1000) >>> willekeurig_getal 758 >>> willekeurig_getal 758 >>> from fatetime import datetime Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'fatetime' >>> from datetime import datetime >>> datum = fatetime.now() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'fatetime' is not defined >>> datum = datetime.now() >>> print(datum) 2020-09-09 12:31:43.834663 >>> datum.strftime('%A %d %B %Y') 'Wednesday 09 September 2020' >>> import locale >>> locale.setlocale(locale.LC_TIME, 'nl_NL') 'nl_NL' >>> datum.strftime('%A %d %B %Y') 'woensdag 09 september 2020' >>> locale.setlocale(locale.LC_TIME, 'it_IT') 'it_IT' >>> datum.strftime('%A %d %B %Y') 'mercoledì 09 settembre 2020' >>>
# -*- coding: utf-8 -*- import time WAITING_FOR_SLEEP = 0.5 WAITING_FOR_TIMEOUT = 30 class TimeoutException(BaseException): pass def waiting_for(func, timeout=None, sleep=None, args=None, kwargs=None): """ Wait for good result of callback function. Example:: flag = 0 def target_1(): if flag > 0: return 'greater' return '' def target_2(): return flag > 0 waiting_for(target_1) waiting_for(target_2, timeout=10) :param func: callback function :param timeout: number of seconds for timeout :param sleep: number of second for sleep after call function :param args: callback args :param kwargs: callback kwargs :raises: TimeoutException """ args = args or tuple() kwargs = kwargs or {} sleep = sleep or WAITING_FOR_SLEEP timeout = timeout or WAITING_FOR_TIMEOUT t_start = time.time() while time.time() <= t_start + timeout: result = func(*args, **kwargs) if result: return result time.sleep(sleep) else: mess = 'Timeout {timeout} exceeded.'.format(timeout=timeout) raise TimeoutException(mess)
#!/usr/bin/python3 '''Defines Amenity class that inherits from BaseModel''' from models.base_model import BaseModel class Amenity(BaseModel): '''Amenity class inherits from BaseModel. Attributes: name (str): Name of Amenity ''' name = ""
def checkgender(mystr): cntar=[0]*26 for ch in mystr: idx=ord(ch)-ord('a') cntar[idx]+=1 cnt=0 for x in cntar: if x!=0: cnt+=1 if int(cnt%2)==0: print("CHAT WITH HER!") else: print("IGNORE HIM!") mystr=input() checkgender(mystr)
def finddangerous(mystr): i=0 ans1=0 ans0=0 while i<len(mystr): if i<len(mystr) and mystr[i]=='1': c1=1 i+=1 while i<len(mystr) and mystr[i]=='1': c1+=1 i+=1 ans1=max(ans1,c1) elif i<len(mystr) and mystr[i]=='0': c0=1 i+=1 while i<len(mystr) and mystr[i]=='0': c0+=1 i+=1 ans0=max(ans0,c0) if ans0>=7 or ans1>=7: print("YES") else: print("NO") mystr=input() finddangerous(mystr)
def matrix(mat): r,c=0,0 for i in range(5): for j in range(5): if mat[i][j]==1: r,c=i,j break print(abs(r-2)+abs(c-2)) mat=[] for i in range(5): row=[] row=list(map(int,input().split())) mat.append(row) matrix(mat)
def add(a, b): return a - b def substract(a, b): return a - b def test_add(): foo = 10 bar = 12 assert add(foo, bar) == 22 def test_substract(): foo = 10 bar = 12 assert add(foo, bar) == -2
hours = float(input('Enter hours worked: ')) rate = float(input('Pay rate : ')) if hours > 40: pay = (hours - 40) * (rate * 1.5) + (40 * rate) print(pay) if hours < 41: pay = rate * hours print(pay)
import string import random password=[] password += [random.choice(string.ascii_uppercase) for i in range(2)] #2 upper case letter, password += [random.choice(string.digits) for i in range(2)] #2 digits, password += [random.choice(string.punctuation) for i in range(2)] # 2 special symbols, password += [random.choice(string.printable) for i in range(4)] #kalan 4 karakter ise tüm klavyeden rastgele seçiliyor. random.shuffle(password) #yukarıdaki listeyi karıştırıyoruz. password= "".join(password) #düzgün çıktı almak için join ile string haline getiriyoruz. print(password)
list1=[] list2=[] n=int(input("enter the total number of lists to be inserted")) for i in range(n): print('enter the',int(i+1),'element to enter') ele=input('') list1.append(ele) for i in list1: if i not in list2: list2.append(i) print("list 1 is",list1) print("unique element list is",list2)
filename=input("Enter Filename:") Extension=filename.split(".") print("Extension of the filename is:", Extension[-1])
class Solution: def reverseWords(self, s: str) -> str: result = "" s = s.split() for i, n in enumerate(s): for j in range(len(n)-1, -1, -1): result += n[j] if i != len(s)-1: result += " " return result
# Sort Array By Parity # Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. # # You may return any answer array that satisfies this condition. # # # # Example 1: # # Input: [3,1,2,4] # Output: [2,4,3,1] # The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. def sortArrayByParity(A): index = 0 count = 0 while count<len(A): if A[index] %2!=0: A.append(A[index]) del A[index] else: index+=1 count+=1 return A print(sortArrayByParity([3,1,2,4])) # >>> [2,4,3,1],[4,2,3,1],[2,4,1,3], or [4,2,1,3] # 285 / 285 test cases passed. # Status: Accepted # Runtime: 84 ms # Memory Usage: 14.2 MB
# A Queue class using deque from collections import deque class Queue: def __init__(self): self.buffer = deque() def enqueue(self,val): self.buffer.appendleft(val) def dequeue(self): return self.buffer.pop() def is_empty(self): return len(self.buffer) == 0 def size(self): return len(self.buffer) pq = Queue() pq.enqueue({ 'company': 'Wall Mrt', 'timeStamp': '15 Apr, 11:01 AM', 'price': 131.10 }) pq.enqueue({ 'company': 'Wall Mrt', 'timeStamp': '15 Apr, 11:02 AM', 'price': 132 }) pq.enqueue({ 'company': 'Wall Mrt', 'timeStamp': '15 Apr, 11:03 AM', 'price': 135 }) print(pq.buffer) # >>> deque([{'company': 'Wall Mrt', 'timeStamp': '15 Apr, 11:03 AM', 'price': 135}, {'company': 'Wall Mrt', 'timeStamp': '15 Apr, 11:02 AM', 'price': 132}, {'company': 'Wall Mrt', 'timeStamp': '15 Apr, 11:01 AM', 'price': 131.1}]) print(pq.dequeue()) # >>> {'company': 'Wall Mrt', 'timeStamp': '15 Apr, 11:01 AM', 'price': 131.1} print(pq.size()) # >>> 2
# coding=utf-8 # Lists # Consider a list (list = []). You can perform the following commands # insert i e: Insert integer e at position i. # print: Print the list. # remove e: Delete the first occurrence of integer e. # append e: Insert integer e at the end of the list. # sort: Sort the list. # Pop: pop the last element of the list # reverse: Reverse the list. # # # Initialize your list and read in the value of n followed by n lines of commands where each command will be of the 7 types listed above. Iterate through each command in order and perform the corresponding operation on your list. # # insert 0 5 # insert 1 10 # insert 0 6 # print # remove 6 # append 9 # append 1 # sort # print # pop # reverse # print x = [] for i in range(N): n = input().split(' ') if n[0] == "append": x.append(int(n[1])) elif n[0] == "insert": x.insert(int(n[1]), int(n[2])) elif n[0] == "remove": x.remove(int(n[1])) elif n[0] == "pop": x.pop() elif n[0] == "sort": x.sort() elif n[0] == "reverse": x.reverse() elif n[0] == "print": print(x)
# Count by x # Create a function with two arguments that will return an array of the first (n) multiples of (x). # # Assume both the given number and the number of times to count will be positive numbers greater than 0. # # Return the results as an array (or list in Python, Haskell or Elixir). # # Examples: # # count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10] # count_by(2,5) #should return [2,4,6,8,10] def count_by(x, n): """ Return a sequence of numbers counting by `x` `n` times. """ return [i*x for i in range(1,n+1)] print(count_by(1,10))
# Stringy Strings # write me a function stringy that takes a size and returns a string of alternating '1s' and '0s'. # # the string should start with a 1. # # a string with size 6 should return :'101010'. # # with size 4 should return : '1010'. # # with size 12 should return : '101010101010'. # # The size will always be positive and will only use whole numbers. def stringy(s): return "".join([ '1' if x%2==0 else '0' for x in range(s) ]) print(stringy(12)) #, '101010101010'
# Return-Two-Highest-Values-in-List: # In this kata, your job is to return the two distinct highest values in a list. If there're less than 2 unique values, return as many of them, as possible. # # The result should also be ordered from highest to lowest. # # Examples: # # [4, 10, 10, 9] => [10, 9] # [1, 1, 1] => [1] # [] => [] def two_highest(arg1): if arg1 == []: return [] if len(arg1) == 1: return arg1 lst = sorted(set(arg1)) return [lst[-1],lst[-2]] print(two_highest([15, 20, 20, 17])) # [20, 17]
# Relative Sort Array # Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. # # Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order. # # # # Example 1: # # Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] # Output: [2,2,2,1,4,3,3,9,6,7,19] # # # Constraints: # # arr1.length, arr2.length <= 1000 # 0 <= arr1[i], arr2[i] <= 1000 # Each arr2[i] is distinct. # Each arr2[i] is in arr1. def relativeSortArray(arr1, arr2): res = [] exel = [] for i in arr1: if i not in arr2: exel.append(i) while len(arr2)>0: [res.append(i) for i in arr1 if i == arr2[0]] arr2 = arr2[1:] return res + sorted(exel) print(relativeSortArray([2,3,1,3,2,4,6,7,9,2,19], [2,1,4,3,9,6])) # >>> [2,2,2,1,4,3,3,9,6,7,19] print(relativeSortArray([2,21,43,38,0,42,33,7,24,13,12,27,12,24,5,23,29,48,30,31], [2,42,38,0,43,21])) # >>> [2,42,38,0,43,21,5,7,12,12,13,23,24,24,27,29,30,31,33,48]
# Exercise: fourth power # Write a Python function, fourthPower, that takes in one number and returns that value raised to the fourth power. # You should use the square procedure that you defined in an earlier exercise # (you don't need to redefine square in this box; when you call square, the grader will use our definition). # This function takes in one number and returns one number. # Code Editor # 1 # def fourthPower(x): def square(x): # Your code here return x*x def fourthPower(x): ''' x: int or float. ''' return square(x) * square(x) print(fourthPower(2))
# Exercise: apply to each # testList = [1, -4, 8, -9] # For each of the following questions (which you may assume is evaluated independently of the previous questions, so that # testList has the value indicated above), provide an expression using applyToEach, so that after evaluation testList has # the indicated value. You may need to write a simple procedure in each question to help with this process. testList = [1, -4, 8, -9] def applyToEach(L, f): for i in range(len(L)): L[i] = f(L[i]) return L def testAbs(x): # result [1, 4, 8, 9] return abs(x) def addOne(x): # result [2, -3, 9, -8] return x+1 def square(x): # result [1, 16, 64, 81] return x*x # print(applyToEach(testList, testAbs)) # print(applyToEach(testList, addOne)) print(applyToEach(testList, square))
# Check If N and Its Double Exist # Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). # # More formally check if there exists two indices i and j such that : # # i != j # 0 <= i, j < arr.length # arr[i] == 2 * arr[j] # # # Example 1: # # Input: arr = [10,2,5,3] # Output: true # Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5. # Example 2: # # Input: arr = [7,1,14,11] # Output: true # Explanation: N = 14 is the double of M = 7,that is, 14 = 2 * 7. # Example 3: # # Input: arr = [3,1,7,11] # Output: false # Explanation: In this case does not exist N and M, such that N = 2 * M. # # # Constraints: # # 2 <= arr.length <= 500 # -10^3 <= arr[i] <= 10^3 def checkIfExist(arr): lst = [] for num in arr: if num * 2 in lst or num / 2 in lst: return True else: lst.append(num) return False print(checkIfExist([7,1,14,11])) print(checkIfExist([3,1,7,11])) # 104 / 104 test cases passed. # Status: Accepted # Runtime: 60 ms # Memory Usage: 13.9 MB
# Hash Table Exercise 2: # nyc_weather.csv contains new york city weather for first few days in the month of January. Write a program that can answer following, # What was the temperature on Jan 9? # What was the temperature on Jan 4? # Figure out data structure that is best for this problem jan_weather = {} with open('nyc_weather.csv', 'r') as f: for line in f: data = line.split(',') try: jan_weather[data[0]] = int(data[1]) except: print('No value in this line') # What was the temperature on Jan 9? print(jan_weather['Jan 9']) # What was the temperature on Jan 4? print(jan_weather['Jan 4']) # Figure out data structure that is best for this problem print('Converting nyc_weather.csv to a dictonary and accessing it directly in O(1) is the fastest')
# Cat Dog Rabbit #Test your understanding of what we have covered so far by trying the following exercise. Modify the code from Activecode 8 so that the final list only contains a single copy of each letter. wordList = ['cat','dog','rabbit'] l = [] for i in wordList: [l.append(x) for x in i if x not in l] print(l) # Test your understanding of list comprehensions by redoing Activecode 8 using list comprehensions. For an extra challenge, see if you can figure out how to remove the duplicates. print(set([i for i in "".join(wordList) ]))
# Running Sum # 1480. Running Sum of 1d Array # Easy # # 362 # # 46 # # Add to List # # Share # Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). # # Return the running sum of nums. # # # # Example 1: # # Input: nums = [1,2,3,4] # Output: [1,3,6,10] # Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. # Example 2: # # Input: nums = [1,1,1,1,1] # Output: [1,2,3,4,5] # Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. # Example 3: # # Input: nums = [3,1,2,10,1] # Output: [3,4,6,16,17] def runningSum(arr): s = 0 res = [] for i in arr: s+=i res.append(s) return res print(runningSum([1,2,3,4,5])) # 53 / 53 test cases passed. # Status: Accepted # Runtime: 28 ms # Memory Usage: 14.2 MB
# Exercise: Array DataStructure # Let us say your expense for every month are listed below, # January - 2200 # February - 2350 # March - 2600 # April - 2130 # May - 2190 # Create a list to store these monthly expenses and using that find out, # # 1. In Feb, how many dollars you spent extra compare to January? # 2. Find out your total expense in first quarter (first three months) of the year. # 3. Find out if you spent exactly 2000 dollars in any month # 4. June month just finished and your expense is 1980 dollar. Add this item to our monthly expense list # 5. You returned an item that you bought in a month of April and # got a refund of 200$. Make a correction to your monthly expense list # based on this expenses = [ ['January', 2200], ['February', 2350], ['March', 2600], ['April', 2130], ['May', 2190] ] # 1. In Feb, how many dollars you spent extra compare to January? print('Spent £{} more in Feb compared to Jan.'.format(expenses[1][1]-expenses[0][1])) # Find out your total expense in first quarter (first three months) of the year. print('Total expense for the first quarter: £{}'.format(expenses[0][1]+expenses[1][1]+expenses[2][1])) # 3. Find out if you spent exactly 2000 dollars in any month print('Was there a £200 expense in June? {}'.format(200 in expenses)) # 4. June month just finished and your expense is 1980 dollar. Add this item to our monthly expense list expenses.append(['June', 1980]) print(expenses) # 5. You returned an item that you bought in a month of April and # got a refund of 200$. Make a correction to your monthly expense list # based on this expenses[3][1] = expenses[3][1]-200 print(expenses)
# Merge Sorted Array # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # # Note: # # The number of elements initialized in nums1 and nums2 are m and n respectively. # You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. # Example: # # Input: # nums1 = [1,2,3,0,0,0], m = 3 # nums2 = [2,5,6], n = 3 # # Output: [1,2,2,3,5,6] # # # Constraints: # # -10^9 <= nums1[i], nums2[i] <= 10^9 # nums1.length == m + n # nums2.length == n def merge(nums1, m, nums2, n): """ Do not return anything, modify nums1 in-place instead. """ if n == 0: return if m == 0: nums1[:n] = nums2 x, y = m - 1, n - 1 for i in range(m + n - 1, -1, -1): if x >= 0 and y >= 0: if nums1[x] >= nums2[y]: nums1[i] = nums1[x] x -= 1 else: nums1[i] = nums2[y] y -= 1 elif x >= 0: nums1[i] = nums1[x] x -= 1 else: nums1[i] = nums2[y] y -= 1 return nums1 # nums1 = [1,2,3,0,0,0] # nums2 = [2,5,6] # m = 3 # n = 3 # nums1 = [0] # nums2 = [1] # m = 0 # n = 1 nums1 = [2,0] m = 1 nums2 = [1] n = 1 print(merge(nums1,m,nums2,n))
# Reverse Linked List # Reverse a singly linked list. # # Example: # # Input: 1->2->3->4->5->NULL # Output: 5->4->3->2->1->NULL # Follow up: # # A linked list can be reversed either iteratively or recursively. Could you implement both? # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: curr = head prev = None while curr: next = curr.next curr.next = prev prev = curr curr = next head = prev return head # 27 / 27 test cases passed. # Status: Accepted # Runtime: 36 ms # Memory Usage: 15.4 MB
# Fundamentals: Return # Make multiple functions that will return the sum, difference, modulus, product, quotient, and the exponent respectively. # # Please use the following function names: # # addition = add # # multiply = multiply # # division = divide (both integer and float divisions are accepted) # # modulus = mod # # exponential = exponent # # subtraction = subt # # Note: All math operations will be: a (operation) b import math def add(a,b): return a+b def multiply(a,b): return a*b def divide(a,b): return a//b def mod(a,b): return math.fmod(a, b) def exponent(a,b): return a**b def subt(a,b): return a-b
# Linked Lists - Get Nth # # Implement a GetNth() function that takes a linked list and an integer index and returns the node stored at the Nth index position. GetNth() uses the C numbering convention that the first node is index 0, the second is index 1, ... and so on. So for the list 42 -> 13 -> 666, GetNth() with index 1 should return Node(13); # # getNth(1 -> 2 -> 3 -> null, 0).data === 1 # getNth(1 -> 2 -> 3 -> null, 1).data === 2 # The index should be in the range [0..length-1]. If it is not, GetNth() should throw/raise an exception (ArgumentException in C#, InvalidArgumentException in PHP). You should also raise an exception (ArgumentException in C#, InvalidArgumentException in PHP) if the list is empty/null/None. # # Prerequisite Kata (may be in beta): # # Linked Lists - Push & BuildOneTwoThree # Linked Lists - Length & Count # The push() and buildOneTwoThree() (BuildOneTwoThree in C#, build_one_two_three() in PHP) functions do not need to be redefined. class Node(object): def __init__(self, data): self.data = data self.next = None def get_nth(node, index): # Your code goes here. if node is None or index <0: raise Exception() c = 0 while node: if c == index: return node c+=1 node = node.next raise Exception()
# Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. # By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month. # In this problem, we will not be dealing with a minimum monthly payment rate. # The following variables contain values as described below: # balance - the outstanding balance on the credit card # annualInterestRate - annual interest rate as a decimal # The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example: # Lowest Payment: 180 # Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). # The monthly payment must be a multiple of $10 and is the same for all months. # Notice that it is possible for the balance to become negative using this payment scheme, which is okay. # A summary of the required math is found below: # Monthly interest rate = (Annual interest rate) / 12.0 # Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment) # Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) ##################################################### # Test Case 1 (Lowest Payment: 310): # balance = 3329 # annualInterestRate = 0.2 # minimumFixedPayment = 10 # MonthlyInterestRate = (annualInterestRate) / 12.0 # Test Case 2 ('Lowest Payment: 440'): balance = 4773 newBalance = balance annualInterestRate = 0.2 minimumFixedPayment = 0 MonthlyInterestRate = (annualInterestRate) / 12.0 while newBalance > 0: newBalance = balance minimumFixedPayment += 10 for x in range(12): MonthlyUnpaidBalance = (newBalance) - (minimumFixedPayment) UpdatedBalanceEachMonth = (MonthlyUnpaidBalance) + \ (MonthlyInterestRate * MonthlyUnpaidBalance) newBalance = UpdatedBalanceEachMonth print('Lowest Payment: {}'.format(minimumFixedPayment))
# FInd Pivot Index # Given an array of integers nums, write a method that returns the "pivot" index of this array. # # We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to the right of the index. # # If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index. # # # # Example 1: # # Input: nums = [1,7,3,6,5,6] # Output: 3 # Explanation: # The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3. # Also, 3 is the first index where this occurs. # Example 2: # # Input: nums = [1,2,3] # Output: -1 # Explanation: # There is no index that satisfies the conditions in the problem statement. def pivotIndex(nums): if len(nums) == 0: return -1 for i in range(len(nums)+1): if i > 1 and sum(nums[0:i-1]) == sum(nums[i:len(nums)]): return i-1 elif i == 0 and sum(nums[1:]) == 0: return 0 return -1 print(pivotIndex([1, 7, 3, 6, 5, 6])) # >>> 3 print(pivotIndex([1, 2, 3])) #  >>> -1 print(pivotIndex([-1, -1, -1, -1, -1, 0])) # >>> 2 print(pivotIndex([-1, -1, -1, 0, 1, 1])) # >>> 0 print(pivotIndex([-1, -1, 0, 1, 1, 0])) # >>> 5 # Runtime: 9396 ms, faster than 5.02% of Python3 online submissions for Find Pivot Index. # Memory Usage: 14.8 MB, less than 91.74% of Python3 online submissions for Find Pivot Index. # 742 / 742 test cases passed. # Status: Accepted # Runtime: 9640 ms # Memory Usage: 15 MB
# Rotate List # Given a linked list, rotate the list to the right by k places, where k is non-negative. # # Example 1: # # Input: 1->2->3->4->5->NULL, k = 2 # Output: 4->5->1->2->3->NULL # Explanation: # rotate 1 steps to the right: 5->1->2->3->4->NULL # rotate 2 steps to the right: 4->5->1->2->3->NULL # Example 2: # # Input: 0->1->2->NULL, k = 4 # Output: 2->0->1->NULL # Explanation: # rotate 1 steps to the right: 2->0->1->NULL # rotate 2 steps to the right: 1->2->0->NULL # rotate 3 steps to the right: 0->1->2->NULL # rotate 4 steps to the right: 2->0->1->NULL # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: #1. if there is no node or only one node in the list #just return head if not head or not head.next: return head #2. we do not need to move k times but move k % len(lst) if k% len(lst) != 0 # so we need walk through the list to find the length n = 0 p = head while p: n += 1 p = p.next # update k, which is the actual time we need to move right k = k % n if k == 0: return head # initialize two pointer, # one is point the head # one is point the position we need to rotate p1, p2 = head, head # walk p2 to the position of rotate for _ in range(k): p2 = p2.next # now we walk p1 and p2 till p2 or p2.next is None # then p1 would be the rotation position while p2 and p2.next: p1 = p1.next p2 = p2.next res = p1.next # link the two part and update the tail p1.next = None p2.next = head return res # 231 / 231 test cases passed. # Status: Accepted # Runtime: 40 ms # Memory Usage: 14.1 MB
''' Find the square root of the integer without using any Python library. You have to find the floor value of the square root. For example if the given number is 16, then the answer would be 4. If the given number is 27, the answer would be 5 because sqrt(5) = 5.196 whose floor value is 5. The expected time complexity is O(log(n)) ''' def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ # Return the number if it is 0 or 1 if number == 0 or number == 1: return number elif number < 0: return None bottom_val = 0 top_val = number # Search for the square root through guess and check and narrowing the list by n/2 each time. while bottom_val <= top_val: mid_val = (top_val + bottom_val) // 2 if mid_val ** 2 == number: return mid_val elif mid_val ** 2 > number: top_val = mid_val elif mid_val ** 2 < number: bottom_val = mid_val if mid_val ** 2 < number < (mid_val + 1) ** 2: return mid_val # 'Pass' Test Cases print ("Pass" if (3 == sqrt(9)) else "Fail") print ("Pass" if (0 == sqrt(0)) else "Fail") print ("Pass" if (4 == sqrt(16)) else "Fail") print ("Pass" if (1 == sqrt(1)) else "Fail") print ("Pass" if (5 == sqrt(27)) else "Fail") print ("Pass" if (None == sqrt(-2)) else "Fail") # 'Fail' Test Cases print ("Pass" if (5 != sqrt(16)) else "Fail") print ("Pass" if (30 != sqrt(9345)) else "Fail") print ("Pass" if (4 != sqrt(27)) else "Fail")
import math import heapq from collections import namedtuple Cost = namedtuple('Cost', ['total', 'journey', 'to_end']) # (float, float) Path = namedtuple('Path', ['cost', 'intersections', 'previous', 'current']) # (Cost, [int, int ...], int, int) class Map(object): def __init__(self): self.roads = None self.intersections = None def shortest_path(input_map, start, end): # if the end point is the start, return the path immediately if start == end: return [start] elif start not in input_map.intersections or end not in input_map.intersections: return -1 # Create a priority queue and add the path of the initial map point using the Path tuple heap = list() min_path_cost = float('inf') # Temporarily set the minimum cost to the end to infinity min_path = None initial_distance = distance_between(input_map.intersections[start], input_map.intersections[end]) path = Path(Cost(initial_distance, 0, initial_distance), [start], start, start) heapq.heappush(heap, path) # While the heap is not empty while len(heap) >= 1: # Pop the path with the lowest total cost (traversed distance + estimated distance to end) from the heap closest_path = heapq.heappop(heap) # For each map point adjacent to the current point for road in input_map.roads[closest_path.current]: # Prevent from moving to a previous road if road == closest_path.previous: continue new_path = update_path(input_map, closest_path, road, end) # Arrived at the end point in one of our paths if road == end: # If the cost to get to the end on this path is our cheapest option, save the new cost and path if new_path.cost.total < min_path_cost: min_path_cost = new_path.cost.total min_path = new_path.intersections else: # If one of the other paths has already arrived to the end, check to see if we should continue with this current path if min_path is not None: if new_path.cost.total < min_path_cost: heapq.heappush(heap, new_path) else: heapq.heappush(heap, new_path) if min_path_cost is None: return -1 else: return min_path def distance_between(p1, p2): # Find the distance between two points x1, y1 = p1[0], p1[1] x2, y2 = p2[0], p2[1] distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return distance def update_path(input_map, path, next_point, end): distance_to_point = distance_between(input_map.intersections[path.current], input_map.intersections[next_point]) distance_to_end = distance_between(input_map.intersections[next_point], input_map.intersections[end]) new_path_cost = path.cost.journey + distance_to_point total_new_path_cost = new_path_cost + distance_to_end new_path_intersections = path.intersections + [next_point] updated_path = Path(Cost(total_new_path_cost, new_path_cost, distance_to_end), new_path_intersections, path.current, next_point) return updated_path # Test Data map_10 = Map() map_10.intersections = {} map_10.roads = [] map_40 = Map() map_40.intersections = { 0: [0.7801603911549438, 0.49474860768712914], 1: [0.5249831588690298, 0.14953665513987202], 2: [0.8085335344099086, 0.7696330846542071], 3: [0.2599134798656856, 0.14485659826020547], 4: [0.7353838928272886, 0.8089961609345658], 5: [0.09088671576431506, 0.7222846879290787], 6: [0.313999018186756, 0.01876171413125327], 7: [0.6824813442515916, 0.8016111783687677], 8: [0.20128789391122526, 0.43196344222361227], 9: [0.8551947714242674, 0.9011339078096633], 10: [0.7581736589784409, 0.24026772497187532], 11: [0.25311953895059136, 0.10321622277398101], 12: [0.4813859169876731, 0.5006237737207431], 13: [0.9112422509614865, 0.1839028760606296], 14: [0.04580558670435442, 0.5886703168399895], 15: [0.4582523173083307, 0.1735506267461867], 16: [0.12939557977525573, 0.690016328140396], 17: [0.607698913404794, 0.362322730884702], 18: [0.719569201584275, 0.13985272363426526], 19: [0.8860336256842246, 0.891868301175821], 20: [0.4238357358399233, 0.026771817842421997], 21: [0.8252497121120052, 0.9532681441921305], 22: [0.47415009287034726, 0.7353428557575755], 23: [0.26253385360950576, 0.9768234503830939], 24: [0.9363713903322148, 0.13022993020357043], 25: [0.6243437191127235, 0.21665962402659544], 26: [0.5572917679006295, 0.2083567880838434], 27: [0.7482655725962591, 0.12631654071213483], 28: [0.6435799740880603, 0.5488515965193208], 29: [0.34509802713919313, 0.8800306496459869], 30: [0.021423673670808885, 0.4666482714834408], 31: [0.640952694324525, 0.3232711412508066], 32: [0.17440205342790494, 0.9528527425842739], 33: [0.1332965908314021, 0.3996510641743197], 34: [0.583993110207876, 0.42704536740474663], 35: [0.3073865727705063, 0.09186645974288632], 36: [0.740625863119245, 0.68128520136847], 37: [0.3345284735051981, 0.6569436279895382], 38: [0.17972981733780147, 0.999395685828547], 39: [0.6315322816286787, 0.7311657634689946]} map_40.roads = [ [36, 34, 31, 28, 17], [35, 31, 27, 26, 25, 20, 18, 17, 15, 6], [39, 36, 21, 19, 9, 7, 4], [35, 20, 15, 11, 6], [39, 36, 21, 19, 9, 7, 2], [32, 16, 14], [35, 20, 15, 11, 1, 3], [39, 36, 22, 21, 19, 9, 2, 4], [33, 30, 14], [36, 21, 19, 2, 4, 7], [31, 27, 26, 25, 24, 18, 17, 13], [35, 20, 15, 3, 6], [37, 34, 31, 28, 22, 17], [27, 24, 18, 10], [33, 30, 16, 5, 8], [35, 31, 26, 25, 20, 17, 1, 3, 6, 11], [37, 30, 5, 14], [34, 31, 28, 26, 25, 18, 0, 1, 10, 12, 15], [31, 27, 26, 25, 24, 1, 10, 13, 17], [21, 2, 4, 7, 9], [35, 26, 1, 3, 6, 11, 15], [2, 4, 7, 9, 19], [39, 37, 29, 7, 12], [38, 32, 29], [27, 10, 13, 18], [34, 31, 27, 26, 1, 10, 15, 17, 18], [34, 31, 27, 1, 10, 15, 17, 18, 20, 25], [31, 1, 10, 13, 18, 24, 25, 26], [39, 36, 34, 31, 0, 12, 17], [38, 37, 32, 22, 23], [33, 8, 14, 16], [34, 0, 1, 10, 12, 15, 17, 18, 25, 26, 27, 28], [38, 5, 23, 29], [8, 14, 30], [0, 12, 17, 25, 26, 28, 31], [1, 3, 6, 11, 15, 20], [39, 0, 2, 4, 7, 9, 28], [12, 16, 22, 29], [23, 29, 32], [2, 4, 7, 22, 28, 36] ] # Test 1 path = shortest_path(map_40, 5, 34) if path == [5, 16, 37, 12, 34]: print("great! Your code works for these inputs!") else: print("something is off, your code produced the following:") print(path) # Test 2 path = shortest_path(map_10, 0, 0) if path == [0]: print("great! Your code works for these inputs!") else: print("something is off, your code produced the following:") print(path) # Test 3 path = shortest_path(map_40, 5, 40) if path == -1: print("great! Your code works for these inputs!") else: print("something is off, your code produced the following:") print(path)
"""Duoc gioi han boi cap ngoac () Chua duoc moi gia tri Toc do truy xuat nhanh hon list Chiem dung luong bo nho nho hon list Bao ve du lieu khong bi thay doi Co the dung lam key cua dictionary""" # Toan tu cua tuple giong voi toan tu cua chuoi # Toan # tuple tup = (1,) print(tup) print(type(tup)) a = tuple((1,2,3)) print(a) a = (i for i in range(10)) print(a) # <generator object <genexpr> at 0x7f06f77e59e8> a = tuple(a) print(a) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) print(tuple(i for i in range(20) if i % 2 == 0)) # + print('---Toan tu +---') tup = (1,4,5) tup += (3,6) print(tup) # * print('---Toan tu *---') tup *= 3 print(tup) # in print(1 in tup) # True # indexing print(tup[3]) # 3 # len() print(len(tup)) # last element print(tup[-1]) # reverse tuple print(tup[::-1]) # tup[0] = 'One' => error # tuple matrix, like list ((), (), ()) a = ([1,2,3]) # => list print(a, type(a)) # count() # index()
print('hello', 'world') # Parameter # sep (chia ra, phân ra) print('--- parameter sep ---') print('Hello', 'Python', 'Course', sep='---') # Hello---Python---Course # end print('--- parameter end ---') print('line 1', end='|') print('line 2') print('line 3') # sleep() from time import sleep print('start...') sleep(1) print('end...') print('start...', end='') sleep(1) print('end...') # file print('---print file by open file---') with open('test1.txt', 'w') as f: print('Printed by print function', file=f) # flush # default False # liên quan trực tiếp đến parameter end # flush=True => Yêu cầu bộ đệm xuất những gì có trong bộ đệm ra. print('---parameter flush ---') print('start...xxx...', end='', flush=True) sleep(1) print('end...') # So sánh print trong Python 3x và 2x # 3x: Hàm, 2x: Câu lệnh. print('---Print funny---') name = 'Panda.' great = 'Hello! My name is ' for char in great + name: print(char, end='', flush=True) sleep(0.2)
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree(object): def __init__(self, root): self.root = Node(root) # choose the type of traversal type def print_tree(self, traversal_type): if traversal_type == "preorder": return self.preorder_print(self.root, "") elif traversal_type == "inorder": return self.inorder_print(self.root, "") elif traversal_type == "postorder": return self.postorder_traversal(self.root, "") elif traversal_type == "levelorder": return self.levelorder_print(self.root) elif traversal_type == "reverseorder": return self.reverse_levelorder_print(self.root) else: print("Traversal type " + traversal_type + " not supported") return False # Traversal Depth-First Approach 1 def preorder_print(self, start, traversal): if start: traversal += (str(start.value) + "-") traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal # Traversal Depth-First Approach 2 def inorder_print(self, start, traversal): if start: traversal = self.inorder_print(start.left, traversal) traversal += (str(start.value) + "-") traversal = self.inorder_print(start.right, traversal) return traversal # Traversal Depth-First Approach 3 def postorder_traversal(self, start, traversal): if start: traversal = self.postorder_traversal(start.left, traversal) traversal = self.postorder_traversal(start.right, traversal) traversal += (str(start.value) + "-") return traversal def levelorder_print(self, start): if start is None: return queue = Queue() queue.enqueue(start) traversal = "" while len(queue) > 0: traversal += str(queue.peek()) + "-" node = queue.dequeue() if node.left: queue.enqueue(node.left) if node.right: queue.enqueue(node.right) return traversal def reverse_levelorder_print(self, start): if start is None: return queue = Queue() queue.enqueue(start) stack = Stack() traversal = "" while (len(queue) > 0): node = queue.dequeue() if node.right: queue.enqueue(node.right) if node.left: queue.enqueue(node.left) stack.push(node) while len(stack) > 0: node = stack.pop() traversal += str(node.value) + "-" return traversal def tree_height(self, node): # base case: if nothing, then return -1 if node is None: return -1 left_height = self.tree_height(node.left) right_height = self.tree_height(node.right) return 1 + max(left_height, right_height) class Queue(object): def __init__(self): self.items = [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): if not self.is_empty(): return self.items.pop() def is_empty(self): return len(self.items) == 0 def peek(self): if not self.is_empty(): return self.items[-1].value def __len__(self): return self.size() def size(self): return len(self.items) class Stack(object): def __init__(self): self.items = [] def __len__(self): return self.size() def size(self): return len(self.items) def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() def peek(self): if not self.is_empty(): return self.items[-1] def is_empty(self): return len(self.items) == 0 def __str__(self): s = "" for i in range(len(self.items)): s += str(self.items[i].value) + "-" return s
#!/bin/env python """ Advent of Code Day 18 """ import re class Num: """ A bit strange math needed for the exercises """ def __init__(self, value) -> None: """ A special number :type value: int """ self.value = value def __sub__(self, other): """ redefine sub used for part 1 """ return Num(self.value * other.value) def __and__(self, other): """ redefine the and use for part 2 """ return Num(self.value * other.value) def __add__(self, other): """ add is used in both examples """ return Num(self.value + other.value) @property def __int__(self): """ int is still a Num for adding """ return Num(self.value) class Day18: """ Class for processing of day 18 """ def __init__(self, task: int = 1) -> None: self.lines = [] self.task = task def load_input(self, file_name): """ load the input """ with open(file_name, "r") as in_file: self.lines = [] for line in in_file: self.lines.append(line.rstrip('\n')) @property def get_task(self) -> int: """ Solve the equations :rtype: int """ solution = Num(0) for line in self.lines: # - has the same priority as + # for part2, & has lower priority than + if self.task == 1: line = line.replace('*', '-') else: line = line.replace('*', '&') line = re.sub(r'(\d+)', r"Num(\1)", line) line_result = eval(line) solution += line_result print(f"Task{self.task}: {solution.value}") return solution.value def test_app(): """ Run the tests """ runner = Day18() runner.load_input("input18_test") assert runner.get_task == 13632 runner.task = 2 assert runner.get_task == 23340 if __name__ == "__main__": day_processor = Day18() day_processor.load_input("input18") task1 = day_processor.get_task day_processor.task = 2 task2 = day_processor.get_task
import matplotlib.pyplot as plt from matplotlib import animation import numpy as np fig,ax = plt.subplots() x = np.arange(0,2* np.pi,0.01) line, = ax.plot(x,np.sin(x)) def animate(i): line.set_ydata(np.sin((x+i)/10)) return line, def init(): line.set_ydata(np.sin(x)) return line, ani = animation.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init,interval=60,blit=False) plt.show()
import random import copy import math from timeit import default_timer as timer HOLES_AMOUNT = 14 PLAYER_ONE = -1 PLAYER_TWO = 0 COUNTER_FIRST, COUNTER_SECOND = 0, 0 MOVES_ONE, MOVES_TWO = 0, 0 class Hole: def __init__(self, number): self.stones = 4 self.hole_number = number self.opposite_hole = None self.next_hole = None def move_stones(self, player_turn): moving_stones = self.stones self.stones = 0 if moving_stones > 0: return Hole.take_stone_and_go_on(self.next_hole, moving_stones, player_turn) @staticmethod def take_stone_and_go_on(hole, remaining_stones, player_turn): if remaining_stones == 1: if (player_turn == PLAYER_ONE and hole.hole_number == -1) or (player_turn == PLAYER_TWO and hole.hole_number == 0): hole.next_hole.stones += 1 return hole.next_hole.hole_number else: hole.stones += 1 return hole.hole_number if (player_turn == PLAYER_ONE and hole.hole_number == -1) or (player_turn == PLAYER_TWO and hole.hole_number == 0): return Hole.take_stone_and_go_on(hole.next_hole, remaining_stones, player_turn) else: hole.stones += 1 return Hole.take_stone_and_go_on(hole.next_hole, remaining_stones - 1, player_turn) class Board: def __init__(self): self.player_turn = random.choice([PLAYER_ONE, PLAYER_TWO]) self.holes = [Hole(-1), Hole(1), Hole(2), Hole(3), Hole(4), Hole(5), Hole(6), Hole(0), Hole(7), Hole(8), Hole(9), Hole(10), Hole(11), Hole(12)] self.holes[7].stones = 0 self.holes[0].stones = 0 self.set_next_holes() self.set_opposite_holes() def set_next_holes(self): for i in range(HOLES_AMOUNT - 1): self.holes[i].next_hole = self.holes[i+1] self.holes[HOLES_AMOUNT - 1].next_hole = self.holes[0] def set_opposite_holes(self): for i in range(1, int(HOLES_AMOUNT / 2)): self.holes[i].opposite_hole = self.holes[HOLES_AMOUNT - i] self.holes[HOLES_AMOUNT - i].opposite_hole = self.holes[i] def decide_turn(self, current_hole_number): if self.player_turn == PLAYER_ONE: if current_hole_number != 0: self.player_turn = PLAYER_TWO else: if current_hole_number != -1: self.player_turn = PLAYER_ONE def check_if_the_game_is_finished(self): # start_hole = 1 # end_hole = 7 # if self.player_turn == PLAYER_TWO: # start_hole = 8 # end_hole = 14 # for i in range(start_hole, end_hole): # if self.holes[i].stones != 0: # return False # self.add_remaining_stones_to_winners_well() # return True if all(hole.stones == 0 for hole in self.holes[1:7]): added_stones = 0 for hole in self.holes[8:14]: added_stones += hole.stones hole.stones = 0 self.holes[0].stones += added_stones return True elif all(hole.stones == 0 for hole in self.holes[8:14]): added_stones = 0 for hole in self.holes[1:7]: added_stones += hole.stones hole.stones = 0 self.holes[7].stones += added_stones return True return False @staticmethod def h1_heuristic(board, starting_player): if starting_player == PLAYER_ONE: return board.holes[6].stones else: return board.holes[13].stones @staticmethod def heuristic_evaluate(board, number_of_moves, starting_player): sign = 1 if starting_player == PLAYER_TWO: sign = -1 right_hole = Board.h1_heuristic(board, starting_player) # right_hole = 0 return 2 * (board.holes[7].stones - board.holes[0].stones) + (0.161 * right_hole * sign) + (0.29 * number_of_moves * sign) def add_remaining_stones_to_winners_well(self): start_hole = 1 end_hole = 7 winners_well_index = 7 if self.player_turn == PLAYER_ONE: start_hole = 8 end_hole = 14 winners_well_index = 0 for i in range(start_hole, end_hole): self.holes[winners_well_index].stones += self.holes[i].stones self.holes[i].stones = 0 def check_if_stone_takes_opposite_hole(self, hole_number): if (self.player_turn == PLAYER_ONE and 1 <= hole_number < 7) or (self.player_turn == PLAYER_TWO and 7 <= hole_number <= 12): if hole_number > 6: hole_number += 1 if self.holes[hole_number].opposite_hole is not None and self.holes[hole_number].stones == 1: stones_in_opposite = self.holes[hole_number].opposite_hole.stones if stones_in_opposite > 1: self.holes[hole_number].opposite_hole.stones = 0 self.holes[hole_number].stones = 0 if self.player_turn == PLAYER_ONE: self.holes[7].stones += stones_in_opposite + 1 else: self.holes[0].stones += stones_in_opposite + 1 def get_available_moves(self): available_moves = self.get_potential_moves() updated_moves = [] Board.include_additional_move(self, available_moves, updated_moves) return updated_moves def get_potential_moves(self): start_hole = 1 end_hole = 7 if self.player_turn == PLAYER_TWO: start_hole = 8 end_hole = 14 potential_moves = [] for i in range(start_hole, end_hole): if self.holes[i].stones > 0: potential_moves.append([i]) return potential_moves @staticmethod def include_additional_move(board, available_moves, updated_moves): for move in available_moves: last_element = move[-1] temp_board = copy.deepcopy(board) last_hole_number, is_game_finished = temp_board.move_stones_from_hole(last_element) if not is_game_finished and temp_board.does_move_reach_players_well(last_hole_number): potential_moves = temp_board.get_potential_moves() next_choices = [] for potential in potential_moves: next_choices.append(move + potential) Board.include_additional_move(temp_board, next_choices, updated_moves) del temp_board else: del temp_board updated_moves.append(move) def does_move_reach_players_well(self, last_hole_number): if self.player_turn == PLAYER_ONE: if last_hole_number == 0: return True elif self.player_turn == PLAYER_TWO: if last_hole_number == -1: return True return False def move_stones_from_hole(self, hole_index): last_hole_number = self.holes[hole_index].move_stones(self.player_turn) self.check_if_stone_takes_opposite_hole(last_hole_number) is_game_finished = self.check_if_the_game_is_finished() return last_hole_number, is_game_finished def ai_random_move(self): start_hole = 1 end_hole = 6 if not self.player_turn: start_hole = 8 end_hole = 13 r = random.randint(start_hole, end_hole) while self.holes[r].stones == 0: r = random.randint(start_hole, end_hole) return self.holes[r].move_stones(self.player_turn) def ai_minimax_move(self, depth): global MOVES_ONE, MOVES_TWO maximizing = True turn = 'Player\'s one choice: ' if self.player_turn == PLAYER_TWO: maximizing = False turn = 'Player\'s two choice: ' best_val, chosen_moves = Board.minimax(self, depth, maximizing) self.make_moves_from_list(chosen_moves) print(turn, best_val, chosen_moves) if self.player_turn == PLAYER_ONE: MOVES_ONE += len(chosen_moves) self.player_turn = PLAYER_TWO else: MOVES_TWO += len(chosen_moves) self.player_turn = PLAYER_ONE def ai_alpha_beta_move(self, depth): global MOVES_ONE, MOVES_TWO maximizing = True turn = 'Player\'s one choice: ' if self.player_turn == PLAYER_TWO: maximizing = False turn = 'Player\'s two choice: ' best_val, chosen_moves = Board.minimax_with_alpha_beta(self, depth, -math.inf, math.inf, maximizing) self.make_moves_from_list(chosen_moves) print(turn, best_val, chosen_moves) if self.player_turn == PLAYER_ONE: MOVES_ONE += len(chosen_moves) self.player_turn = PLAYER_TWO else: MOVES_TWO += len(chosen_moves) self.player_turn = PLAYER_ONE def ai_heuristics_move(self, depth): global MOVES_ONE, MOVES_TWO maximizing = True turn = 'Player\'s one choice: ' if self.player_turn == PLAYER_TWO: maximizing = False turn = 'Player\'s two choice: ' best_val, chosen_moves = Board.minimax_with_alpha_beta_heuristics(self, depth, -math.inf, math.inf, maximizing, self.player_turn, 0) self.make_moves_from_list(chosen_moves) print(turn, best_val, chosen_moves) if self.player_turn == PLAYER_ONE: MOVES_ONE += len(chosen_moves) self.player_turn = PLAYER_TWO else: MOVES_TWO += len(chosen_moves) self.player_turn = PLAYER_ONE def make_moves_from_list(self, moves): for move in moves: self.move_stones_from_hole(move) @staticmethod def minimax(game, depth, is_maximizing): global COUNTER_FIRST, COUNTER_SECOND chosen_moves = [] if depth == 0 or game.check_if_the_game_is_finished(): return game.holes[7].stones - game.holes[0].stones, chosen_moves if is_maximizing: best_val = -math.inf for available_moves in game.get_available_moves(): COUNTER_FIRST += 1 game_copy = copy.deepcopy(game) game_copy.make_moves_from_list(available_moves) result = Board.minimax(game_copy, depth - 1, False)[0] del game_copy if result > best_val: best_val = result chosen_moves = available_moves return best_val, chosen_moves else: best_val = math.inf for available_moves in game.get_available_moves(): COUNTER_SECOND += 1 game_copy = copy.deepcopy(game) game_copy.make_moves_from_list(available_moves) result = Board.minimax(game_copy, depth - 1, True)[0] del game_copy if result < best_val: best_val = result chosen_moves = available_moves return best_val, chosen_moves @staticmethod def minimax_with_alpha_beta(game, depth, alpha, beta, is_maximizing): global COUNTER_FIRST, COUNTER_SECOND chosen_moves = [] if depth == 0 or game.check_if_the_game_is_finished(): return game.holes[7].stones - game.holes[0].stones, chosen_moves if is_maximizing: best_val = -math.inf for available_moves in game.get_available_moves(): COUNTER_FIRST += 1 game_copy = copy.deepcopy(game) game_copy.make_moves_from_list(available_moves) result = Board.minimax_with_alpha_beta(game_copy, depth - 1, alpha, beta, False)[0] del game_copy if result > best_val: best_val = result chosen_moves = available_moves alpha = max(alpha, result) if beta <= alpha: break return best_val, chosen_moves else: best_val = math.inf for available_moves in game.get_available_moves(): COUNTER_SECOND += 1 game_copy = copy.deepcopy(game) game_copy.make_moves_from_list(available_moves) result = Board.minimax_with_alpha_beta(game_copy, depth - 1, alpha, beta, True)[0] del game_copy if result < best_val: best_val = result chosen_moves = available_moves beta = min(beta, result) if beta <= alpha: break return best_val, chosen_moves @staticmethod def minimax_with_alpha_beta_heuristics(game, depth, alpha, beta, is_maximizing, starting_player, number_of_moves): global COUNTER_FIRST, COUNTER_SECOND chosen_moves = [] if depth == 0 or game.check_if_the_game_is_finished(): return Board.heuristic_evaluate(game, number_of_moves, starting_player), chosen_moves if is_maximizing: best_val = -math.inf for available_moves in game.get_available_moves(): COUNTER_FIRST += 1 game_copy = copy.deepcopy(game) game_copy.make_moves_from_list(available_moves) starts = True if starting_player == PLAYER_TWO: starts = False if starts == is_maximizing: number_of_moves += len(available_moves) result = Board.minimax_with_alpha_beta_heuristics(game_copy, depth - 1, alpha, beta, False, starting_player, number_of_moves)[0] del game_copy if result > best_val: best_val = result chosen_moves = available_moves alpha = max(alpha, result) if beta <= alpha: break return best_val, chosen_moves else: best_val = math.inf for available_moves in game.get_available_moves(): COUNTER_SECOND += 1 game_copy = copy.deepcopy(game) game_copy.make_moves_from_list(available_moves) starts = True if starting_player == PLAYER_TWO: starts = False if starts == is_maximizing: number_of_moves += len(available_moves) result = Board.minimax_with_alpha_beta_heuristics(game_copy, depth - 1, alpha, beta, True, starting_player, number_of_moves)[0] del game_copy if result < best_val: best_val = result chosen_moves = available_moves beta = min(beta, result) if beta <= alpha: break return best_val, chosen_moves def visualize_board(self): for hole in self.holes[1:7]: print(' ' + str(hole.stones) + ' ', end='') print('\n' + str(self.holes[0].stones) + 15 * ' ' + str(self.holes[7].stones)) for hole in self.holes[13:7:-1]: print(' ' + str(hole.stones) + ' ', end='') print('\n') def ai_simulation(self): end = False while not end: print(self.get_available_moves()) print(Board.minimax(self, 5, self.player_turn)) last = self.ai_random_move() self.check_if_stone_takes_opposite_hole(last) self.decide_turn(last) end = self.check_if_the_game_is_finished() print("The game has ended!") print("AI 1 score: ", self.holes[7].stones) print("AI 2 score: ", self.holes[0].stones) def ai_simulation_minimax(self, depth): last = self.ai_random_move() self.check_if_stone_takes_opposite_hole(last) self.decide_turn(last) end = self.check_if_the_game_is_finished() while not end: Board.ai_minimax_move(self, depth) self.visualize_board() end = self.check_if_the_game_is_finished() print("The game has ended!") print("AI 1 score: ", self.holes[7].stones) print("AI 2 score: ", self.holes[0].stones) def ai_simulation_alpha_beta(self, depth): last = self.ai_random_move() self.check_if_stone_takes_opposite_hole(last) self.decide_turn(last) end = self.check_if_the_game_is_finished() while not end: Board.ai_alpha_beta_move(self, depth) self.visualize_board() end = self.check_if_the_game_is_finished() print("The game has ended!") print("AI 1 score: ", self.holes[7].stones) print("AI 2 score: ", self.holes[0].stones) def ai_simulation_heuristics(self, depth): last = self.ai_random_move() self.check_if_stone_takes_opposite_hole(last) self.decide_turn(last) end = self.check_if_the_game_is_finished() while not end: Board.ai_heuristics_move(self, depth) self.visualize_board() end = self.check_if_the_game_is_finished() print("The game has ended!") print("AI 1 score: ", self.holes[7].stones) print("AI 2 score: ", self.holes[0].stones) if __name__ == '__main__': avg_time = 0 avg_moves = 0 iters = 5 for i in range(iters): b = Board() start = timer() b.ai_simulation_minimax(3) # b.ai_simulation_alpha_beta(3) # b.ai_simulation_heuristics(4) end = timer() avg_time += (end - start) print(end - start) print(COUNTER_FIRST, COUNTER_SECOND) if b.holes[0].stones > b.holes[7].stones: avg_moves += COUNTER_SECOND else: avg_moves += COUNTER_FIRST COUNTER_SECOND, COUNTER_FIRST = 0, 0 print('-----------------------------------') print(avg_time / iters) print(avg_moves / iters) # b = Board() # b1 = Board() # b.ai_simulation_minimax(3) print('-------------------------') print(MOVES_ONE / iters, MOVES_TWO / iters) # b1.ai_simulation_heuristics(4)
#!/usr/bin/env python # # filemap.py # # Sort a list of files into a dict of separate lists by suffix # For, like, tests and stuff # (c) 2015-2019 Alexander Bohn, All Rights Reserved # from __future__ import print_function, unicode_literals def filemapper(files): """ Sort a list of files into a dict of separate lists by suffix """ return dict( jpg = [f for f in files if f.endswith('jpg')], jpeg = [f for f in files if f.endswith('jpeg')], png = [f for f in files if f.endswith('png')], tif = [f for f in files if f.endswith('tif')], tiff = [f for f in files if f.endswith('tiff')], hdf5 = [f for f in files if f.endswith('hdf5')], pvr = [f for f in files if f.endswith('pvr')])
from nodo import* class Lista_simple: # Constructor def __init__(self): self.head=None self.tail=None self.size=0 # Metódo insertar def insert(self, info): newNodo=Nodo_lista(information=info) if self.head == None: self.head=self.tail=newNodo print('Se inserto al principio de la lista') else: self.tail.next=newNodo self.tail=newNodo print('Se inserto') self.size+=1 print(self.size) # Metódo mostrar def show(self): if self.head == None: print('La lista esta vacia') else: current_node=self.head while current_node != None: current_node.information.show_datos() current_node=current_node.next print('None') # Metodo existe el nombre del terreno def exist(self, name): new_node=self.head if new_node == None: print('La lista esta vacia') return False else: node_exist=False new_node=self.head while new_node != None: if new_node.information.get_name() == name: print('Ya existe no se agrego :(') node_exist=True new_node=new_node.next return node_exist # Metódo buscar el nombre del terreno def search(self,name): new_node=self.head if self.head == None: print('La lista esta vacia') else: while new_node != None: if new_node.information.get_name() == name: return new_node.information new_node=new_node.next
import turtle oct = turtle.Turtle() oct.pensize(5) oct.color("yellow") oct.fillcolor("orange") oct.begin_fill() for p in range(1, 8): oct.right(45) oct.forward(100) oct.right(45) oct.forward(100) oct.end_fill() turtle.done()
import turtle bob = turtle.Turtle() bob.shape('square') bob.speed(0) for i in range (100): bob.forward(i) bob.left(360/5)
'''name = input("Please enter your name: ") prompt = "If you tell us who you are, we can personalize the massages you see." prompt += "\nWhat is your first name? " name = input(prompt) print(f"\nHello, {name}!")''' def get_formatted_name(first_name, last_name, middle_name=''): """Return a full name, neatly formatted.""" full_name = f"{first_name} {last_name}" return full_name.title() while True: print("\nPlease tell me your name: ") print("(Enter 'q' at anytime to quite)") f_name = input("First Name: ") if f_name == 'q': break l_name = input("Last Name: ") if l_name == 'q': break formatted_name = get_formatted_name(f_name, l_name) print(f"\nHello, {formatted_name}")
fav_fruit = ['oranges','grapes','cherries'] for fruit in fav_fruit: if fruit == 'apples': print("I really like bananas instead") if fruit == 'pears': print("I really like bananas instead") if fruit == 'bananas': print("I really like bananas instead") if fruit == 'limes': print("I really like bananas instead") if fruit == 'cherries': print("I really like bananas instead")
requested_toppings = ['mushrooms','green preppers','extra cheese'] if 'mushrooms' in requested_toppings: print("Adding mushrooms.") if 'pepperoni' in requested_toppings: print("Adding pepperoni.") if 'extra cheese' in requested_toppings: print("Adding extra cheese") print("\nFinished making your pizza!\n") for topping in requested_toppings: print(f"Adding {topping}!") print("\nFinished making your pizza!\n") for topping in requested_toppings: if topping == 'green preppers': print(f"Sorry but we are out of {topping}") else: print(f"Adding {topping}!") print("\nFinished making your pizza!\n") requested_toppings = [] if requested_toppings: for topping in requested_toppings: print(f"Adding {topping}") print("\nFinished making your pizza") else: print("Are you sure you want a plain pizza?\n") avilable_toppings = ['mushrooms','olives','green preppers','pepperoni','pineapple','extra cheese'] requested_toppings = ['mushrooms','french fries','extra cheese'] for requested_topping in requested_toppings: if requested_topping in avilable_toppings: print(f"Adding {requested_topping}") else: print(f"We dont have {requested_topping}") print("\nFinished making your pizza!")
# Start with some designs that need to be printed. unprinted_designs = ['phone case','robot pendant','dodecahedron'] completed_models = [] # Simulate printing each design, until none are left. # Move each design to completed_models after printing. while unprinted_designs: current_design = unprinted_designs.pop() print(f"Printing model: {current_design}") completed_models.append(current_design) # Display all completed models. print("\nThe following models have been printed.") for completed_model in completed_models: print(completed_model) import printing_functions unprinted_designs = ['phone case','robot pendant','dodecahedron'] completed_models = [] printing_functions.print_models(unprinted_designs, completed_models) printing_functions.show_completed_models(completed_models)
from random import choice lotto_numbers = ['1', '23', '20', '15'] lotto_letters = ['r', 'd', 'w', 'g'] win_ticket = [] my_ticket = ['1', 'r', '23', 'w', '15', 'g', '20', 'd'] num_lett = 1 lotto_tries = 1 my_ticket.sort() while win_ticket != my_ticket: win_ticket = [] if num_lett <= 4: win_number = choice(lotto_numbers) win_ticket.append(win_number) win_letter = choice(lotto_letters) win_ticket.append(win_letter) num_lett += 1 print(num_lett) lotto_tries += 1 win_ticket.sort() #print(lotto_tries) print(f"You have finally won the lotto it took you {lotto_tries} tries!") #print("Who ever has these winning numbers and letters on their ticket wins a prize!") #print(win_ticket)
rivers = {'nile': "egypt", 'mississippi': 'usa', 'amazon': 'brazil'} for river, contury in rivers.items(): if contury == 'usa': print(f"The {river.title()} runs though {contury.upper()}.") else: print(f"The {river.title()} runs though {contury.title()}.") for river in rivers.keys(): print(river) for contury in rivers.values(): print(contury)
person_0 = {'first_name': 'Manny', 'last_name': 'Terrazas', 'age': 38, 'city': 'Huffman'} person_1 = {'first_name': 'Fred', 'last_name': 'Bock', 'age': 60, 'city': 'Pasadena'} person_2 = {'first_name': 'Jeremy', 'last_name': 'Easten-Marks', 'age': 40, 'city': 'Houston'} people = [person_0, person_1, person_2] f_name = person_0['first_name'].title() l_name = person_0['last_name'].title() age_0 = person_0['age'] city_0 = person_0['city'].title() print(f"First Name: {f_name}") print(f"Last Name: {l_name}") print(f"Age: {age_0}") print(f"City: {city_0}") for person in people: print(f"\n Full Name: {person['first_name'].title()} {person['last_name']}") print(f"\t Age: {person['age']}") print(f"\t Location: {person['city']}")
num_user = int(input('Введите положительное число: ')) num = num_user max_num = 0 while num > 0: if num % 10 > max_num: max_num = num % 10 num = num // 10 print(f'В числе "{num_user}" -> максимальное число "{max_num}"')
#!/usr/bin/env python import argparse, random parser = argparse.ArgumentParser(description="Generates the name of the next GiSHWheS hybridized mascot animal.") parser.add_argument(("-f", "--file"), nargs=1, action='store') animals = [ "bear", "el>e<phant", "oct>o<pus", "pig", "cat", "din>o<saur", "mite", "wolf", "r>oo<ster"] left = random.choice(animals) right = left while (right == left): right = random.choice(animals) if ('<' in left): left = left.replace('>', '').split('<')[0] elif ('|' in left): parts = left.split('|') index = random.randint(0, len(parts)) left = ''.join(parts[:index]) if ('>' in right): right = right.replace('<', '').split('>')[1] if ('|' in right): parts = right.split('|') index = random.randint(0, len(parts)) right = ''.join(parts[index:]) print("{}{}".format(left, right))
class Solution(object): def deckRevealedIncreasing(self, deck): """ :type deck: List[int] :rtype: List[int] """ deck.sort(reverse=True) reveal = [] for num in deck: if len(reveal) > 1: tmp_pop = reveal.pop() reveal.insert(0,tmp_pop) reveal.insert(0,num) return reveal def main(): input = [17,13,11,2,3,5,7] ans = Solution().deckRevealedIncreasing(input) print(ans) if __name__ == "__main__": main()
#Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ root = None for num in preorder: root = self.addnode(root,num) return root def addnode(self, root, num): if root: if num < root.val: root.left = self.addnode(root.left,num) if num > root.val: root.right = self.addnode(root.right,num) return root else: return TreeNode(num) def main(): input = [8,5,1,7,10,12] ans = Solution().bstFromPreorder(input) print(ans) if __name__ == "__main__": main()
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): path = 0 def distributeCoins(self, root): """ :type root: TreeNode :rtype: int """ self.path = 0 self.backtrace(root) return self.path def backtrace(self, root): val = root.val nodes = 1 if root.right: v,n = self.backtrace(root.right) val += v nodes += n self.path += abs(v - n) if root.left: v,n = self.backtrace(root.left) val += v nodes += n self.path += abs(v - n) return val,nodes def main(): input = TreeNode(1) input.right = TreeNode(0) input.left = TreeNode(0) input.left.right = TreeNode(3) ans = Solution().distributeCoins(input) print(ans) if __name__ == "__main__": main()
import matplotlib import matplotlib.pyplot as plt def extract_data(filename): file = open(filename, "r") data = [] # getting rid of first line line = file.readline() # extracting rest of the data while(True): line = file.readline() if (line == ""): break else: line = line.split(",") data.append([float(line[0]), float(line[1])]) file.close() return data def clean(data): print(data) for item in data: if item[1] == -1: del item return data def normalize(data, y_max): length = len(data) x_max = data[length-1][0] x_list = [item[0]/x_max for item in data] y_list = [item[1]/y_max for item in data] normalized_data = [] for i in range(length): normalized_data.append([x_list[i], y_list[i]]) return normalized_data def graph(data, color, name): x_data = [item[0] for item in data] y_data = [item[1] for item in data] plt.plot(x_data, y_data, color, label=name) if __name__ == '__main__': print("\n" "This program will graph both the truth data and algorithm results" "onto the same graph with a normalized x and y axis.\n" "To run the program:\n" "1. Must have the truth data file named \"truth_data.csv\" in same directory.\n" "2. Must have algorithm results file (.csv) in same directory\n" "3. Must know the maximum y-value for your algorithm results (i.e. height of your cv2 window)" "\n") # truth data filename1 = "truth_data.csv" data1 = extract_data(filename1) normalized_data1 = normalize(data1, 10) graph(normalized_data1, "r", "Hand-Measured Result") # algorithm results filename2 = input("Input \".csv\" file here: ") y_max = input("Input maximum y-value here: ") data2 = extract_data(filename2) normalized_data2 = normalize(data2, int(y_max)) graph(normalized_data2, "g", "Histogram-Calculated Result") # configuring graph plt.title("Lane Detection Results") plt.xlabel("Time (Normalized)") plt.ylabel("Distance to Lane (Normalized)") fig = matplotlib.pyplot.gcf() fig.set_size_inches(16, 8) plt.legend(loc='upper right') plt.grid(True) plt.show()
# DSA-Assgn-16 class Queue: def __init__(self, max_size): self.__max_size = max_size self.__elements = [None]*self.__max_size self.__rear = -1 self.__front = 0 def is_full(self): if(self.__rear == self.__max_size-1): return True return False def is_empty(self): if(self.__front > self.__rear): return True return False def enqueue(self, data): if(self.is_full()): print("Queue is full!!!") else: self.__rear += 1 self.__elements[self.__rear] = data def dequeue(self): if(self.is_empty()): print("Queue is empty!!!") else: data = self.__elements[self.__front] self.__front += 1 return data def display(self): for index in range(self.__front, self.__rear+1): print(self.__elements[index]) def get_max_size(self): return self.__max_size # You can use the below __str__() to print the elements of the DS object while debugging def __str__(self): msg = [] index = self.__front while(index <= self.__rear): msg.append((str)(self.__elements[index])) index += 1 msg = " ".join(msg) msg = "Queue data(Front to Rear): "+msg return msg class Stack: def __init__(self, max_size): self.__max_size = max_size self.__elements = [None]*self.__max_size self.__top = -1 def is_full(self): if(self.__top == self.__max_size-1): return True return False def is_empty(self): if(self.__top == -1): return True return False def push(self, data): if(self.is_full()): print("The stack is full!!") else: self.__top += 1 self.__elements[self.__top] = data def pop(self): if(self.is_empty()): print("The stack is empty!!") else: data = self.__elements[self.__top] self.__top -= 1 return data def display(self): if(self.is_empty()): print("The stack is empty") else: index = self.__top while(index >= 0): print(self.__elements[index]) index -= 1 def get_max_size(self): return self.__max_size # You can use the below __str__() to print the elements of the DS object while debugging def __str__(self): msg = [] index = self.__top while(index >= 0): msg.append((str)(self.__elements[index])) index -= 1 msg = " ".join(msg) msg = "Stack data(Top to Bottom): "+msg return msg def separate_boxes(box_stack): temp_stack = Stack(box_stack.get_max_size()) counter = box_stack.get_max_size() res_queue = Queue(box_stack.get_max_size()) while counter > 0: item = box_stack.pop() if item.lower() == "red" or item.lower() == "blue" or item.lower() == "green": temp_stack.push(item) else: res_queue.enqueue(item) counter -= 1 while not temp_stack.is_empty(): box_stack.push(temp_stack.pop()) return res_queue # Use different values for stack and test your program box_stack = Stack(8) box_stack.push("Red") box_stack.push("Magenta") box_stack.push("Yellow") box_stack.push("Red") box_stack.push("Orange") box_stack.push("Green") box_stack.push("White") box_stack.push("Purple") print("Boxes in the stack:") box_stack.display() result = separate_boxes(box_stack) print() print("Boxes in the stack after modification:") box_stack.display() print("Boxes in the queue:") result.display()
class Apparel: counter = 100 def __init__(self, price, item_type): Apparel.counter += 1 self.__item_id = "" if item_type.lower() == "cotton": self.__item_id = "C" + str(Apparel.counter) else: self.__item_id = "S" + str(Apparel.counter) self.__price = price self.__item_type = item_type def calculate_price(self): self.__price += self.__price * 0.05 def get_item_id(self): return self.__item_id def get_price(self): return self.__price def get_item_type(self): return self.__item_type def set_price(self, price): self.__price = price class Cotton(Apparel): def __init__(self, price, discount): super().__init__(price, "Cotton") self.__discount = discount def calculate_price(self): super().calculate_price() price = self.get_price() price -= price * (self.__discount / 100) price += price * 0.05 self.set_price(price) def get_discount(self): return self.__discount class Silk(Apparel): def __init__(self, price): self.__price = price self.__points = 0 super().__init__(self.__price, "Silk") def calculate_price(self): super().calculate_price() if self.get_price() > 10000: self.__points = 10 else: self.__points = 3 self.set_price(self.get_price()+(self.get_price()*0.1)) def get_points(self): return self.__points
from threading import Thread def func1(): result_sum = 0 # Write the code to find the sum of numbers from 1 to 10000000 for i in range(10000000): result_sum += i print("Sum from func1:", result_sum) def func2(): result_sum = 0 # Write the code to accept 5 numbers from user and find its sum for i in range(5): result_sum += int(input("Enter next number:")) print("Sum from func2:", result_sum) thread1 = Thread(target=func1) thread1.start() thread2 = Thread(target=func2) thread2.start() thread1.join() thread2.join()
import random def find_it(num,element_list): no_of_guesses = 0 for i in element_list: no_of_guesses += 1 if i == num: return no_of_guesses else: pass #Initializes a list with values 1 to n in random order and returns it def initialize_list_of_elements(n): list_of_elements=[] for i in range(1,n+1): list_of_elements.append(i) mid=n//2 for j in range(0,n): index1=random.randrange(0,mid) index2=random.randrange(mid,n) num1=list_of_elements[index1] list_of_elements[index1]=list_of_elements[index2] list_of_elements[index2]=num1 return list_of_elements def play(n): elems = initialize_list_of_elements(n) rand_num = random.randrange(1,n+1) print(find_it(rand_num,elems)) #Pass different values to play() and observe the output play(400)
# DSA-Assgn-12 class Queue: def __init__(self, max_size): self.__max_size = max_size self.__elements = [None]*self.__max_size self.__rear = -1 self.__front = 0 def is_full(self): if(self.__rear == self.__max_size-1): return True return False def is_empty(self): if(self.__front > self.__rear): return True return False def enqueue(self, data): if(self.is_full()): print("Queue is full!!!") else: self.__rear += 1 self.__elements[self.__rear] = data def dequeue(self): if(self.is_empty()): print("Queue is empty!!!") else: data = self.__elements[self.__front] self.__front += 1 return data def display(self): for index in range(self.__front, self.__rear+1): print(self.__elements[index]) def get_max_size(self): return self.__max_size # You can use the below __str__() to print the elements of the DS object while debugging def __str__(self): msg = [] index = self.__front while(index <= self.__rear): msg.append((str)(self.__elements[index])) index += 1 msg = " ".join(msg) msg = "Queue data(Front to Rear): "+msg return msg class Ball: def __init__(self, color, name): self.__color = color self.__name = name def __str__(self): return (self.__color+" "+self.__name) def get_color(self): return self.__color def get_name(self): return self.__name # Implement Game class here class Game: def __init__(self, ball_stack): self.ball_stack = ball_stack self.ball_container = [] self.red_balls_container = [] self.green_balls_container = [] self.blue_balls_container = [] self.yellow_balls_container = [] def grouping_based_on_color(self): while not self.ball_stack.is_empty(): temp = self.ball_stack.dequeue() if temp.get_color() == 'Red': self.red_balls_container.append(temp) elif temp.get_color() == 'Blue': self.blue_balls_container.append(temp) elif temp.get_color() == 'Green': self.green_balls_container.append(temp) elif temp.get_color() == 'Yellow': self.yellow_balls_container.append(temp) def rearrange_balls(self): temp = self.red_balls_container[0] self.red_balls_container = self.red_balls_container[1:] self.red_balls_container.insert(1, temp) temp = self.blue_balls_container[0] self.blue_balls_container = self.blue_balls_container[1:] self.blue_balls_container.insert(1, temp) temp = self.green_balls_container[0] self.green_balls_container = self.green_balls_container[1:] self.green_balls_container.insert(1, temp) temp = self.yellow_balls_container[0] self.yellow_balls_container = self.yellow_balls_container[1:] self.yellow_balls_container.insert(1, temp) def display_ball_details(self): pass # Use different values to test your program ball1 = Ball("Red", "A") ball2 = Ball("Blue", "B") ball3 = Ball("Yellow", "B") ball4 = Ball("Blue", "A") ball5 = Ball("Yellow", "A") ball6 = Ball("Green", "B") ball7 = Ball("Green", "A") ball8 = Ball("Red", "B") ball_list = Queue(8) ball_list.enqueue(ball1) ball_list.enqueue(ball2) ball_list.enqueue(ball3) ball_list.enqueue(ball4) ball_list.enqueue(ball5) ball_list.enqueue(ball6) ball_list.enqueue(ball7) ball_list.enqueue(ball8) g = Game(ball_list) g.grouping_based_on_color() # Create objects of Game class, invoke the methods and test the program
def find_leap_years(given_year): list_of_leap_years = [given_year] for i in range(15): list_of_leap_years.append(list_of_leap_years[i] + 4) return list_of_leap_years list_of_leap_years = find_leap_years(2000) print(list_of_leap_years)
def count_strings(number): a = [0 for i in range(number)] b = [0 for i in range(number)] a[0] = b[0] = 1 for i in range(1, number): a[i] = a[i-1] + b[i-1] b[i] = a[i-1] return a[number-1] + b[number-1] # Pass different values to the function and test your program number = 3 print("The number of strings that can be made are:", count_strings(number))
def find_pairs_of_numbers(num_list, n): pairs = 0 for i in range(len(num_list)): for j in range(i+1, len(num_list)): if (num_list[i] + num_list[j]) == n: pairs += 1 return pairs num_list = [1, 2, 7, 4, 5, 6, 0, 3] n = 6 print(find_pairs_of_numbers(num_list, n))
def last_instance(num_list, start, end, key): first = -1 last = -1 for i in range(len(num_list)): if not num_list[i] == key: continue if first == -1: first = i last = i return last num_list = [1, 1, 2, 2, 3, 4, 5, 5, 5, 5] start = 0 end = len(num_list)-1 key = 5 # Number to be searched # Pass different values for num_list, start,end and key and test your program result = last_instance(num_list, start, end, key) if(result != -1): print("The index position of the last occurrence of the number:", result) else: print("Number not found")
import sqlite3 from tkinter import * from tkinter import messagebox class DB: def __init__(self): self.conn = sqlite3.connect("Student_record.db") self.cur = self.conn.cursor() self.cur.execute( "CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY, fname TEXT, lname TEXT, sgpa DOUBLE)") self.conn.commit() def __del__(self): self.conn.close() def view(self): self.cur.execute("SELECT * FROM student") rows = self.cur.fetchall() return rows def insert(self, fname, lname, sgpa): self.cur.execute("INSERT INTO student VALUES (NULL,?,?,?)", (fname, lname, sgpa)) self.conn.commit() self.view() def update(self, id, fname, lname, sgpa): self.cur.execute("UPDATE student SET fname=?, lname=?, sgpa=? WHERE id=?", (fname, lname, sgpa, id)) self.view() def delete(self, id): self.cur.execute("DELETE FROM student WHERE id=?", (id,)) self.conn.commit() self.view() def search(self, fname="", lname="", sgpa=""): self.cur.execute("SELECT * FROM student WHERE fname=? OR lname=? OR sgpa=?", (fname, lname, sgpa)) rows = self.cur.fetchall() return rows db = DB() def get_selected_row(event): global selected_tuple index = list1.curselection()[0] selected_tuple = list1.get(index) e1.delete(0, END) e1.insert(END, selected_tuple[1]) e2.delete(0, END) e2.insert(END, selected_tuple[2]) e3.delete(0, END) e3.insert(END, selected_tuple[3]) def view_command(): list1.delete(0, END) for row in db.view(): list1.insert(END, row) def search_command(): list1.delete(0, END) for row in db.search(fname_text.get(), lname_text.get(), sgpa_text.get()): list1.insert(END, row) def add_command(): db.insert(fname_text.get(), lname_text.get(), sgpa_text.get()) list1.delete(0, END) list1.insert(END, (fname_text.get(), lname_text.get(), sgpa_text.get())) def delete_command(): db.delete(selected_tuple[0]) def update_command(): db.update(selected_tuple[0], fname_text.get(), lname_text.get(), sgpa_text.get()) window = Tk() window.title("STUDENT SEARCH APP") def on_closing(): dd = db if messagebox.askokcancel("Quit", "Do you want to quit?"): window.destroy() del dd window.protocol("WM_DELETE_WINDOW", on_closing) # handle window closing lbl_title = Label(window, text = "STUDENT SEARCH APP", font=('arial', 15)) lbl_title.grid(row=0, column=1) l1 = Label(window, text="First Name:") l1.grid(row=1, column=1) l2 = Label(window, text="Last Name:") l2.grid(row=2, column=1) l3 = Label(window, text="Marks(SGPA):") l3.grid(row=3, column=1) l4 = Label(window, text="DISPLAY OF RECORDS") l4.grid(row=4, column=0) fname_text = StringVar() e1 = Entry(window, textvariable=fname_text) e1.grid(row=1, column=2) lname_text = StringVar() e2 = Entry(window, textvariable=lname_text) e2.grid(row=2, column=2) sgpa_text = StringVar() e3 = Entry(window, textvariable=sgpa_text) e3.grid(row=3, column=2) list1 = Listbox(window, height=6, width=35) list1.grid(row=4, column=0, rowspan=6, columnspan=2) sb1 = Scrollbar(window) sb1.grid(row=4, column=2, rowspan=6) list1.configure(yscrollcommand=sb1.set) sb1.configure(command=list1.yview) list1.bind('<<ListboxSelect>>', get_selected_row) b1 = Button(window, text="View all", width=12, command=view_command) b1.grid(row=4, column=3) b2 = Button(window, text="Search entry", width=12, command=search_command) b2.grid(row=5, column=3) b3 = Button(window, text="Add entry", width=12, command=add_command) b3.grid(row=6, column=3) b4 = Button(window, text="Update selected", width=12, command=update_command) b4.grid(row=7, column=3) b5 = Button(window, text="Delete selected", width=12, command=delete_command) b5.grid(row=8, column=3) b6 = Button(window, text="Close", width=12, command=window.destroy) b6.grid(row=9, column=3) window.mainloop()
#! /usr/bin/env python3 # This program searches all plain text files in a folder for a user-inputted regex. import os, re, sys # Prompts user to input regex. userRegex = re.compile(input('Enter your chosen regex:\n'), re.I) # Prompts user to input file path. path = input('Please enter your chosen folder with file path:\n') # Checks that file path is valid. while True: if os.path.exists(path) == True: break else: print('Sorry, I can\'t find this file path.') sys.exit() # Opens and reads all files in folder with .txt extension. # Finds and prints all instances of user's regex. fileList = os.listdir(path) for file in fileList: if file.endswith('.txt'): print(os.path.join(path, file)) content = open(os.path.join(path, file), 'r+') text = content.read() result = userRegex.findall(text) print(result)
#Dependencies/Modules import os import csv #path to budget to open csv file budget_data_csv = os.path.join("Resources", "budget_data.csv") #opens budget_data csv to manipulate data for report with open(budget_data_csv, newline='') as budget: budget_reader = csv.reader(budget, delimiter=',') budget_header = next(budget_reader) month_counter = 0 month_list = [] profit_loss_total = 0 profit_loss_list = [] for row in budget_reader: #make month list month_list.append(row[0]) #number of months month_counter += 1 #sum of profit/loss total profit_loss_total = int(row[1]) + profit_loss_total profit_loss_list.append(int(row[1])) #since I want to find the average of each, i will make a list of pairs to evaluate pair_of_values = zip(profit_loss_list[:-1], profit_loss_list[1:]) #above created tuple list of differences #at each index (x,y) where x is the profit loss list without the last value and y is the same list without the first value #list comprehension finding difference with the list of pairs to evaluate differences_profit_loss = [((y - x)) for (x, y) in pair_of_values] #average change of complete data average_change = (sum(differences_profit_loss)/(len(differences_profit_loss))) #finding max change max_difference = max(differences_profit_loss) find_max_month_index = differences_profit_loss.index(max_difference) #i want the month that is largest/smallest #since the list of tuples shifted the index by 1, I have to add 1 #max month max_month = month_list[(find_max_month_index + 1)] #finding min month min_difference = min(differences_profit_loss) find_min_month_index = differences_profit_loss.index(min_difference) min_month = month_list[(find_min_month_index + 1)] #prints report to terminal #used format method for see report variables better #f notation can be used too, .2f is 2 decimal places with float variable report_to_print =( ''' Financial Analysis ---------------------------- Total Months: {} Total: ${} Average Change: ${:.2f} Greatest Increase in Profits: {} $({}) Greatest Decrease in Profits: {} $({}) ``` '''.format(month_counter, profit_loss_total, average_change, max_month, max_difference, min_month, min_difference)) print(report_to_print) #writes financial_report.txt to same folder as main.py with open('financial_report.txt', 'w', newline='') as finance_report: finance_report.write(report_to_print) #test print for each variable # print(month_counter) # print(profit_loss_total) # print(average_change) # print(max_month) # print(max_difference) # print(min_month) # print(min_difference)
# functions # A function is a group of related statements that performs a specific task. # Creating a function def my_function(): print("Hello My Name Is Rohan!") # Calling a function my_function() # Parameter and Arguments def greet(name): print("Hello", name) print("How do you do?") # calling function by passing arguments greet("Amit") # Return value from a function def add_numbers(n1, n2): result = n1 + n2 return result result = add_numbers(5.4, 6.7) print("The sum is", result) # Example # find the average marks and return it def find_average_marks(marks): sum_of_marks = sum(marks) number_of_subjects = len(marks) average_marks = sum_of_marks/number_of_subjects return average_marks # compute grade and return it def compute_grade(average_marks): if average_marks >= 80.0: grade = 'A' elif average_marks >= 60: grade = 'B' elif average_marks >= 50: grade = 'C' else: grade = 'F' return grade marks = [55, 64, 75, 80, 65] average_marks = find_average_marks(marks) grade =compute_grade(average_marks) print("Your average marks is", average_marks) print("Your grade is", grade) # Positional Arguments # Positional arguments are the arguments that need to be passed to the function call in a proper order. def add(n1, n2): result = n1 + n2 return result result = add(100, 200) print(result) # Default Arguments def add_default(n1 = 100, n2 = 1000): result = n1 + n2 return result result = add_default(5.4) print(result) # Keyword Arguments def greet_you(name, message): print("Hello", name) print(message) greet_you("Jack", "What's going on?") greet_you(message = "Howdy?", name = "Jill") # Lambda function or anonymous function. # A lambda function is a small anonymous function. # A lambda function can take any number of arguments, but can only have one expression. double = lambda x: x * 2 print(double(5))
# Object-Oriented Programming methodologies # Inheritance # When a class derives from another class. # The child class will inherit all the public and protected properties and methods from the parent class. # In addition, it can have its own properties and methods. class employee1(): # This is a parent class def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary class childemployee(employee1): #This is a child class def __init__(self, name, age, salary,id): self.name = name self.age = age self.salary = salary self.id = id emp1 = employee1('Rohan',22,1000) print(emp1.age) # Multilevel Inheritance #Multi-level inheritance enables a derived class to inherit properties from an immediate parent class # which in turn inherits properties from his parent class. class employee2(): # Super class def __init__(self,name,age,salary): self.name = name self.age = age self.salary = salary class childemployee1(employee2): # First child class def __init__(self,name,age,salary): self.name = name self.age = age self.salary = salary class childemployee2(childemployee1): #Second child class def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary emp1 = employee2('Anirruddha',22,1000) emp2 = childemployee1('Siddhesh',23,2000) print(emp1.age) print(emp2.age) # Hierarchical Inheritance: # Hierarchical level inheritance enables more than one derived class to inherit properties from a parent class. class employee3(): def __init__(self, name, age, salary): #Hierarchical Inheritance self.name = name self.age = age self.salary = salary class childemployee3(employee3): def __init__(self,name,age,salary): self.name = name self.age = age self.salary = salary class childemployee4(employee3): def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary emp1 = employee3('Rohan',22,1000) emp2 = employee3('Amit',23,2000) print(emp1.age) print(emp2.age) # Multiple Inheritance: # Multiple level inheritance enables one derived class to inherit properties from more than one base class. class employee4(): #Parent class def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary class employee5(): #Parent class def __init__(self,name,age,salary,id): self.name = name self.age = age self.salary = salary self.id = id class childemployee5(employee4,employee5): def __init__(self, name, age, salary,id): self.name = name self.age = age self.salary = salary self.id = id emp1 = employee4('John',22,1000) emp2 = employee5('Cena',23,2000,1234) print(emp1.age) print(emp2.id)
# Tuples are used to store multiple items in a single variable. # A tuple is a collection which is ordered and unchangeable. # Tuples are written with round brackets. # tuples are ordered, it means that the items have a defined order, and that order will not change. # Tuple items allow duplicate values. # To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. # Create a tuple thistuple = ("apple", "banana", "cherry") print(thistuple) # Tuple with single item singletuple = ("apple",) print(type(singletuple)) #Access Tuple Items accesstuple = ("apple", "banana", "cherry") print(accesstuple[1]) # Indexing in tuple is same as list # Update tuple # Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. # But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple. x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print(x) # Remove Items # Tuples are unchangeable, so you cannot remove items from it, # but you can use the same workaround as we used for changing and adding tuple items. removetuple = ("apple", "banana", "cherry") y = list(removetuple) y.remove("apple") removetuple = tuple(y) # Delete tuple thistuple = ("apple", "banana", "cherry") del thistuple print(thistuple) # Unpacking tuple fruits = ("apple", "banana", "cherry") (green, yellow, red) = fruits print(green) print(yellow) print(red) # Join two tuples tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3)
''' Author : Shyam Ramkumar Given a source file and target file, the program compares the files and provides an output. The output contains each line of source and how many times have the occured in a given target file. ''' import glob import csv import time #from re import search def main(): ''' Main function to be called in the python program. Contains: input file path or source file path Target directory path containing list of files to be read and compared with Output file path to write the output of the program ''' input_file_path = r"C:\Users\sramkumar\Desktop\customer\Sheik\Folder.txt" target_dir = r"C:\Users\sramkumar\Desktop\customer\Sheik\comparison" output_file_path = r"C:\Users\sramkumar\Desktop\customer\Sheik\output.txt" Anomalypath = [] target_comp_files = [] #Open the input file fin = open(input_file_path,'r') #Read lines and store it in a variable 'input' for item in fin: Anomalypath.append(item) fin.close() #For target file paths in a folder: #store file paths in a variable for filepath in glob.glob(target_dir+"\*.*"): target_comp_files.append(filepath) Fileprocessing(target_comp_files,Anomalypath,output_file_path) def Fileprocessing(target_comp_files,inputfile_lines,output): ''' Compare two list and output occurence of each item in list 1 in list 2 to a dictionary ''' dictout = {} for item in target_comp_files: target_path_list = [] print("Processing File: ", item) #Open target file ftarget = open(item,'r') #Read lines in the file and store in a variable 'target#' for line in ftarget: target_path_list.append(line) ftarget.close() #For each line in 'input': #Set counter to 0 #If line is matching with corresponding line in 'target#' #increment the count #add line in 'input' to dictionary - line and count for line in inputfile_lines: #print("Source: ",line) #time.sleep(1) counter = 0 for target in target_path_list: #print("target: ",target) #time.sleep(1) #print("Result: ",line in target) #if line in target: #due to some reason I get false all the time #if search(str(line),str(target)): if target.find(line.strip()) !=-1: #print(line) #print(target) counter += 1 dictout[line.strip()] = counter fout = open(output,'+a',newline='') #fout.write(item) #fout.write("\n") #fout.write("\n") dic = csv.writer(fout) #fout.write(dictout) cannot write dictionary using write function. This function writes only strings. for key,val in dictout.items(): dic.writerow([key,val]) fout.close() main()
import cv2 import numpy as np face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Assign our face cascade with the attributes of the downloaded xml file. eye_cascade = cv2.CascadeClassifier('HaarCascades/haarcascade_eye.xml') # Assign directory for eye xml file with all eye detection attributes. cap = cv2.VideoCapture(0) # Activate the video camera feed to start filming. while True: ret, img = cap.read() # Assign the true if we are able to video then put the feed into the img variable. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Easier to read from grayscaled images. faces = face_cascade.detectMultiScale(gray, 1.8, 5) # Depending on size and likelihood we would change the numerical values, and we are gonna read from the grayscaled image. for (x,y,w,h) in faces: cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0), 2) # Lets start at x and y until we width and height of the image, and lets draw a blue rectangle around its detection, accompanied with a width of 2. roi_gray = gray[y:y+h, x:x+w] # So the region of image we want is grayscaled, we take the y region till its end and the x region till its end for the found object within the image, and we assign that to our region of the image. # So in summary roi_gray is the region of detection within the image and a rectangle will be surrounding it. roi_color = img[y:y+h, x:x+w] # Same thing as roi_gray but we want to have the colored region saved. # Now we will define the eye detection within the face detection. eyes = eye_cascade.detectMultiScale(roi_gray) # Lets search for eyes within the gray face image. for (ex, ey, ew, eh) in eyes: # Lets draw a green rectangle around we starting and ending points of the eye detection. cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2) cv2.imshow('img', img) k = cv2.waitKey(30) & 0xFF if k == 27: # If we press the escape key terminate. break cap.release() # Turn off the camera. cv2.destroyAllWindows() for i in range(1,5): # As always due to delays of processes we want a waitkey of 4 per window open to fully terminate without freezing. cv2.waitKey(1)
import cv2 import numpy as np img = cv2.imread('bookpage.jpg') retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY) # The threshold here takes the lowest darkness of 12, to a max of 255 and applies the THRESH_BINARY filter. grayscaled = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Grayscale the image retval, threshold2 = cv2.threshold(grayscaled, 12, 255, cv2.THRESH_BINARY) # We are creating a black and white threshold above. gaus = cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) # Adaptive threshold applied to the grayscaled image to enhance white pixels. cv2.imshow('original', img) cv2.imshow('threshold', threshold) cv2.imshow('threshold2', threshold2) cv2.imshow('gaus', gaus) cv2.waitKey(0) cv2.destroyAllWindows() for i in range(1,17): # A range of 8 becayse we have 4 waitKey's per image. cv2.waitKey(1)
A = {5, 3, 8, 6, 1} B = {1, 5, 3, 4, 2} print("A union B : ",A.union(B)) print("A intersection B :",A.intersection(B)) print("A - B : ", A-B) print("Maximum and Minimum values of A : " , max(A),min(A)) print("Maximum and Minimum values of B : " , max(B),min(B))
 import time ##class TreeNode: ## def __init__(self, x): ## self.val = x ## self.left = None ## self.right = None ##class ListNode: ## def __init__(self, x): ## self.val = x ## self.next = None ##class RandomListNode: ## def __init__(self, x): ## self.label = x ## self.next = None ## self.random = None from functools import wraps def wrapper(func): @wraps(func) def wrapper_function(self,*arc): start=time.time() res = func(self,*arc) end = time.time() print(f"Your function used {(end-start):.2f} seconds") print(f'Return value of your function is : \n{res}') return res return wrapper_function class Solution: @wrapper def longestPalindrome(self, s): def palindrome(s, i,j): while i >=0 and j < len(s) and s[i] == s[j]: i -= 1 j += 1 return s[i+1:j] res = '' for i in range(len(s)): r1 = palindrome(s, i, i) if len(r1) > len(res): res = r1 r2 = palindrome(s, i, i+1) if len(r2) > len(res): res = r2 return res def main(): s = Solution() s.longestPalindrome("babad") main()
# SIMPLE TIC N TOE GMAES # Creating the structure of the boar using aDictionaries board = { "T-Left": '-', "T-Middle": '-', "T-Right": '-', "M-Left": '-', "M-Middle": '-', "M-Right": '-', "B-Left": '-', "B-Middle": '-', "B-Right": '-', } def printBoard(): print( """ {a} | {b} | {c} | {d} | {e} | {f} | {g} | {h} | {i} | """ .format( a = board ["T-Left"], b = board ["T-Middle"], c=board ["T-Right"], d = board ["M-Left"], e = board ["M-Middle"], f=board ["M-Right"], g= board ["B-Left"], h = board ["B-Middle"], i=board ["B-Right"], ) ) def playGame(): userTurn= 'X' for i in range(9): printBoard() print("This is " + userTurn + " turn. Make Your move.") turnInput = input() # placing the input on given position board[turnInput] = userTurn # checking the winner checkGameWinner = checkWinner(userTurn) if checkGameWinner: print('Congratulation '+ userTurn + " You are the Winner") break if userTurn == 'X': userTurn = 'O' else: userTurn = 'X' def checkWinner(turn): if board ["T-Left"] == board ["T-Middle"] ==board ["T-Right"] == turn : return True elif board ["M-Left"] == board ["M-Middle"] ==board ["M-Right"] == turn: return True elif board ["B-Left"] == board ["B-Middle"] ==board ["B-Right"] == turn: return True elif board ["T-Left"] == board ["M-Left"] ==board ["B-Left"] == turn: return True elif board ["M-Middle"] == board ["M-Middle"] ==board ["B-Middle"]== turn: return True elif board ["T-Right"] == board ["M-Right"] ==board ["B-Right"]== turn: return True elif board ["T-Left"] == board ["M-Middle"] ==board ["B-Right"]== turn: return True elif board ["T-Right"] == board ["T-Middle"] ==board ["B-Left"]== turn: return True else: return False playGame()
# _*_ coding=utf-8 _*_ __author__ = 'patrick' class Person(object): def __init__(self, name, action): self.name = name self.action = action def do_action(self): print (self.name, self.action.name) return self.action class Action(object): def __init__(self, name): self.name = name def action(self): print(self.name) return self def stop(self): print("then stop") return self if __name__ == '__main__': move = Action("move") person = Person("patrick", move) person.do_action().action().stop().action().stop()
# _*_ coding=utf-8 _*_ __author__ = 'patrick' class MoveFileCommand(object): def __init__(self, src, dest): self.src = src self.dest = dest def rename(self): print "rename {0} to {1}".format(self.src, self.dest) # todo how to invoke method dynamically def execute(self, method_name): # if method_name == "rename": # self.rename() # else: # self.undo() getattr(self, method_name)() def undo(self): print "under rename {0} to {1}".format(self.src, self.dest) if __name__ == '__main__': command_stack = [MoveFileCommand("1", "2"), MoveFileCommand("2", "3")] for command in command_stack: command.execute("rename") command.execute("undo") for cmd in reversed(command_stack): cmd.execute("undo")
import logging from flask import json from actions.util import * def list_wans(api_auth, parameters, contexts): """ Allows users to list all the WANs that are in the organisation Works by calling the list_WANs action defined in api/wans.py Parameters: - api_auth: SteelConnect API object, it contains authentication log in details - parameters: The json parameters obtained from the Dialogflow Intent. In this case, we obtain nothing Returns: - speech: A string which has the list of all WANs in the organisation Example Prompt: - List WANs """ logging.info("Listing WANs") res = api_auth.wan.list_wans() if res.status_code == 200: data = res.json()["items"] num_WANs = len(data) if num_WANs == 0: speech = "There are no WANs" elif num_WANs >= 1: speech = "There are {} WANs in the organisation:\n".format(num_WANs) count = 1 for WAN in data: name = WAN["longname"] id = WAN["id"] num_uplinks_attached = len(WAN["uplinks"]) speech += "\n{}. ID: {}\n\t WAN: {}\n\t Number Of Uplinks Attached: {}\n".format(str(count).zfill(len(str(num_WANs))), id, name, num_uplinks_attached) count += 1 else: speech = "Unknown error occurred when retrieving WANs" else: speech = "Error: Could not connect to SteelConnect" logging.debug(speech) return speech
# Utility functions that actions can call on. class APIError(Exception): pass def format_wan_list(items): """ Given the successful result of `api_auth.list_wans().json()["items"]`, returns the list of WANs as a nicely-formatted string suitable for presenting to the user. """ s = "" for wan in items: if wan["longname"] is not None: s += "\n - " + str(wan["name"]) + " (" + wan["longname"] + ")" else: s += "\n - " + str(wan["name"]) return s def get_wan_id_by_name(api_auth, wan_name): """ Given a WAN's short name: - If there is a WAN by that exact name, returns the ID of the first matching WAN. - If no such WAN exists, raises an APIError with a human-readable error string. """ res = api_auth.wan.list_wans() data = res.json()["items"] if res.status_code == 200: for wan in data: if wan["name"] == wan_name: return wan["id"] raise APIError("The WAN '{}' does not exist. Valid WANs (use the name not in brackets):".format(wan_name) + format_wan_list(data)) else: raise APIError("Failed to get the list of WANs") def get_site_id_by_name(api_auth, site_name, city, country_code): """ Given a Site's short name: - If there is a Site by that name city and country, returns the ID of the first matching Site. - If no such site exists, raises an APIError with a human-readable error string. """ res = api_auth.site.list_sites() if res.status_code == 200: data = res.json()["items"] for site in data: if site["name"] == site_name and site["city"] == city and site["country"] == country_code: return site["id"] raise APIError(("The site {} in {} {} does not exist").format(site_name, city, country_code)) elif res.status_code == 400: raise APIError("Invalid parameters: {}".format(res.json()["error"]["message"])) elif res.status_code == 500: raise APIError("Failed to get the list of Sites") else: raise APIError("Error: Could not connect to SteelConnect") def format_sitelink_list(api_auth, items): """ Given the successful result of `api_auth.sitelink.get_sitelinks().json()["items"]`, returns the list of sitelinks as a nicely-formatted string suitable for presenting to the user. Requires `api_auth` to get the names of the remote sites. """ s = "" for link in items: remote_site_name = "" res = api_auth.site.get_site(link["remote_site"]) if res.status_code == 200: remote_site_name = res.json()["name"] else: remote_site_name = "<unknown>" s += "\n - To: {} ({}), Status: {}".format(remote_site_name, link["remote_site"], link["status"]) return s
import logging from flask import json from actions.util import get_site_id_by_name, APIError def delete_site(api_auth, parameters, contexts): """ Allows users to delete a site In order for them to do so, we need to know the city, site name and country code. Works by getting the parameters, and calling the SteelConnect API with the parameters to delete the site. It checks to see if the site does exist, and if it does, it will delete the site. It not, it will let the user know that the site doesn't exist Parameters: - api_auth: SteelConnect API object, it contains authentication log in details - parameters: The json parameters obtained from the Dialogflow Intent. It obtains the following: > city: The city where the user wants to delete the site > country_code: The country code of where the user wants to delete the site + The country name will be obtained from the country code, and will not be directly retrieved from the user > site_name: A name that the user gives the site they want to delete Returns: - speech: A string which has the response to be read/printed to the user Example Prompt: - Delete butterfree site in Penang, Malaysia """ try: site_name = parameters["name"] city = parameters["City"] country_code = parameters["Country"]["alpha-2"] country_name = parameters["Country"]["name"] except KeyError as e: error_string = "Error processing deleteSite intent. {0}".format(e) logging.error(error_string) return error_string # Grab site id by name, city and country try: site_id = get_site_id_by_name(api_auth, site_name, city, country_code) except APIError as e: return str(e) # Deleting site res = api_auth.site.delete_site(site_id) if res.status_code == 200: speech = "The site {} located in {}, {} has been successfully deleted".format(site_name, city, country_name) elif res.status_code == 400: speech = "Invalid parameters: {}".format(res.json()["error"]["message"]) elif res.status_code == 500: speech = "Error: We could not delete the {} site located in {}, {}".format(site_name, city, country_name) else: speech = "Error: Could not connect to SteelConnect" logging.debug(speech) return speech
a=10 b=20 a if a<b else b 10 x=1<2<3 x True x=1<3<2 x False def compare(a,b,c): return a if a<b else b def compare(a,b,c): return a if a<b and a<c else b if b<c and b<a else c