text
stringlengths
37
1.41M
""" Dictiobnaries are unordered mappings for storing objects. previously we saw how lists store onjects n an unordered sequence dictionaries use a key value pair instead This key value pair allows users to quickly grab objects without needing to know an index location Dictionaries use curly braces and colons to signify keys and their associated values {key 1: Value 1, key 2 : Value 2} So when to choose a list and when to choose a dictionary Dictionaries : Objects retrieved by key name Unordered and cannot be sorted. Lists : Objects retrieved by location Ordered sequence can be indexed or sliced """ my_dict={'key1': 'value1','key2': 'value2','key3': 'value3'} print (my_dict) print (my_dict['key1']) prices_lookup={'apple': 2.99, 'oranges':1.99, 'milk': 5.80, 'apple': 3.50} print(prices_lookup['apple']) d={'k1': 123, 'k2':[1,2,3,4,5],'k3': (12,34,'hi'),'k4':{'insidekey':100}} print (d) print (d['k4']) print (d['k4']['insidekey']) d['k2']="567" print (d) d1={'k1':100,'k2':200,'k3':'300'} d1['k4']='400' print (d1) print (d.keys()) print (d.values()) print(d.items())
n=int(input("Digite o valor de n:")) if(n==0): print(1) else: fatorial=1 while(n>0): fatorial=fatorial*n n-=1 print(fatorial)
# -*- coding: utf-8 -*- import math a=float(input("Digite a:")) b=float(input("Digite b:")) c=float(input("Digite c:")) if(b**2 < 4*a*c): print("esta equação não possui raízes reais") else: if(b**2 == 4*a*c): x1=(-b + math.sqrt(b**2-4*a*c))/(2*a) print("a raiz desta equação é %0.2f" % x1) else: x1=(-b + math.sqrt(b**2-4*a*c))/(2*a) x2=(-b - math.sqrt(b**2-4*a*c))/(2*a) if(x1<x2): print("as raízes da equação são %0.2f e %0.2f" %(x1,x2)) else: print("as raízes da equação são %0.2f e %0.2f" %(x2,x1)) #O resultado dos testes com seu programa foi: #***** [0.3 pontos]: Testando Báskara com uma raiz real (a = 9, b = -12, c = 4) - Falhou ***** #AssertionError: ('Esta equação tem exatamente uma raiz, mas a resposta recebida foi\n%s', 'a raiz desta equação é X\n') #***** [0.4 pontos]: Testando Báskara com 2 raízes reais (a = 1, b = -3, c = -10) - Falhou ***** #AssertionError: As raízes devem ser listadas em ordem crescente
''' Exercicios da seção 7 do curso pt1 ''' ''' # exercicio 1 total = 0 vetor = [1, 0, 5, -1, -5, 7] total = vetor [0] + vetor[1] + vetor[5] print(total) vetor[4] = 100 print(vetor[4]) print(*vetor, sep= '\n') # exercicio 2 valores = [] for i in range(0,6): print(input('Insira um valor')) valores.append(i) print(valores) # exercicio 3 numquadrado = set({}) num = set({}) for i in range(0, 4): num.add(input('Digite 10 numeros')) print(num) xxxxx # exercicio 4 total = 0 lista = [] for i in range(0,3): lista.append(int(input('Digite 3 numeros'))) for z in lista: total = lista[1] + lista[2] print(total) # exercicio 5 vetor = [] total = 0 for i in range(0,5): vetor.append(int(input('Digite um valor'))) if vetor[i] % 2 == 0: total += 1 print(vetor) print(total) # exercico 6 vetor1 = [] vetor = [[vetor1.append(input('Digite um numero'))] for i in range(0, 5)] print(vetor1) print(max(vetor1)) print(min(vetor1)) # exercicio 7 lista = [] maior = 0 menor = 0 for cont in range(0, 5): lista.append(int(input(f'Digite um valor para a posiçao {cont}'))) if cont == 0: maior = menor = lista[cont] else: if lista[cont] > maior: maior = lista[cont] if lista[cont] < menor: menor = lista[cont] print(f'Os numeros digitados foram: ', lista) print(f'O maior valor foi: {maior} nas posições ', end ='') posMai = [print(f'{i}...') if v == maior else print(end='') for i, v in enumerate(lista)] print(f'O menor valor foi: {menor} nas posições ', end='') posMen = [print(f'{i}...') if v == menor else print(end='') for i, v in enumerate(lista)] # exercicio 8 num = [input(print('Digite um numero')) for i in range(0, 3)] print(num[::-1]) # exercicio 9 numeros = [int(input(print('Digite apenas numeros pares'))) for i in range(0, 5)] print(numeros) pares = [par for par in numeros if par % 2 == 0] print(pares[::-1]) # exercicio 10 notas = [] total = 0 for i in range(0, 5): notas.append(int(input('Digite a nota do aluno '))) print(notas) total = sum(notas) print(total / 5) # exercicio 11 num = [] numeros = [num.append(float(input("Digite um numero "))) for i in range(0, 6)] negativos = [n for n in num if n < 0] positivos = [n for n in num if n > 0] cont = 0 for i in negativos: cont += 1 print('Nessa lista há: ', cont, 'números negativos') print('A soma dos números positivos da lsita é de', sum(positivos)) # exercicio 12 numeros = [] x = [numeros.append(int(input('Digite um numero'))) for i in range(0,5)] max = [max(numeros)] min = [min(numeros)] media = sum(numeros) print('O maior indice é ', max) print('O menor indice é ', min) print('A media dos numeros é de: ', media / 5) # exercicio bonus numerosDict = {0:'zero', 1:'um', 2: 'dois', 'tres': 3, 'quatro': 4, 'cinco': 5, 'seis': 6, 'sete': 7, 'oito': 8, 'nove': 9, 'dez': 10} xxxxxxx for valor,chave in numerosDict.items(): x = int(input('Digite um numero de 0 - 10')) if valor == x: print(f'Voce digitou o numero {chave}') else: print('Não encontrei nenhum numero') exit(0) xxxxx # exercicio 14 lista = [] for i in range(0, 5): lista.append(int(input('Digite um numero'))) num = [] for n in lista: if n == 0: n = lista[n] if n == lista[n]: num.(lista[n]) else: print('Não encontrei nenhum valor repetido') print('Esses valores se repetem na lista: ', num) # exercicio 15 lista = [] repetido = [0] xxxxxxxxxx for i in range(0, 5): lista.append(int(input("Digite um numero"))) repetido= lista.copy() for i in repetido: for n in lista: if repetido[i] == lista[n]: lista.pop(lista[n]) xzxxxxxxxxxxxxx print(lista) # exercicio 16 lista = [] for i in range(0, 5): lista.append(float(input('Digite um numero qualquer'))) cont = int(input('Digite um 1 para ver a lista, 2 para ve-la inversa e 0 para sair')) while cont != 0: if cont == 1: print(lista) if cont == 2: print(lista[::-1]) if cont != 0 or cont != 2 or cont != 1: print('Nenhuma função executada, encerrando') exit(0) else: if cont == 0: exit(0) # exercicio 17 lista = [] for i in range(0, 5): lista.append(int(input('Digite um numero inteiro qualquer'))) if lista[i] < 0: lista[i] = 0 print(lista) # exercicio 18 lista =[] Multiplo = int(input('Digite um numero que deseja encontrar multiplos')) Multiplos = [] for i in range(0,5): lista.append(int(input('Digite um numero inteiro qualquer'))) if Multiplo % lista[i] == 0: Multiplos.append(lista[i]) print(Multiplos) # exercicio 19 lista = [] x = [] for i in range(0, 50): lista.append((i + 5 * i) % (i + 1)) print(lista) # exercicio 20 lista = [] impares = [] x = [] c = 0 y = 0 while c < 5: x = int(input('Digite um numero inteiro entre 0 e 50')) if x < 0 or x > 50: print('Numero Invalido, tente novamente') else: if x > -1 or x < 51: c = c + 1 lista.append(x) if x % 2 !=0: impares.append(x) y = y + 1 print('Os numeros digitados foram: ', lista) print('Os numeros impares são:', impares) # exercicio 21 xxxxxxxxxxxxxxxxxx lista1 = [] lista2 = [] lista3 = [] for i in range(0, 2): lista1.append(int(input('Digite 2 numeros para a lista 1'))) lista2.append(int(input('Digite 2 numeros para a lista 2'))) for i in lista1, lista2: x = lista1[i] - lista2[i] lista3.append(x) print(lista3) ''' # exercicio 22 lista1 = [] lista2 = [] lista3 = [] for i in range(0, 3): lista1.append(int(input('Digite um numero para a lista 1'))) if lista1[i] % 2 == 0: lista3.append(lista1[i]) else: i += 1 lista3.append(lista1[i]) for i in range(0, 3): lista2.append(int(input('Digite um numero para a lista 2'))) if lista2[i] % 2 != 0: lista3.append(lista2[i]) print(f'Lista 1: {lista1}') print(f'Lista 2: {lista2}') print(f'Lista 3: {lista3}') ''' lista = [] maior = 0 menor = 0 for cont in range(0, 5): lista.append(int(input(f'Digite um valor para a posiçao {cont}'))) if cont == 0: maior = menor = lista[cont] else: if lista[cont] > maior: maior = lista[cont] if lista[cont] < menor: menor = lista[cont] '''
variable = "hola" variable = 2 # el nombre de una variale puede ser la misma # pero se ira sustituyendo a medida se cambie su valor, al final va tener el valor ultimo que se le dio a = 9 b = 8 c = 7 suma = a + b resta = a - c multiplicacion = c*a division = b/b divisionEntera = b//c # para conocer el tipo de una variable se coloca la palabra type y dentro de parentesis la variable que se quiere conocer su tipo type(division) #tipos de mensajes mensaje1 = """este es un un mensaje de multiples lineas""" # se debe mantener una identacion que el programa entienda que algo pertenece a algo # para entender simbolos # (=) es para asiganar, # (==) es para comparacion if a > b: print("el numero a es mayor que el numero b") else: print("el numero b es mayor que el numero a") # def nombre_de_la_funcion( zona para recibir parametros): recibe distintos tipos de parametros #recibe instruciones de una funcion #return(opcional) # def nombre_de_la_funcion(parametro): aca ya tiene parametros y ya tiene una funcion establecida que recibira un tipo de parametro #recibe instruciones def mensaje ():#declaracion print("Estamos aprendiendo Python")#cuerpo print("estamos recibiendo instrucciones basicas")#cuerpo print("poco a poco se ira avanzando")#cuerpo # notese que la identacion es necesaria para saber que pertenece a que mensaje()# llamando la funcion #tipos de operadores #Aritmeticos # suma + #resta - #multiplicacion * #division / # modulo % # exponente ** #division entera // #de comparacion #igual que == #mayor qye > #menor que < #diferente que != #mayor igual >= #menor igual que <= #logicos #and (y) #or(o) #not(negacion) # # # # # # # #
#! /usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Tokuume Shinya<g1244785@cc.kyoto-su.ac.jp>" __status__ = "production" __date__ = "22 December 2014" class Tuple(object): """タプル:総理大臣の情報テーブルの中の各々のレコード。""" def __init__(self, attributes, values): """属性リストと値リストからタプルを作るコンストラクタ。""" self.attributes = attributes self.values = values def __str__(self): """自分自身を文字列にして、それを応答する。""" a_str = str(self.__class__.__name__)+'\n' for (attribute,value) in zip(self.attributes,self.values): a_str += str(attribute)+':' a_str += str(value)+'\n' a_str += "\n" return a_str def attributes(self): """属性リストを応答する。""" return self.attributes def values(self): """値リストを応答する。""" return self.values def set_attributes(self,attributes): """属性リストを設定する """ self.attributes = attributes return def set_values(self,values): """値リストを設定する。""" self.values = values return
""" Project Euler Problem 3 Largest Prime Factor: what is he largest prime factor of 600851475143 https://projecteuler.net/problem=3 """ num = 10 prime_list = [] def is_it_prime(number): """ function to check if a number is a prime number """ counter = 2 while counter <= round(number/2): if number % counter == 0: return(False) counter += 1 else: return(True) def highest_prime_factor(number): """ Finds the highest prime factor of a number, if the number is prime this function returns itself. """ counter = 2 while counter <= round(number/2): if number % counter == 0: factor = number/counter if is_it_prime(factor) == True: return(factor) counter += 1 else: return(number)
def DikdortgenAlanCevreHesapla(): uzun_kenar = int(input("Uzun kenarı girin:")) kisa_kenar = int(input("Kısa kenarı girin:")) alan = uzun_kenar * kisa_kenar cevre = (uzun_kenar * 2) + (kisa_kenar * 2) print ("Alanı: ", alan) print ("Çevresi: ", cevre ) while True: DikdortgenAlanCevreHesapla();
import random import numpy as np import matplotlib.pyplot as plt x = [i for i in range(200)] total_cost = [] for i in range(250): if i < 50: cost = random.uniform( (200 - i) * 900, (200 - i) * 1000) total_cost.append(cost) elif i >= 50 and i < 100: cost = random.uniform( (200 - i) * 800, (200 - i) * 900) total_cost.append(cost) elif i >= 100 and i < 150: cost = random.uniform( (200 - i/1.5) * 750, (200 - i) * 800) total_cost.append(cost) else: cost = random.uniform( (200 - i/1.5) * 740, (200 - i) * 770) total_cost.append(cost) plt.figure() plt.plot(x, total_cost) # x=[0,1] # y=[0,1] # plt.figure() # plt.plot(x,y) # plt.xlabel("time(s)") # plt.ylabel("value(m)") # plt.title("A simple plot") plt.show()
def average(numbers): ave = 0 count = 0 for number in numbers: ave = ave + number count = count + 1 return ave/count print(average([1, 5, 9])) print(average(range(11)))
with open('input.txt') as my_file: lines = list(map(lambda x: x.strip('\n'), my_file.readlines())) lines = [line.split(')') for line in lines] planets = {line[1]: line[0] for line in lines} # child: parent santa_ancestors = ['COM'] you_ancestors = ['COM'] '''return a count of objects a planet is directly or indirectly orbiting''' def ancestor_list(you_or_santa): planet = you_or_santa planet = planets[planet] while planet != 'COM': if you_or_santa == 'SAN': santa_ancestors.append(planet) else: you_ancestors.append(planet) planet = planets[planet] return santa_ancestors if you_or_santa == 'SAN' else you_ancestors ancestor_list('SAN') ancestor_list('YOU') def diff(lista, listb): return [item for item in lista if item not in listb] santa_uniques = diff(santa_ancestors, you_ancestors) you_uniques = diff(you_ancestors, santa_ancestors) # +1 for missed common item above, -1 since counting edges instead of vertices print(len(santa_uniques) + len(you_uniques))
# -*- coding: utf-8 -*- """ Created on Thu Sep 2 18:51:42 2021 @author: lemit """ #Condiciones #En un while siempre hay ciclos dependiendo la condicion c=2 d=2 if c>d: print ('Esto es lo correcto') elif c<d: print('Esto es incorrecto') elif c==d: print ('me da igual') c=2 d=5 if c>d: print ('Esto es lo correcto') else: print("Todo el resto") c=8 d=5 if c>d and d==5 :#las dos se deben cumplir para que funcione con and print ('Esto es lo correcto') if c>d or d==5 :#Solo una se debe cumplir print ('Esto es lo correcto')
# -*- coding: utf-8 -*- """ Created on Wed Nov 13 18:05:09 2019 @author: emeka """ # !/usr/bin/env python # -*- coding: utf-8 -*- """ Lesson 9 - Temperature Conversion ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In this homework, you will write a program which will convert a temperature given by the user into Fahrenheit or Celsius depending on what the user requests. - """ print(f'Welcome to my temperature converter!') # Task 1: Ask the user what temperature they would like to convert. # Hint: Save this to a variable and be careful with types. user_temp = input( 'what temperature do you want to convert? Fahrenheit or Celsius; ') # Task 2: Ask the user which temperature scale they would like their # temperature converted to? # Hint: Save the answer to a variable. conv_user_temp = input( 'which temperature scale do you want the tempearture to be converted to? ') valid_temperature_scales = ('Fahrenheit', 'F', 'Celsius', 'C') # Task 3: Using a while loop, check whether the desired temperature is in # among the `valid_temperature_scales` defined above. If it is not, then the # program should enter into the while loop execution block and prompt the # user to provide again the desired temperature scale until a valid was is # given by the user. Perhaps you might also want to print out some helpful # information to the user, so as letting them know they did not choose a # valid scale and which scales are valid. while conv_user_temp not in valid_temperature_scales: print('Sorry, I can\'t convert this') conv_user_temp = input('''Enter another temperature scale, e.g., Fahrenheit(F), Celsius(C); ''') # Task 4: Print back to the user what you plan to do with their request, i.e. # 'Okay, I will convert 45 Celsius to Fahrenheit for you' print(f'Okay, I will convert {user_temp} to {conv_user_temp} for you') # Task 5: Calculate the converted temperature. You can easily find these # questions online if you are stuck. if user_temp == 'Fahrenheit': fah = float(input('Enter the temperature degree in fahrenheit; ')) Celsius = (fah - 32) / 1.8 print(f'{fah} degree Fahrenheit is equal to {Celsius} degree Celsius') elif user_temp == 'Celsius': cel = float(input('Enter the temperature degree in celsius; ')) Fahrenheit = (cel * 1.8) + 32 print(f'{cel} degree celsius is equal to {Fahrenheit} degree Fahrenheit') # Task 6: Print the results to your user. # Task 7: Use your Celsius to Fahrenheit equation and a for loop to print # the conversions of Celsius to Fahrenheit for Celsius values -10 to 30. # Hint: Your for loop should use the `range` function. for index in range(-10, 31): Fahrenheit = (index * 1.8) + 32 print(f'{index} degree Celsius is equal to {Fahrenheit} degree Fahrenheit')
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Lesson 9 - Pair Programming ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Exercise 3 Write a Python program to get the Fibonacci series between 0 to 50. Note: The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, .... Every next number is found by adding up the two numbers before it. Expected Output : 1 1 2 3 5 8 13 21 34 Hints: - The variables `x` and `y` have been initialized for you. - Use a while loop to check the value of y - Use the block within the while loop to change the values of `x` and `y` with each iteration """ x = 0 y = 1
print(f'Welcome to my temperature converter!') users_temp = int(input('what is your prefered temperature?')) users_temp_scale = input('what temperature scale would you prefer?') valid_temperature_scales = ('Fahrenheit', 'F', 'Celsius', 'C') while users_temp_scale not in valid_temperature_scales: users_temp_scale = input('what temperature scale would you prefer?') print('Hint: you did not choose a valid scale,scale is between C and F') print(' Ok, I will convert 45 Celsius to Fahrenheit for you!') print('Your prefered temperature in Fahrenheit is 113 degrees!')
class Solution(object): def canPartition(self, nums): lookup = set([0]) for n in nums: new_lookup = set() for lookup_sum in lookup: new_lookup.add(lookup_sum + n) new_lookup.add(lookup_sum - n) lookup = new_lookup print(lookup) return 0 in lookup #res = Solution().canPartition([1,1,2,5,5]) #print(res)
""" Palindromes are strings that read the same from the left or right, for example madam or 0110. You will be given a string representation of a number and a maximum number of changes you can make. Alter the string, one digit at a time, to create the string representation of the largest number possible given the limit to the number of changes. The length of the string may not be altered, so you must consider 's left of all higher digits in your tests. For example is valid, is not. Given a string representing the starting number, and a maximum number of changes allowed, create the largest palindromic string of digits possible or the string '-1' if it is not possible to create a palindrome under the contstraints. Example Make replacements to get . Make replacement to get . Function Description Complete the highestValuePalindrome function in the editor below. highestValuePalindrome has the following parameter(s): string s: a string representation of an integer int n: the length of the integer string int k: the maximum number of changes allowed Returns string: a string representation of the highest value achievable or -1 """ # Complete the highestValuePalindrome function below. def highestValuePalindrome(s, n, k): s = list(s) mid = int((n -1) / 2) l = len(s) spots = [] vals = [] for i in range(mid + 1): if s[i] > s[l - i -1]: spots.append(l - i -1) vals.append(s[i]) elif s[i] < s[l - i -1]: spots.append(i) vals.append(s[l - i -1]) if k < len(spots): return '-1' changed = set() for i in range(len(spots)): s[spots[i]] = vals[i] changed.add(spots[i]) k = k - len(changed) #it's alread a palindrom, now it's trying to replace numbers with 9 for i in range(mid + 1): if k == 0: break #skip the ones that are 9 already if s[i] != '9': #one of them has been changed, change both side only count as 1 if i in changed or l - i - 1 in changed: s[i] = '9' s[l - i - 1] = '9' k -= 1 else: #if it's greater than 1, and both side of this spot is untouch, #change both side to 9 if k > 1: s[i] = '9' s[l - i - 1] = '9' k -= 2 else: break if k >= 1 and l % 2 == 1: s[mid] = '9' return "".join(s)
''' 316. Remove Duplicate Letters Medium 2640 193 Add to List Share Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/ Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb" Constraints: 1 <= s.length <= 104 s consists of lowercase English letters. Accepted 123,225 Submissions 310,759 ''' class Solution(object): def removeDuplicateLetters(self, s): """ :type s: str :rtype: str """ stack = [] seen = set() lookup = {c: i for i, c in enumerate(s)} for i, c in enumerate(s): print(stack) if c not in seen: while stack and c < stack[-1] and i < lookup[stack[-1]]: seen.discard(stack.pop()) seen.add(c) stack.append(c) return ''.join(stack)
''' 332. Reconstruct Itinerary Medium 2793 1293 Add to List Share You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. Example 1: Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] Output: ["JFK","MUC","LHR","SFO","SJC"] Example 2: Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order. Constraints: 1 <= tickets.length <= 300 tickets[i].length == 2 fromi.length == 3 toi.length == 3 fromi and toi consist of uppercase English letters. fromi != toi Accepted 216,659 Submissions 562,671 ''' from collections import defaultdict class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: self.graph = defaultdict(list) self.tickets = tickets self.path_used = 0 self.sol = None for t in self.tickets: self.graph[t[0]].append(t[1]) self.backtrack("JFK", ["JFK"]) return self.sol def backtrack(self, curr, curr_acc): targets = sorted(self.graph[curr]) for tar in targets: if self.path_used + 1 == len(self.tickets): self.sol = curr_acc + [tar] return self.graph[curr].remove(tar) self.path_used +=1 self.backtrack(tar, curr_acc + [tar]) self.path_used -=1 if self.sol: return self.graph[curr].append(tar)
# 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 pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ if not root: return [] self.sol = [] self.sum = sum if not root.left and not root.right: if root.val == sum: return [[root.val]] else: return [] self.backtrack(root, [], 0) return self.sol def backtrack(self, root, curr, count): if not root.left and not root.right: if count + root.val == self.sum: self.sol.append(curr + [root.val]) curr.append(root.val) count += root.val if root.left: self.backtrack(root.left, curr, count) if root.right: self.backtrack(root.right, curr, count) curr.pop() count -= root.val
""" 501. Find Mode in Binary Search Tree Easy 1893 518 Add to List Share Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it. If the tree has more than one mode, return them in any order. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the node's key. The right subtree of a node contains only nodes with keys greater than or equal to the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [1,null,2,2] Output: [2] Example 2: Input: root = [0] Output: [0] Constraints: The number of nodes in the tree is in the range [1, 104]. -105 <= Node.val <= 105 Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count). Accepted 138,797 Submissions 298,964 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findMode(self, root: Optional[TreeNode]) -> List[int]: count = 0 max_count = 0 sol = set([]) last = None def traverse(root): if not root: return nonlocal sol nonlocal last nonlocal count nonlocal max_count traverse(root.left) if last == root.val: count += 1 else: if count > max_count: sol = set([last]) max_count = count elif count == max_count: sol.add(last) count = 1 last = root.val traverse(root.right) traverse(root) if count > max_count: sol = [last] elif count == max_count: sol.add(last) return sol
""" 241. Different Ways to Add Parentheses Medium 3068 157 Add to List Share Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order. Example 1: Input: expression = "2-1-1" Output: [0,2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: Input: expression = "2*3-4*5" Output: [-34,-14,-10,-10,10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 Constraints: 1 <= expression.length <= 20 expression consists of digits and the operator '+', '-', and '*'. All the integer values in the input expression are in the range [0, 99]. Accepted 146,937 Submissions 243,642 """ from collections import defaultdict class Solution: def diffWaysToCompute(self, expression: str) -> List[int]: l = len(expression) def get_tokens(exp): ops = [] nums = [] num_start_idx = 0 for i, c in enumerate(exp): if c in ['+', '-', '*']: ops.append(c) nums.append(int(exp[num_start_idx:i])) num_start_idx = i + 1 elif i == l - 1: nums.append(int(exp[num_start_idx:i+1])) return nums, ops def calc(num1, op, num2): if op == '+': return num1 + num2 elif op == '-': return num1 - num2 elif op == '*': return num1 * num2 nums, ops = get_tokens(expression) cache = {} def helper(start, end): key = (start, end,) if key in cache: return cache[key] nlen = end - start if nlen == 1: return [nums[start]] elif nlen == 2: return [calc(nums[start], ops[start], nums[start + 1])] sol = [] num1 = nums[start] for i in range(start + 1, end): #recursion on both the left side and the right side for ln in helper(start, i): for rn in helper(i, end): sol.append( calc(ln, ops[i-1], rn) ) num1 = calc(num1, ops[i - 1], nums[i]) cache[key] = sol return sol return helper(0, len(nums))
import datetime dt = datetime.datetime.today() days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: target = datetime.date(year = year, month = month, day = day) days_diff = (target - dt.date()).days sign = 1 if days_diff >= 0: idx = (dt.weekday() + days_diff) % 7 return days[sign * idx] else: days_back = dt.weekday() + days_diff if days_back >= 0: return days[days_back] else: return days[-1 * (abs(days_back) % 7)]
''' 582. Kill Process Medium 683 14 Add to List Share You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process's parent process. Each process has only one parent process but may have multiple children processes. Only one process has ppid[i] = 0, which means this process has no parent process (the root of the tree). When a process is killed, all of its children processes will also be killed. Given an integer kill representing the ID of a process you want to kill, return a list of the IDs of the processes that will be killed. You may return the answer in any order. Example 1: Input: pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5 Output: [5,10] Explanation: The processes colored in red are the processes that should be killed. Example 2: Input: pid = [1], ppid = [0], kill = 1 Output: [1] Constraints: n == pid.length n == ppid.length 1 <= n <= 5 * 104 1 <= pid[i] <= 5 * 104 0 <= ppid[i] <= 5 * 104 Only one process has no parent. All the values of pid are unique. kill is guaranteed to be in pid. Accepted 49,932 Submissions 77,682 ''' from collections import defaultdict class Solution(object): def killProcess(self, pid, ppid, kill): """ :type pid: List[int] :type ppid: List[int] :type kill: int :rtype: List[int] """ children = defaultdict(list) killed = set() for ppi in range(len(ppid)): children[ppid[ppi]].append(pid[ppi]) killed.add(kill) curr = children[kill] while curr: _curr = [] for c in curr: killed.add(c) _curr.extend(children[c]) curr = _curr return killed
""" 95. Unique Binary Search Trees II Medium 4296 282 Add to List Share Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order. Example 1: Input: n = 3 Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]] Example 2: Input: n = 1 Output: [[1]] Constraints: 1 <= n <= 8 Accepted 286,220 Submissions 594,379 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def generateTrees(self, n: int) -> List[Optional[TreeNode]]: if n == 0: return [] nums = range(n) def generate(low, high): if low == high: return [None] res = [] for i in range(low, high): left_trees = generate(low, i) right_trees = generate(i + 1, high) for l in left_trees: for r in right_trees: mid = TreeNode(nums[i] + 1) mid.left = l mid.right = r res.append(mid) return res return generate(0, n)
""" 89. Gray Code Medium 1286 2160 Add to List Share An n-bit gray code sequence is a sequence of 2n integers where: Every integer is in the inclusive range [0, 2n - 1], The first integer is 0, An integer appears no more than once in the sequence, The binary representation of every pair of adjacent integers differs by exactly one bit, and The binary representation of the first and last integers differs by exactly one bit. Given an integer n, return any valid n-bit gray code sequence. Example 1: Input: n = 2 Output: [0,1,3,2] Explanation: The binary representation of [0,1,3,2] is [00,01,11,10]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit Example 2: Input: n = 1 Output: [0,1] Constraints: 1 <= n <= 16 Accepted 222,809 Submissions 408,775 """ class Solution: def grayCode(self, n: int) -> List[int]: if n == 0: return [0] rest = self.grayCode(n - 1) # everytime it builds one set, reverse the front part return [ r << 1 for r in rest] + [ (r << 1) + 1 for r in rest[::-1]]
""" 96. Unique Binary Search Trees Medium 6472 255 Add to List Share Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n. Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 19 """ """ #recursion with memorization class Solution: def numTrees(self, n: int) -> int: mem = {0:1, 1:1} def recursion(num): if num in mem: return mem[num] if num == 1 or num == 0: return 1 res = 0 for i in range(num): res += recursion(i) * recursion(num - i - 1) mem[num] = res return res return recursion(n) """ #dp derived from the above class Solution: def numTrees(self, n: int) -> int: dp = [1,1] for i in range(2, n + 1): dp.append(sum([ dp[j] * dp[i - j - 1] for j in range(i)])) return dp[-1]
''' 162. Find Peak Element Medium 2973 2725 Add to List Share A peak element is an element that is strictly greater than its neighbors. Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. You must write an algorithm that runs in O(log n) time. Example 1: Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2. Example 2: Input: nums = [1,2,1,3,5,6,4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. Constraints: 1 <= nums.length <= 1000 -231 <= nums[i] <= 231 - 1 nums[i] != nums[i + 1] for all valid i. Accepted 503,118 Submissions 1,137,238 ''' class Solution: def findPeakElement(self, nums: List[int]) -> int: length = len(nums) if length == 1: return 0 mem_left = [float('-inf')] * length mem_right = [float('-inf')] * length for i in range(1, length): mem_left[i] = max(nums[i-1], mem_left[i-1]) mem_right[length-i-1] = max(nums[length-i], mem_right[length-i]) for i in range(length): if nums[i] >= mem_left[i] and nums[i] >= mem_right[i]: return i
def permute(ls): l = len(ls) if l == 0: return [] if l == 1: return [ls] sol = [] for i in range(l): sub = permute(ls[:i] + ls[i+1:]) for x in sub: sol.append(x + [ls[i]]) return sol print(permute([1,2,3]))
from bisect import bisect class Solution: def heightChecker(self, heights: List[int]) -> int: lst = [] count = 0 for x in heights: i = bisect(lst, x) lst.insert(i, x) for i, x in enumerate(heights): if lst[i] != x: count += 1 return count
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def leafSimilar(self, root1: 'TreeNode', root2: 'TreeNode') -> bool: leaves1 = [] leaves2 = [] self.getLeaves(root1, leaves1) self.getLeaves(root2, leaves2) l1 = len(leaves1) l2 = len(leaves2) if l1 != l2: return False return all([ leaves1[i] == leaves2[i] for i in range(l1)]) def getLeaves(self, root, leaves): if not root.left and not root.right: leaves.append(root.val) if root.left: self.getLeaves(root.left, leaves) if root.right: self.getLeaves(root.right, leaves)
class StockSpanner(object): def __init__(self): self.stack = [] self.i = 0 def next(self, price): """ :type price: int :rtype: int """ if not self.stack: self.stack.append( (price,0) ) self.i += 1 return 1 if price < self.stack[-1][0]: self.stack.append( (price,self.i) ) self.i += 1 return 1 else: while self.stack and self.stack[-1][0] <= price: self.stack.pop() if self.stack: distance = self.i - self.stack[-1][1] self.stack.append( (price,self.i) ) self.i += 1 return distance else: self.stack.append( (price,self.i) ) self.i += 1 return self.i # Your StockSpanner object will be instantiated and called as such: # obj = StockSpanner() # param_1 = obj.next(price)
from Board import Board board = Board() # board.saveLoad = '' board.toggleGameStatus(1) # board.printPiles() # board.saveLoad = 'l' while board.playing: # if board.saveLoad == 's': # board.saveGame() # break if board.winning_player != 0: if board.winning_player == 3: print("The game ended in draw!") break else: print("Congratulation Player ", board.winning_player, ", YOU WON!") break # if board.saveLoad == 'l': # board.loadGame() # board.printPiles() print("Its Player ", board.player, " turn !") board.clicked_index = int(input("Please enter the starting index\n")) board.prepMove() board.printPiles() # board.saveLoad = input("Do you wish to save?\n")
""" Omat Gonzalez web scraper python project """ import urllib.request from bs4 import BeautifulSoup class Scraper: """ Object Scraper takes in a website to scrape from as a parameter for example : "https://news.google.com/" """ def __init__(self,site): self.site=site def scrape(self): #urlopen() makes request to a website and returns response onjext that has its HTML stored in it r = urllib.request.urlopen(self.site) #read() returns the HTML from the reponse object r. html = r.read() parser = "html.parser" #BeautifulSoup object does the heavy lifting and parse the HTML passed sp = BeautifulSoup(html, parser) """ This for loop will call the method find_all on BeautifulSoup object. Passing in "a" as a parameter which will tell the function to look fo <a></a> tags and the method will return all of the URLS the webstie links to in the HTML you downloaded -find_all method: returns iterable containing tag objects found. we just want the Href in the tag not the other elements """ for tag in sp.find_all("a"): url=tag.get("href") if url is None: continue if "html" in url: print ("\n" + url) news = "https://news.google.com/" Scraper(news).scrape()
class StoreItem: TAX = 0.13 def __init__(self, name, price): self.name = name self.price = price self.after_tax_price = 0 self.set_after_tax_price() def set_after_tax_price(self): self.after_tax_price = round(self.price * (1 + self.TAX), 2) def __sub__(self, discount): return StoreItem(self.name, self.price - discount) def __mul__(self, value): return StoreItem(self.name, self.price * value) bread = StoreItem("Bread", 7) # discounted_bread = bread - 2 discounted_bread = bread * 0.8 # apply 20% discount print(discounted_bread.after_tax_price)
class Inventory: def __init__(self): self.slots = [] def add(self, item): self.slots.append(item) # to use len on an object, the object must # have a method named __len__ def __len__(self): return len(self.slots) def __contains__(self, item): return item in self.slots def __iter__(self): # generator, yield data as # we work through the iter yield from self.slots
def rev(name): ptr = len(name) - 1 letters = [] while ptr >= 0: letters.append(name[ptr]) ptr -= 1 return "".join(letters) def rev2(name): res = '' for c in name: res = c + res return res def rev3(name): return name[::-1] print(rev('miles')) print(rev2('charles')) print(rev3('pat'))
""" 1. create a fruit_basket list 2. prompt user to enter in fruit or 'q' to quit 3. check if fruit was entered, if so add fruit to fruit_basket list and then ask again for another fruit. 4. if 'q' was entered end program and display fruits in alphabetically order provided there is at least 1 fruit. """ def main(): fruit_basket = [] while True: fruit = input("Please enter a fruit or 'q' to quit: ") if fruit.lower() == 'q': break fruit_basket.append(fruit) if len(fruit_basket) > 0: for f in sorted(fruit_basket): print(f"{f}", end=' ') if __name__ == "__main__": main()
# Credit goes to Websten from forums # # Program defensively: # # What do you do if your input is invalid? For example what should # happen when date 1 is not before date 2? # # Add an assertion to the code for daysBetweenDates to give # an assertion failure when the inputs are invalid. This should # occur when the first date is not before the second date. # def isLeapYear(year): if year % 400 == 0: return True elif year % 100 == 0: return False elif year % 4 == 0: return True else: return False def daysInMonth(year, month): if month == 2: if isLeapYear(year): return 29 else: return 28 elif month in (1, 3, 5, 7, 8, 10, 12): return 31 else: return 30 def nextDay(year, month, day): """Simple version: assume every month has 30 days""" if day < daysInMonth(year, month): return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1 def dateIsBefore(year1, month1, day1, year2, month2, day2): """Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False.""" if year1 < year2: return True if year1 == year2: if month1 < month2: return True if month1 == month2: return day1 < day2 return False def daysBetweenDates(year1, month1, day1, year2, month2, day2): """Returns the number of days between year1/month1/day1 and year2/month2/day2. Assumes inputs are valid dates in Gregorian calendar.""" # program defensively! Add an assertion if the input is not valid! assert not dateIsBefore(year2, month2, day2, year1, month1, day1) days = 0 while dateIsBefore(year1, month1, day1, year2, month2, day2): year1, month1, day1 = nextDay(year1, month1, day1) days += 1 return days def my_tests(): # tests with 30 days month print("Initiating tests....") assert daysBetweenDates(2013, 1, 1, 2013, 1, 1) == 0 assert daysBetweenDates(2013, 1, 1, 2013, 1, 2) == 1 assert nextDay(2013, 1, 1) == (2013, 1, 2) assert nextDay(2013, 4, 30) == (2013, 5, 1) assert nextDay(2012, 12, 31) == (2013, 1, 1) assert nextDay(2013, 2, 28) == (2013, 3, 1) assert nextDay(2013, 9, 30) == (2013, 10, 1) assert nextDay(2012, 2, 28) == (2012, 2, 29) assert daysBetweenDates(2013, 1, 1, 2014, 1, 1) == 365 assert daysBetweenDates(2012, 1, 1, 2013, 1, 1) == 366 print("All tests have completed!") def tests(): test_cases = [((2012, 1, 1, 2012, 2, 28), 58), ((2012, 1, 1, 2012, 3, 1), 60), ((2011, 6, 30, 2012, 6, 30), 366), ((2011, 1, 1, 2012, 8, 8), 585), ((1900, 1, 1, 1999, 12, 31), 36523)] for (args, answer) in test_cases: result = daysBetweenDates(*args) if result != answer: print(f"Test with data: {args} failed") else: print("Test case passed!") tests() my_tests()
"""this is our little calculator to work with functions.""" def add(num1, num2): """add num1 with num2 and return the results.""" return num1 + num2 def subtract(num1, num2): """subtract num1 with num2 and return the results.""" return num1 - num2 def multiply(num1, num2): """multiply num1 with num2 and return the results.""" return num1 * num2 def divide(num1, num2): """divide num1 with num2 and return the resluts.""" return num1 / num2 if __name__ == "__main__": print("Let's power on our calculator.") print("\nInitializing power sequence...") print() num1 = int(input("Please enter the first number: ")) num2 = int(input("Please enter the second number: ")) print("\nInitializing calculation sequence...") print() print(f"The sum of your two numbers is: {add(num1, num2)}") print(f"The difference of your two numbers is: {subtract(num1, num2)}") print(f"The quotient of your two numbers is: {divide(num1, num2)}") print(f"The product of your two numbers is: {multiply(num1, num2)}")
#!/usr/bin/env python3 """ Copy the messages.py. Write a function called send_messages() that prints each text message and moves each message to a new list called sent_messages as it's printed. After calling the function, print both of your lists to make sure the messages were moved correctly. """ def main(): message_list = ['a star above', 'wonder twins activate', 'go go gadget go', 'i have the power'] # show_messages(message_list) send_messages(message_list) print(f"Unsent Message List: {message_list}") def show_messages(messages): for m in messages: print(f"{m}") def send_messages(messages): sent_messages = [] while messages: current_message = messages.pop(0) print(f"{current_message}") # sent_messages.append(current_message) sent_messages.append(current_message) print(f"Sent Messages List: {sent_messages}") if __name__ == '__main__': main()
class Student: all_students = [] def __init__(self, name, grade): self.name = name self._grade = grade Student.all_students.append(self) @property def grade(self): return self._grade @grade.setter def grade(self, grade): if grade not in range(0, 101): raise ValueError("New grade not in the accepted range of [0-100].") self._grade = grade @classmethod def get_average_grade(cls): return Student.calculate_average_grade(cls.all_students) @classmethod def get_best_student(cls): number_of_students = len(cls.all_students) if number_of_students == 0: return None elif number_of_students == 1: return cls.all_students[0] else: best_student = cls.all_students[0] for student in cls.all_students[1:]: if student._grade > best_student._grade: best_student = student return best_student @staticmethod def calculate_average_grade(students): students_length = len(students) if students_length == 0: return -1 total_students_grades = 0 for student in students: total_students_grades += student._grade return total_students_grades / students_length
def main(): """ variable - container that stores a value. container is a section in the computers memory. ex: color = "blue" Rules to Naming Variables: * cannot start with a number - ex: 5color = "blue" * cannot contain any special characters other than underscores (_) - ex: $^color = "blue" * cannot contain any spaces - ex: favorite color = "blue" """ x = 5 y = "AlgoExpert" x = y z = 5 print(z) print(y) print(x) if __name__ == "__main__": main()
class Group: def __init__(self, name, members=[]): self.name = name self.members = members def add(self, name): self.members.append(name) def delete(self, name): if name in self.members: self.members.remove(name) else: raise Exception("Member not in group.") def get_members(self): return sorted(self.members) def merge(self, group): return Group("New_Group", self.members + group.members) def main(): g1 = Group("A-Team", ["Tim", "Clement"]) g2 = Group("B-Team", ["Antoine"]) g3 = g1.merge(g2) print(g3.get_members()) if __name__ == "__main__": main()
#------------------------------------------------------------------------------- # Name: parse_DB_line # Purpose: The purpose is stated below. The robustness is decreased with # this module due to the strictness of the arg line's structure. # # Author: jkougl # # Created: 29/08/2014 # Copyright: (c) jkougl 2014 # Licence: <your licence> #------------------------------------------------------------------------------- # The purpose of the parse_DB_line is to take in a line from a text file as # well as the number of relevant attributes in that line and parse the line # into a tsil of values which can be utilized in Python. # The structure of the line to be parsed is: 'DATA1 = [attr1, attr2, attr3]' # Returned parsed lines should all still be in string type. def parse_DB_line(line, num_of_values): # Find indexes, and raise ValueError if required markers are not found. try: starting_index = line.index('[') current_starting_index = starting_index + 1 ending_index = line.index(']') current_comma_index = line.index(',') except ValueError: raise ValueError('Database line incorrectly formatted: ' + line) tsil_of_parsed_lines = [] # Parse line and update indexes appropriately. If ValueError is raised, # attributes may be missing. for x in range(num_of_values): try: tsil_of_parsed_lines.append(line[current_starting_index:\ current_comma_index]) current_starting_index = current_comma_index + 2 current_comma_index += line[current_starting_index:\ ending_index].index(',') + 2 except ValueError: current_comma_index = ending_index return tsil_of_parsed_lines
''' Exercice IV : Un cycliste souhaite s'entrainer pour une compétition. Il prépare un programme d'entrainement de 3 semaines. Le premier jour, il parcourt 30km puis il décide d'augmenter la distance parcourue de 10km chaque jour. 1) Ecrire un programme python qui calcule et affiche le nombre de kilometres parcourus le 10eme jour d'entrainement. De même pour le dernier jour d'entrainement. 2) Modifier le programme pour qu'il calcule le nombre total de kilometres parcourus durant ce programme d'entrainement. ''' # Reponse1 # Nombre de Km parcourus le 10 eme jour # Distance 1er jour: 30km dist = 30 numJour = int(input("Entrez un numero de jour: ")) for i in range(1,numJour): dist = dist +10 print("Distance parcourue au ", numJour , " jour", dist) # Reponse2 # Distance 1er jour: 30km dist = 30 distanceTotale = 30 for i in range(1,21): dist = dist +10 distanceTotale = distanceTotale + dist print("Distance totale parcourue ", distanceTotale)
""" Saisie N nombre qui affiche si ce nombre est pair ou impair. Le programme s'arrete des qu'on saisit un nombre négatif """ i = True while i == True: """ print("Saisi un nombre entier") nb = input() nb = int(nb) """ # OU nb = int(input('Saisie un nombre entier :')) # test de coherence if nb < 0: print("Bye!!") i = False else: # Test de la parite if nb %2== 0: print("pair"+ '\n') else: print("impaire"+1 '\n')
''' Programme python qui saisit N nombres et qui affiche si ce nombre est pair ou impair. Le programme s'arrete des qu'on saisit un nombre negatif ''' # Booleen encore = True while encore == True: ''' print("Saisir un nombre entier ") nb = input() nb = int(nb) ''' # OU nb = int(input("Saisir un nombre entier ")) # Test de coherence if nb < 0: print("Bye!!") encore = False else: # Test de la parite if nb %2== 0: print("Ce nombre est pair") else: print("Ce nombre est impair") print("Fin Programme!!!")
# ------------------------------- # Listes necessaires au programme # ------------------------------- # Liste des employes hommes hommes = list() # Liste des employes femmes femmes = list() # Liste des employes dont le salaire est # compris entre 1000 et 1500 euros salaireInf = [] # Liste des employes dont le salaire est # superieur a 1500 euros salaireSup = [] #-------------------------------------- # Saisie des informations des 5 employes for i in range(1, 6): nom = input("Saisir un nom: ") prenom = input("Saisir un prenom: ") sexe = input("Saisir le genre (M/F): ") salaire = float(input("saisir un salaire: ")) # Test du genre de l'employe if sexe == "M": hommes.append(nom) hommes.append(prenom) else: femmes.append(nom) femmes.append(prenom) # Test du salaire if salaire >= 1000 and salaire <= 1500: salaireInf.append(nom) salaireInf.append(prenom) elif salaire > 1500: salaireSup.append(nom) salaireSup.append(prenom) # Afficher le cotenu des listes print("Liste des hommes:",hommes) print("Liste des femmes:",femmes) print("Liste des salaires inf:",salaireInf) print("Liste des salaires Sup:",salaireSup) print(" Merci de votre cooperation!!!!")
from statistics import mean numbers = [] number = input("Please enter a number (0 to quit)") list_lenth = len(numbers) while number != "0" : print(number) numbers.append(float(number)) number = input("Please enter a number") print(numbers) average = sum(numbers)/len(numbers) print("The average of this list is {}".format(average))
import math userNumber = input("Enter a float number") floatingNumber = float(userNumber) wholeNumber = round(abs(floatingNumber)) print(str(floatingNumber) + " rounded is "+ str(wholeNumber) + " ")
months = ("January", "Feburary", "March", "April", "June", "July", "August", "Sept", "Äug", "Nov", "Dec") for month in months [4:7]: print(month)
def multiplicar_por_dos(n): return n * 2 def sumar_dos(n): return n + 2 def aplicar_operacion(f, numeros): resultados = [] for numero in numeros: resultado = f(numero) resultados.append(resultado) print(resultado) # Funciones en estructuras de datos # Las funciones también se pueden incluir en diversas estructuras que las permiten almacenar. # Por ejemplo, una lista puede guardar diversas funciones a aplicar o un diccionario las puede almacenar como valores. def aplicar_operaciones(num): operaciones = [abs, float] resultado = [] for operacion in operaciones: resultado.append(operacion(num)) print('el resultado es: ',resultado) return resultado def run(): print('Operaciones con funciones como objeto') nums = [2,4,6] aplicar_operacion(multiplicar_por_dos,nums) # Funciones lambda en una expresión es utilizando el keyword lambda. lambda tiene la siguiente sintaxis: # lambda <vars>: <expresion>. sumar = lambda x, y: x + y print(sumar(5,12)) print(aplicar_operaciones(-17))
import copy class Board(): def __init__(self, player1, player2): self.initial_state = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] self.player1 = player1 self.player2 = player2 self.current_player = self.player1 self.state = copy.deepcopy(self.initial_state) def start(self): self.current_player = self.player1 def update(self, y, x): # check valid if self.state[y][x] != 0: return False self.state[y][x] = self.current_player.marker self.current_player = self.player1 if self.current_player is self.player2 else self.player2 return True def is_game_over(self): for fila in self.state: if fila[0] != 0 and fila[0] == fila[1] and fila[1] == fila[2]: return True for c in range(3): if self.state[0][c] != 0 and self.state[0][c] == self.state[1][c] and self.state[1][c] == self.state[2][c]: return True if self.state[0][0] != 0 and self.state[0][0] == self.state[1][1] and self.state[1][1] == self.state[2][2]: return True if self.state[0][2] != 0 and self.state[0][2] == self.state[1][1] and self.state[1][1] == self.state[2][0]: return True return False def reset(self): self.state = copy.deepcopy(self.initial_state)
input() A = input() A1 = A.split() a = int(A1[0]) for i in A1: x = int(i) if x >= a: a = x bul = True else: bul = False break if bul: print("Yes") else: print("No")
import random from math import sqrt, acos def normalize(vector): v_sum = vector.x + vector.y return Vector2D(vector.x / v_sum, vector.y / v_sum) class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector2D(self.x - other.x, self.y - other.y) def __str__(self): return f'Vector2D({self.x}, {self.y})' def __repr__(self): return f'Vector2D({self.x}, {self.y})' def __mul__(self, other): types = (int, float) if isinstance(self, types): return Vector2D(self * other.x, self * other.y) elif isinstance(other, types): return Vector2D(self.x * other, self.y * other) else: return Vector2D(self.x * other.x, self.y * other.y) def __copy__(self): return Vector2D(self.x, self.y) def add(self, other): return Vector2D(self.x + other.x, self.y + other.y) def sub(self, other): return Vector2D(self.x - other.x, self.y - other.y) def distance(self, other): return sqrt((self.x - other.x)**2 + (self.y - other.y)**2) def length(self): return sqrt((self.x)**2 + (self.y)**2) def get_norm_direction_to(self, vector): dist = self.distance(vector) return Vector2D((vector.x - self.x) / dist, (vector.y - self.y) / dist) def get_direction_to(self, vector): return Vector2D((vector.x - self.x), (vector.y - self.y)) @classmethod def get_dist_to_line(cls, v1, v2, circle_v): if v1.x != v2.x and v1.y != v2.y: numerator = abs((v2.y - v1.y) * circle_v.x - (v2.x - v1.x) * circle_v.y + v2.x * v1.y - v2.y * v1.x) denumenator = v1.distance(v2) return numerator / denumenator else: return float('inf') @classmethod def create_random_vector(cls): x = random.random() return Vector2D(x, 1 - x)
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> print("Rayon") Rayon >>> arr1=[1,2,3,4,5,6,7] >>> i=0 >>> while(i<7): print(arr1[i]) i=i+1 1 2 3 4 5 6 7 >>> while(i<7): arr1[i]=arr1[i]**2 print(arr1[i]) i=i+1 >>> print(arr1) [1, 2, 3, 4, 5, 6, 7] >>> i=0 >>> while(i<7): arr1[i]=arr1[i]**2 print(arr1[i]) i=i+1 1 4 9 16 25 36 49 >>> print(arr1) [1, 4, 9, 16, 25, 36, 49] >>> i=1 >>> while i<7: arr1[i-1]=arr1[i]+(arr1[i-1]**2) print(arr1[i-1]) i=i+1 5 25 97 281 661 1345 >>>
text = "paralelepípedo" for letra in text: if letra == 'a': print(letra*2) else: print("Não é a letra 'a'") var = input() print("O número é {}".format(var)) meses = {1: 'Janeiro', 2: 'Fevereiro', 3: 'Março', 4: 'Abril', 5: 'Maio', 6: 'Junho', 7: 'Julho', 8: 'Agosto', 9: 'Setembro', 10: 'Outubro', 11: 'Novembro', 12: 'Dezembro', } data = input('Data: ').split('/') output = [data[0], meses[int(data[1])], data[2]] print('Data de Nascimento: {} de {} de {}'.format(*output))
# https://www.geeksforgeeks.org/merge-sort/ def sort(arr, leftIndex, rightIndex): if (rightIndex > leftIndex): midIndex = leftIndex + (rightIndex - leftIndex) / 2 sort(arr, leftIndex, midIndex) sort(arr, midIndex + 1, rightIndex) def merge(arr, leftIndex, rightIndex, midIndex): length1 = midIndex - leftIndex + 1 # length of left subarray length2 = rightIndex - midIndex # length of right subarray # temp arrays leftArray = [i for i in arr if arr[leftIndex:midIndex]] rightArray = [i for i in arr if arr[midIndex:rightIndex]]
# -*- coding: utf-8 -*- import math class Neuron(object): def __init__(self, w, a, c): self.w, self.a, self.c = w, a, c def __call__(self, point): distance = sum(map(lambda x, y: math.pow(x - y, 2.0), point, self.c)) return self.w * math.exp(-1.0 * distance / math.pow(self.a, 2.0)) def laplace(self, point): return sum(map(lambda x, y: -2.0 * self(point) / math.pow(self.a, 2.0) + 4.0 * self(point) * math.pow(x - y, 2.0) / math.pow(self.a, 4.0), point, self.c)) class NeuralNetwork(object): def __init__(self, neurons): self.neurons = neurons def __call__(self, point): return sum(map(lambda neuron: neuron(point), self.neurons)) def laplace(self, point): return sum(map(lambda neuron: neuron.laplace(point), self.neurons))
# !usr/bin/env python3 # -*- coding:utf-8 _*- # author: Alfa # file: PythonTraining_string.py # time: 2018/04/11 23:06 """ 练习字符串的各种方法 """ # join 拼接方法 a = '' a1 = '---' b = '3456' c = 'abcd' d = 'ttee3344' e = 'a is A b is {name}' f = 'a is A b is {name} c is {age}' print(a.join([b, c])) # 3456abcd print(a1.join([b, c])) # 3456---abcd print(a1.join([b, c, d])) # 3456---abcd---ttee3344 # count() 返回字符串中相同的字符个数 print(d.count('t')) # 2 # capitalize() 把字符串首字母大写 print(d.capitalize()) # Ttee3344 # center() 一共打印多少个字符,除了居中显示字符串内容后,其他用后面的字符串内容补充 print(d.center(30, '*')) # ***********ttee3344*********** # endswith() # 以指定字符串结尾,返回true 否则返回false print(d.endswith('4')) # True print(d.endswith('44')) print(d.endswith('5')) # False # find() 查找到第一个指定的字符,并返回索引值 print(d.find('3')) # 4 # format() 格式化输出的另一种方法 print(e.format(name='Y')) # a is A b is Y print(f.format(name='Y', age=99)) # a is A b is Y c is 99 print(e.format_map({'name': "Q"})) # a is A b is Q print(f.format_map({'name': "Q", 'age': 88})) # a is A b is Q c is 88 # 重要的字符串方法 print(d.count('a')) # 返回相同的字符串的个数 print(d.center(10, '#')) # 居中显示字符串,其余用#号补足 print(d.startswith('a')) # 判断以某个内容开头 print(d.find('a')) # 查找到第一个指定字符,返回索引值 print(f.format(name='Y', age=99)) # 格式化输出的另一种方法 print(d.lower()) # 把字符串内容都变成小写 print(d.upper()) # 把字符串内容都变成大写 print(' tt,aa dd '.strip()) # 去掉收尾的空格‘ ’,换行符\n,制表符\t print(' tt,a,a d,d '.replace(',', 'T', 1)) # 按照‘,’ 去替换成T,并且只替换1次 print(' tt,aba dad '.split('a')) # 按照a,分割字符串内容,有a就分割 print(' tt,aba dad '.split('a', 2)) # 按照a,分割字符串内容,分割按照后面的数字控制
# a121_catch_a_turtle.py #-----import statements----- import turtle as trtl import random #-----game configuration---- turtleshape = "turtle" turtlesize = 3 turtlecolor = "blue" counter_interval = 1000 #1000 represents 1 second timer_up = False timer = 10 score = 0 #-----initialize turtle----- bob = trtl.Turtle(shape=turtleshape) bob.color(turtlecolor) bob.shapesize(turtlesize) bob.speed(50) score_writer = trtl.Turtle() score_writer.penup() score_writer.goto(-370,270) score_writer.ht() font_setup = ("Arial",30,"bold") score_writer.write(score,font=font_setup) counter = trtl.Turtle() counter.penup() counter.ht() counter.goto(300,275) #-----game functions-------- def turtle_clicked(x,y): print ("bob got clicked") change_position() update_score() def change_position(): bob.penup() bob.ht() if not timer_up: bobx = random.randint(-400,400) boby = random.randint(-300,300) bob.goto(bobx,boby) bob.st() def update_score(): global score score += 1 print(score) score_writer.clear() score_writer.write(score,font=font_setup) def countdown(): global timer, timer_up counter.clear() if timer <= 0: counter.write("Time's Up", font=font_setup) timer_up = True else: counter.write("Timer: " + str(timer), font=font_setup) timer -= 1 counter.getscreen().ontimer(countdown, counter_interval) #-----events---------------- wn = trtl.Screen() wn.bgcolor("red") bob.onclick(turtle_clicked) wn.ontimer(countdown, counter_interval) wn.mainloop()
from random import randint def sortColor(list): head = 0 tail = len(list)-1 while head < tail: if list[head] is not 0: while list[tail] is not 0: tail-=1 print(head, tail) print("switch") if head>tail: break list[head], list[tail] = list[tail], list[head] print(list) # tail-=1 head +=1 head = 0 tail = len(list)-1 while list[head] is 0: head +=1 while head < tail: if list[head] is not 1: while list[tail] is not 1: tail-=1 print(head, tail) print("switch") if head>tail: break list[head], list[tail] = list[tail], list[head] print(list) # tail-=1 head +=1 print(list) if __name__=="__main__": list = [None for i in range(10)] for i in range(10): j = randint(0,100) if j%3 ==0 : list[i] = 1 elif j%2 ==0: list[i] = 0 else: list[i] = 2 # list = [0,1,2,1,1,2,0,1,2,1] print(list) sortColor(list) # print(list)
class Node: def __init__(self, d=None, n=None): self.data = d self.next = n def __str__(self): return "(" + str(self.data) + ")" class CircularlinkedList: def __init__(self, r=None): self.head = r self.size = 0 def add(self, d): if self.size == 0: self.head = Node(d) self.head.next = self.head else: temp = self.head.next new_node = Node(d, self.head.next) while temp.next != self.head: temp = temp.next temp.next = new_node temp.next.next = self.head self.size += 1 # print("head :", str(self.head.data)) def remove(self, d): node = self.head prev = None while True: if node.data == d: if prev is not None: prev.next = node.next else: while node.next != self.head: node = node.next node.next = self.head.next self.head = self.head.next self.size -= 1 return True elif node.next == self.head: return False prev = node node = node.next def print_list(self): if self.head is None: return node = self.head print(node, end="->") while node.next != self.head: node = node.next if node.next == self.head: print(node) else: print(node, end="->") def candle(n, k): L = buildList(n) # print(" list made :", end="") # L.print_list() return runSimulation(L, n, k) def buildList(n): list = CircularlinkedList() for i in range(1, n + 1): list.add(i) return list def runSimulation(L, n, k): p = L.head while p != p.next: L.print_list() for i in range(k - 1): # print("i: ", str(i)) p = p.next # print("p is:", str(p.data)) # print("removing: ", str(p.next.data)) L.remove(p.next.data) # print("p is now:", str(p.data)) p = p.next # print("p is when entering the loop:", str(p.data)) return p.data if __name__ == "__main__": print(candle(7, 3), "번 촛불")
# input basics a = input("??") print(a) # print print("Hello" "I" "am") print("Hello" + "I" + "am") # , == space print("Hello" , "I" , "am") for i in range(0, 10): print(i, end = ' ')
money = True if money: print("I have money") else: print("I don't have money") money = 2000 if money <=1000: print("cannot buy anything") elif money <=2000: print("can buy one drink") else: print("you are rich") # and or not card = True if money >= 2000 and card: print("okee") else: print("nope") # lists and in l = [1,2,3,4,5] if 1 in l: print("one") else: print("no") #strings, tuples also if 'j' in 'jiyoon': print("jiyooooon") else: print("oo") #pass if True: pass else: print("No")
from random import randint def partition_mid(arr, middle): quickSort(arr, 0, len(arr)-1) print("Sorted", arr) key = find(arr, middle) print(key) return arr[:key], arr[key:key+count(arr, middle)+1], arr[key+count(arr, middle)+1:] def partition(arr, low, high): # print("low:", str(low), "high:", str(high)) i = (low - 1) # index of smaller element pivot = arr[high] # pivot for j in range(low, high): # If current element is smaller than or # equal to pivot if arr[j] <= pivot: # increment index of smaller element i = i + 1 arr[i], arr[j] = arr[j], arr[i] # print(arr) arr[i + 1], arr[high] = arr[high], arr[i + 1] # print(arr, "i+1 is", str(i+1)) return (i + 1) def quickSort(arr, low, high): if len(arr) == 1: return arr if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr, low, high) # Separately sort elements before # partition and after partition quickSort(arr, low, pi - 1) quickSort(arr, pi + 1, high) def find(arr, key): for i in range(len(arr)): if arr[i] == key: return i return -1 def count(arr, key): c=0 for i in arr: if i == key: c+=1 return c def findmatch(B, R): if len(B) ==0: return () if len(B)==1: return (B[0], R[0]) b = B[0] print("key is :", str(b)) Rlt, Req, Rgt = partition_mid(B, b) print(Rlt, Req, Rgt) r = Req[1] if __name__=="__main__": b = [randint(1,100) for i in range(4)] r = [randint(1,100) for i in range(4)] print("b : ", b) print("r: ", r) findmatch(b,r)
# !usr/bin/python # usage: results announcement print "Enter user name r qualified or not:::" name=raw_input() list1=['kalyan','supraja','mahindra','anil','siva','ajay','haritha','keerthi','suhashini','subhashini','nariyan','manoj','santhosh','kumar','niveda','thomos','rasii'] if name in list1 : print 'Qualified in Exams :::' print "congratssss---->{}".format(name) else : print "Better luck next Time -->{}".format(name)
#usr/bin/python a=int(raw_input("please enter the n value we can show uuu 1--->N values:::")) for i in range(a): if i%2==0 : print "even",i else : print "odd",i
#!/usr/bin/env python import pandas as pd # We only need these attributes to contribute attributes = [ "Endurance", "Strength", "Power", "Speed", "Agility", "Flexibility", "Nerve", "Durability", "Hand-Eye Coordination", "Analytical Aptitude" ] # Handles inputting for valid and invalid values. def validInput(attr): inNum = 0 while True: try: inNum = float(input("Enter a value for " + attr + ": ")) if 0 <= inNum and inNum <= 10: break except ValueError: print("Invalid entry. Please try again.") return inNum def main(): df = pd.read_excel("Toughest Sport by Skill.xlsx") attr_table = df[attributes] # Enter all relevant attributes inputs = {attribute:0.0 for attribute in attributes} for attribute in attributes: inputs[attribute] = validInput(attribute) user = pd.DataFrame(inputs, index=[0], columns = attributes) # Now perform the calculations to recommend a sport sportRes = {"Sport":df["Sport"].values, "MSE":[]} for i in range(len(df)): tmp = attr_table.iloc[i].subtract(user.iloc[0]) sportRes["MSE"].append((tmp ** 2).sum()) sportMetrics = pd.DataFrame(sportRes, columns=["Sport", "MSE"]) inx = sportMetrics["MSE"].idxmin() print("We recommend {} as the ideal sport for you!".format(sportMetrics["Sport"][inx])) if __name__ == "__main__": main()
# -*- encoding: utf-8 -*- # 2018-04-22 from __future__ import print_function import tensorflow as tf import numpy as np # Print 10 random numbers. for step in range(10): # https://www.tensorflow.org/api_docs/python/tf/random_uniform # https://crypto.stackexchange.com/questions/20839/what-is-the-difference-between-uniformly-and-at-random-in-crypto-definitions # # random_uniform # # random 指从 Sample Set 里随机抽取一定数量的 Samples。 # # uniform 指 Sample 是均匀分布的。 # Samples 在 Set 里面是均匀分布的。因此每个 Set 里面的 Sample 被取得的几率都是相等的。 # 比如,Set 里有 4 个 Samples。如果 Samples 是均匀分布的,则每个 Sample 被取得的几率都是 1/4。 # # 所以,random_uniform 最终就相当于在规定范围内随机取数。 Weights = tf.Variable(tf.random_uniform([5], -1.0, 1.0)) # Init sess. This have to be done before using Weight. sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) print (sess.run(Weights));
names_list = [["Ellen", "Betty", "Diana"], ["Fox", "Helen", "Andy"], ["Ian", "Glen", "Carol"]] for names in names_list: for i, name in enumerate(names): if i != len(names) - 1: print(name, end=",") else: print(name)
def calc_item(price, count): return price * count def calc_total(items): total = 0 for item in items: total += calc_item(**item) return total items = [{"price": 100, "count": 3}, {"price": 200, "count": 2}, {"price": 300, "count": 1}] total = calc_total(items) print(f"{total:,}")
names = ["Andy", "Betty", "Carol"] for i, name in enumerate(names): print(f"{i+1}:{name}")
def append_list(list1, list2): return list1 + list2 names1 = ["Andy", "Bob", "Carol"] names2 = ["Alice", "Betty", "Charlie"] print(append_list(names1, names2))
scores = [90, 95, 80, 85, 80, 95, 80, 90, 100] score_count_dict = {} for score in scores: count = 1 if score in score_count_dict.keys(): count = score_count_dict[score] count = count + 1 score_count_dict[score] = count for score, count in score_count_dict.items(): print(f"{score:3}:", count)
some_string = "Hi, hello how are you doing. My name is Sandeep Siddapureddy. Some people call me Sandy or Deep. I don't rly care what you call me." count = {} for char in some_string: count.setdefault(char, 0) count[char] = count[char] + 1 for k, v in count.items(): print(k,v) # a = count.keys() # print(a)
# https://www.practicepython.org/exercise/2014/05/21/15-reverse-word-order.html #write a program to reverse order of a stentence def reverse(string): #init final list rev_string = [] #sep initial string sep_string = string.split() for w in sep_string: rev_string.append((sep_string[(len(sep_string)) - (sep_string.index(w)+1)])) print(rev_string) a = "hi my name is sandeep" reverse(a) # input("type a sentence\n") ######## one line solution########### # def reverseWord(w): # return ' '.join(w.split()[::-1])
from threading import Thread, Lock import os import time from queue import Queue if __name__ == "__main__": q = Queue() q.put(1) q.put(2) q.put(3) first = q.get() print(first) q.task_done() #tells that the task is done after u call q.get() q.join() # blocks until all items in queue have been proccessed. Similar to the thread.join() print("end main")
import sys def sum_of_num_gen(n): num = 0 while n>0: yield n num = num + n n -= 1 def sum_of_num_list (nu): count = nu listed = [] while count > 0: listed.append(count) count -=1 return listed print (sum(sum_of_num_list(10000000))) print (sum(sum_of_num_gen(10000000))) print(sys.getsizeof(sum_of_num_list(10000000))) print(sys.getsizeof(sum_of_num_gen(10000000)))
#multiplication operation mult = 2*4 print (mult) #power operation power = 2 ** 4 print(power) #list/tuple/str duplication operation zero = [1, 5] * 10 print(zero) #* args and **kwargs def somefunc(a, b, *args, **kwargs): print(a, b) for arg in args: print(arg) for k in kwargs: print(k , kwargs[k]) somefunc("a", "b", "c", "d", "e", six="f", seven="g") ###unpacking stuff, ** for dictionary def doo(a, b, c): print(a, b, c) some_list= [1, 2, 3] doo(*some_list) #more unpacking, will always unpack into list nums = [1, 2, 3, 4, 5, 6, 7, 8] *beginning_cannamethisanything, last_cannamethisanything = nums print(beginning_cannamethisanything) print(last_cannamethisanything) #to pack, can also pack dictionaries if you use ** a_list = [1, 2, 3] a_tuple = (4, 5, 6) a_set = {5, 6, 7, 8, 9, 9, 9, 9, 9, 9} a_nums = (*a_list, *a_tuple, *a_set) print(*a_list, *a_tuple, *a_set) print(a_nums)
class CountCalls: def __init__ (self, func): self.func = func self.num_calls = 0 #call method allows you to exceute a object of this class, just like a funciton. # For eg if this method has a print function, and you create a class like cc = CountCalls(None), every time you execute (or call?) the object cc(), the print function like will run def __call__(self, *args, **kwargs): self.num_calls += 1 print (f"This is excecuted {self.num_calls} times") return self.func(*args, **kwargs) @CountCalls def say_hello(): print ("hello") say_hello() say_hello()
def permutation(combo: str): length = len(combo) for i in range(length): for j in range(length): swap(combo, i, j) pass pass def swap(combo: str, i, j): temp = combo[i] combo[i] = combo[j] combo[j] = temp
def merge_sort(arr): length = len(arr) if length == 1 or length == 0: return arr mid = (length // 2) left = arr[:mid] right = arr[mid:] left_arr = merge_sort(left) right_arr = merge_sort(right) return merge(left_arr, right_arr) def merge(left_arr, right_arr): arr = [] i = 0 j = 0 c = 0 left_length = len(left_arr) right_length = len(right_arr) while i < left_length and j < right_length: if left_arr[i] < right_arr[j]: arr.append(left_arr[i]) c += 1 i += 1 else: arr.append(right_arr[j]) c += 1 j += 1 while i < left_length: arr.append( left_arr[i]) c += 1 i += 1 while j < right_length: arr.append(right_arr[j]) c += 1 j += 1 return arr if __name__ == '__main__': print(merge_sort([5, 2, 3, 4, 1]))
""" function: arithmetic_arranger: takes a list with up to five entries of "number +- number" prints them in columns formatted according to the specifications found in proj_desc.txt Author: Kai Ellis Date: 2020-09-16 """ import re def arithmetic_arranger(l,tf = False): if len(l) > 5: #check to see if there are more than five problems entered return("Error: Too many problems.") count = 0 for entry in l: #this loop splits the entry into its component parts, allowing us to test for entry errors, and enabling further string manipulation entrylist = entry.split() if len(entrylist[0]) > 4 or len(entrylist[2]) > 4: #check 4 digit max return "Error: Numbers cannot be more than four digits." if not re.match("[+-]",entrylist[1]): #check to see if they have entered an operator other than +- return "Error: Operator must be '+' or '-'." if re.search(r"\D", entrylist[0]) or re.search(r"\D", entrylist[2]): #confirm there are only diget characters return "Error: Numbers must only contain digits." l[count] = entrylist #enter the now broken down equation into the list l[count].append(len(max(l[count],key = len))) #longest number's length, saved for future formatting use if tf == True: #checks if they want an answer, provides if yes l[count].append(eval(entry)) count += 1 toprow = "" bottomrow = "" line = "" answerline = "" for entry in l: #runs through each problem entry and formats them by parts (top number, bottom number, line, and potentially answer) indent = ">" + str(entry[3]) toprow += (" " + format(entry[0],indent) + " ") bottomrow += ( entry[1] + " " + format(entry[2],indent) + " ") line += "-"*(entry[3] + 2) + " " if tf == True: #formats the answer, if desired ansindent = ">" + str(entry[3]+1) answerline += " " + format(entry[4],ansindent) + " " finreturn = (toprow.rstrip() + "\n" + bottomrow.rstrip() + "\n" + line.rstrip()) #merge the component parts into one final answer string if tf == True: #add answer if neccissary finreturn += ("\n" + answerline.rstrip()) return finreturn #return final format if __name__ == "__main__": x = ["32 - 698", "1 - 3801", "45 + 43", "123 + 49"] print(arithmetic_arranger(x, True))
""" lots of exercises for this one: 1): modify the socket program to prompt the user for a url of interest that you can connect to 2) change the program so it counts the number of characters and stops displaying text after it's shown 3000. all should be recieved but only 3k printed 3) change the socket program so that it only shows data post header+blank line note on installing packages with the command line: format is py -m pip install packagename """ import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') html = urllib.request.urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') # Retrieve all of the anchor tags tags = soup('a') for tag in tags: print(tag.get('href', None)) """ mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #open a server socket, connected to the internet that will stream data mysocket.connect((host,80)) #connect to a host and port cmd = f'GET {userl} HTTP/1.0\r\n\r\n'.encode() #issue a command, \r\n\r\n give two carridge returns and two newlines, neccisarry for host recognition mysocket.send(cmd) while True: #receives a datastream from the host at port 512(our port), cuts off streaming if there is no data being imported, decodes the html,css,etc data = mysocket.recv(512) if (len(data) < 1) : break print(data.decode()) #this converts from UTF-8 to string unicode mysocket.close() #closes our internet socket """
""" reading files: bringing the secondary memory into the equation! we will later be getting to databases etc. Text files are just sequences of lines of text separated by newline characters \n (this is recognized as one character not two in python) note: print() always adds a \n to the end of a print statement using open(): handle += open(filename,mode) gives us a variable called handle which we can use to manipulate the file in question filenem must be a string mode is optional: use r for reading, w for writing when file is missing? Traceback error! often for loops are used for reading files: handles just treated as a sequence of lines example: xfile = open('file.txt') for l in xfile: print(l) this loop will print each line in a file count = 0 for l in xfile: count += 1 print("numlines:",count) this loop will count the number of lines in a file can also read the file as a string: but careful, generates a very large string if file is large xfile = open("file.txt") inp = xfile.read() print(len(inp)) #this tells you how large the string is print(inp[:200]) #prints first two hundred char searching for a file: fhand = open("file") for line in fhand: if line.startswith("From:"): print(line) this setup actually double spaces, as print always adds an extra \n strip removes spaces and newlines! fhand = open("file") for line in fhand: line = line.strip() if line.startswith("From:"): print(line) fixed! fhand = open("file") for line in fhand: line = line.strip() if not line.startswith("From:"): continue print(line) does the same thing, but skips any lines that dont start with from: Complete mailbox subject line counter: #fname = input('Enter the file name! ') try: fhand = open(fname) except: print("error, file doesn't exist") quit() #useful for terminating the python program without traceback (more professional) count = 0 for line in fhand: if line.startswith('Subject: ') : count += 1 print("There were", count, "subject lines in", fname) """ # exercise: write a program to read through a file and print the contents in all uppercase: fname = input('Enter the file name of interest! ') try: fhand = open(fname) except: print("this file doesn't exist, please try again.") quit() for line in fhand: line = line.strip() line = line.upper() print(line)
import copy import random # Consider using the modules imported above. class Hat: def __init__(self,**kwargs): #on initialization, will take any number of keywords and append them into a list based on thier value self.contents = [] for arg in kwargs.items(): #cycles through each of the provided keywords i = 1 while i <= arg[1]: #appends the keyword to the list i times, where i is the value of the keyword self.contents.append(arg[0]) i+=1 self.oghat = copy.copy(self.contents) #this copy will be useful for reseting the list def draw(self,numball): #extract a number of items from the list randomly, without replacement if numball >= len(self.contents): #returns the full contents of the bag if the user wants an amount greater than or equal to remaining return self.contents draw = random.sample(self.contents,numball) #does a draw without replacement for d in draw: #they want it to remove the items from our list for some reason? This does that self.contents.remove(d) return draw def reset(self): #resets the bag to it's origional state self.contents = copy.copy(self.oghat) def cif(v2,v1): #does a check if one list is the subset of another, duplicates included. takes two ORDERED lists it = iter(v1) return all(c in it for c in v2) def experiment(hat, expected_balls, num_balls_drawn, num_experiments): count = 0 success = 0 expected_list = [] for arg in expected_balls.items(): #converts from dic to list i = 1 while i <= arg[1]: expected_list.append(arg[0]) i+=1 expected_list = sorted(expected_list) while count < num_experiments: #does a draw num_experiments times, and checks if the expected items were included in the draw. increases success tally if yes, remains the same if no draw = hat.draw(num_balls_drawn) draw = sorted(draw) if cif(expected_list,draw): success += 1 hat.reset() count += 1 prob = success/count return prob if __name__ == "__main__": hat = Hat(blue=3,red=2,green=6) print(experiment(hat=hat, expected_balls={"blue":2,"green":1}, num_balls_drawn=4, num_experiments=100))
# -*- coding: utf-8 -*- """ Created on Thu Sep 17 09:44:38 2020 Bot which asks the user what year they were born, and tells them their horoscope. @author: Randy Zhu """ # Data of the horoscopes. # I wonder how much RAM this uses. rat = [ 1996, 1984, 1972, 1960, 1948 ] ox = [ 1997, 1985, 1973, 1961, 1949 ] tiger = [ 1998, 1986, 1974, 1962, 1950 ] rabbit = [ 1999, 1987, 1975, 1963, 1951 ] dragon = [ 2000, 1988, 1976, 1964, 1952 ] snake = [ 2001, 1989, 1977, 1965, 1953 ] horse = [ 2002, 1990, 1978, 1966, 1954 ] goated = [ 2003, 1991, 1979, 1967, 1955 ] monkey = [ 2004, 1992, 1980, 1968, 1956 ] rooster = [ 2005, 1993, 1981, 1969, 1957 ] dog = [ 2006, 1994, 1982, 1970, 1958 ] pig = [ 2007, 1995, 1983, 1971, 1959 ] # Asks the user what year they were born in. user_year = input("In what year were you born?: ").strip(" ,!.?") # Because input() returns string, we need to cast the user_year variable # to an int. user_year = int(user_year) # Checks if the user's year are in the arrays. if user_year in rat: # Print a response according to their year. print("You were born in the year of the rat.") elif user_year in ox: print("You were born in the year of the ox.") elif user_year in tiger: print("You were born in the year of the tiger.") elif user_year in rabbit: print("You were born in the year of the rabbit") elif user_year in dragon: print("You were born in the year of the dragon") elif user_year in snake: print("You were born in the year of the snake") elif user_year in horse: print("You were born in the year of the horse") elif user_year in goated: print("You are goated") elif user_year in monkey: print("You were born in the year of le monke") elif user_year in rooster: print("You were born in the year of the rooster") elif user_year in dog: print("You were born in the year of the dog") elif user_year in pig: print("You were born in the year of the pig.")
# -*- coding: utf-8 -*- """ Created on Mon Oct 5 09:02:50 2020 evaluates city bliss. @author: Randy Zhu """ # Ask about which city to evaluate. city = input("What city would you like to evaluate?: ") # Tell the user which city they are evaluating. print("Okay, we are evaluating " + city + ".\n") # Make a list of questions. questions = [ "How would you rate the environment out of 5?: ", "How would you rate the safety out of 5?: ", "How would you rate the public transport system out of 5?: " ] # Initialize score. score = 0 # for each question in the list, make a rating variable, which is the user's # input out of five, ask the user about how much that rating means to them, # and add it to score, multiplying the rating by the weight. for question in questions: rating = int(input(question)) weight = int(input("How important is that to you, out of 5?: ")) score += rating * weight # print a newline. print() # Tell the user their weighted average score. print("You have rated " + city + " as " + str(score / (25 * len(questions))))
# -*- coding: utf-8 -*- """ Created on Fri Sep 18 09:27:56 2020 @author: Randy Zhu """ X = 10 Y = 5 print("x is: " + str(X)) print("y is: " + str(Y)) # nah. print("Is x equal to y?: " + str(X == Y))
# -*- coding: utf-8 -*- """ Created on Fri Nov 6 08:47:46 2020 @author: 1257035 """ import turtle from random import randint anna = turtle.Turtle() anna.speed(0) def draw_cookie(x: int, y: int) -> None: """ Draw a cookie. """ # Draw cookie outside anna.penup() anna.goto(-5 + x, -30 + y) anna.pendown() anna.circle(30) anna.penup() # Chocolate chip in the middle. anna.goto(0 + x, 0 + y) anna.stamp() # Chocolate chip bottom left. anna.goto(-10 + x, -10 + y) anna.stamp() # Chocolate chip top left. anna.goto(-10 + x, 10 + y) anna.stamp() # Chocolate chip top right. anna.goto(10 + x, -10 + y) anna.stamp() anna.goto(10 + x, 10 + y) anna.stamp() while True: draw_cookie(randint(-500, 500), randint(-500, 500)) for index in range(0, 500, 100): draw_cookie(index, 0) turtle.done()
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 09:16:26 2020 Calculate age in 2051. @author: Randy Zhu """ CURRENT_YEAR = 2020 current_age = int(input("How old are you right now?: ")) print("You wil be " + str(2051 - CURRENT_YEAR + current_age) + " years old in 2051!")
""" Author: Randy Zhu Purpose: Determine whether the user is in the dark or light. Date: 09-30-2020 """ # Introduce yourself. print("I will decide whether you can join the Dark Side.") # Set variables. IN_DARK = False # Ask user for input. user_likes_red_input = input("Is red your favorite color?: ") user_likes_capes_input = input("Do you like capes?: ") # If the user likes red or capes, set IN_DARK to True. if (user_likes_red_input.lower().strip("?!. ") == "yes" or user_likes_capes_input.lower().strip("?!. ") == "yes"): IN_DARK = True # If IN_DARK is True, tell them that they are in the dark side. if IN_DARK: print("Dark side it is!") # Otherwise, say that they're in the light side. else: print("Light side, I see.")
# -*- coding: utf-8 -*- """ Created on Wed Oct 14 09:01:13 2020 Produce an amortization chart for a mortage. @author: Randy Zhu """ # Import higher precision math library to prevent weird rounding errors with floating points from decimal import Decimal # Ask the user for inputs on purchase price of the home, the payment period, interest rate as a percent, # down payment, and payment amount per period. purchase_price = Decimal(input("What is the purchase price of the home?: ")) payment_type = input( "What is the payment type of the mortgage?: ").lower().strip("!?. ") interest_rate = Decimal( input("What is the interest rate of the mortgage as a percent?: ").strip("%")) * Decimal(10**-2) down_payment = (Decimal( input("What is the down payment of the mortgage expressed as a percent?: ").strip("%")) * Decimal(10**-2)) * purchase_price payment_amount = Decimal( input("What is the payment amount of the mortgage?: ")) # Define a payment_weekly variable, and set it to zero. payment_weeks = 0 # Define another payment name variable, which we will set later. payment_name = "" # Set payment data accordingly with user input. if payment_type == "monthly": payment_weeks = 12 payment_name = "Month: " elif payment_type == "semi-monthly": payment_weeks = 24 payment_name = "Half month: " elif payment_type == "bi-weekly": payment_weeks = 26 payment_name = "Bi - week: " elif payment_type == "weekly": payment_weeks = 52 payment_name = "Week: " # Set the intital loan amaount. loan_amount = purchase_price - down_payment # Set the initial interest rate. interest_rate_for_payment = interest_rate / payment_weeks # Set the initital price of interest on a payment interest_rate_per_payment = loan_amount * interest_rate_for_payment # Print first column on table. print( """ | Period | Starting Balance | Payment | Interest | Principle | Ending Balance | """, end="" ) # First set the balance to be the loan amount. balance = loan_amount # We need a counter for the loop to indicate which month. months = 0 # The principle is the subtractive result of the payment and the interest rate for each payment principle = 0 # The annual interest and principle. pperannum = 0 iperannum = 0 # The totals of the payment. pcum = 0 icum = 0 # While the balance is not paid: while balance - principle > 0: # Subtract the balance per principle as payment, balance -= principle # Set the interest rate as the remaining balance, which was previously subtracted multiplied by th t # e # interest rate for the payment overall. interest_rate_per_payment = balance * interest_rate_for_payment # Alas, set the principle to the payment amount minus the interest rate per payment. principle = payment_amount - interest_rate_per_payment # If the balance without the principle is lesser than 0, declare that it is paid. if balance - principle < 0: print( # Print the month, and the cumulative principle and interest. f"| Month {months + 1} | Paid! | Final interest paid ${round(icum,2)} | Final principle paid ${round(pcum, 2)}") # Stop looping. # break # Print the stats print( f""" | {payment_name + str(months + 1)} | {"$" + str(round(balance, 2))} | {"$" + str(payment_amount)} | {"$" + str(round(interest_rate_per_payment, 2))} | {"$" + str(round(principle, 2))} | {"$" + str(round(balance - principle, 2))} | """, end="" ) # After displaying the payment, and performing the calculations, # add the principle to the cumulative payments. pcum += principle icum += interest_rate_per_payment # Add the same thing to the payment per annum. # Why do we do this? Because this is the per annum # payment for the program, and below, we clear the value # if a month has passed. pperannum += principle iperannum += interest_rate_per_payment # Check whether a month has passed per payment type, and report accordingly. if payment_type == "monthly": if (months + 1) % 12 == 0: print(f"iperannum: {round(iperannum, 2)}") print(f"pperannum: {round(pperannum, 2)}") iperannum = 0 pperannum = 0 if payment_type == "semi-monthly": if (months + 1) % 24 == 0: print(f"iperannum: {round(iperannum, 2)}") print(f"pperannum: {round(pperannum, 2)}") iperannum = 0 pperannum = 0 if payment_type == "bi-weekly": if (months + 1) % 26 == 0: print(f"iperannum: {round(iperannum, 2)}") print(f"pperannum: {round(pperannum, 2)}") iperannum = 0 pperannum = 0 if payment_type == "weekly": if (months + 1) % 52 == 0: print(f"iperannum: {round(iperannum, 2)}") print(f"pperannum: {round(pperannum, 2)}") iperannum = 0 pperannum = 0 # Add one to the months. months += 1
from threading import Thread # a. Run the following concurrent program. Are there any particular patterns in # the output? Is the interleaving of the output from the two threads # predictable in any way? # # Ans a). # No, there is no particular pattern in the output. Also, there is no # predictabilty in the output from the two thread. # # b. If the answer to part (a) is affirmative, run the same program while # browsing the web. Does the pattern you outlined in section (a) hold? # # Ans b). # The pattern is not predictable and is different each time the program is # run. # # c. In general, can one rely on a particular timing/interleaving of executions # of concurrent processes? # # Ans c). # We cannot rely on a particular timing/interleaving of executions of # concurrent processes. # # d. Given that there are no synchronization operations in the code below, any # interleaving of executions should be possible. When you run the code, do # you believe that you see a large fraction of the possible interleavings? If # so, what do you think makes this possible? If not, what does this imply # about the effectiveness of testing as a way to find synchronization errors? # # Ans d). # Yes, we see large fraction of the possible interleavings. The Operating # system is making this possible by scheduling the processes in and out. # class Worker1(Thread): def __init__(self): Thread.__init__(self) def run(self): while True: print("Hello from Worker 1") class Worker2(Thread): def __init__(self): Thread.__init__(self) def run(self): while True: print("Hello from Worker 2") w1 = Worker1() w2 = Worker2() w1.start() w2.start() ## ## vim: ts=4 sw=4 et ai ##
#!/usr/bin/env python # -*- coding=utf8 -*- import chardet import sys # print sys.argv filelist=sys.argv[1:] # print filelist # exit() # open file not_converted=[] for ifile in filelist : # print ifile try: inputfile=open(ifile, 'r') except IOError: print "can not open file ", ifile continue # read file content content=inputfile.read() # print content encoding=chardet.detect(content)['encoding'] inputfile.close() # print encoding # convert to utf8 if encoding!='utf-8': content_utf8 = content.decode(encoding) print content_utf8 ss=raw_input("is the content correct?") if ss=='y': outputfile=open(ifile,'w') outputfile.write(content_utf8.encode('utf-8')) outputfile.close() else: not_converted=not_converted.append(ss) continue print "not converted files are", not_converted # write to file # print content_utf8.encode('utf8')
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ product = 0 for a in range(1000): for b in range(a, 1000): c = (1000 - a - b) if a**2 + b**2 == c**2: product = a * b * c print(product)
#!/usr/bin/python from core_tool import * def Help(): return '''List up the attributes or assign value to an element. Usage: attr attr 'list' [MAX_LEVEL] List up the attributes MAX_LEVEL: Maximum level of printed attribute attr 'keys' [MAX_LEVEL, ] [KEY1 [, KEY2 [, ...]]] List up the keys of attributes with their types (not values) MAX_LEVEL: Maximum level of printed attribute KEY*: List of attribute keys attr 'show' [KEY1 [, KEY2 [, ...]]] Show the value of the specified attribute KEY*: List of attribute keys attr 'set' KEY1 [, KEY2 [, ...]], VALUE Assign VALUE to the specified attribute KEY*: List of attribute keys VALUE: Value attr 'del' KEY1 [, KEY2 [, ...]] Delete the specified attribute KEY*: List of attribute keys attr 'savemem' [, MEM_FILE] Save 'memory' into a file. MEM_FILE: Memory file in YAML format (default: MEMORY_FILE). attr 'loadmem' [, MEM_FILE] Load 'memory' from a file. MEM_FILE: Memory file in YAML format (default: MEMORY_FILE). attr 'dump', DUMP_FILE Save the whole attributes into DUMP_FILE. DUMP_FILE: Data file in YAML format. attr 'load', YAML_FILE Load from YAML_FILE. YAML_FILE: Data file in YAML format. Note: The default memory file MEMORY_FILE is defined in base_const.py Example: attr set 'c1','x', [0,0,0, 0,0,0,1] ''' def Run(t,*args): col= 1 c1,c2= ACol.X2(col) with t.attr_locker: if len(args)==0: PrintDict(t.attributes,col=col) else: command= args[0] args= args[1:] if command=='list': if len(args)==0: PrintDict(t.attributes, col=col) elif len(args)==1: PrintDict(t.attributes,max_level=args[0], col=col) else: raise Exception('Invalid arguments for %r: %r'%(command,args)) elif command=='keys': if len(args)==0: PrintDict(t.attributes,keyonly=True, col=col) else: if isinstance(args[0],int): max_level= args[0] keys= args[1:] else: max_level= -1 keys= args value= t.GetAttr(*keys) if isinstance(value,dict): if len(keys)==0: PrintDict(value,max_level=max_level,level=0,keyonly=True, col=col) else: print '%s[%s]%s= ...' % (c1,']['.join(keys),c2) PrintDict(value,max_level=max_level,level=1,keyonly=True, col=col) else: print '%s[%s]%s= %s' % (c1,']['.join(keys),c2, type(value)) elif command=='show': value= t.GetAttr(*args) if isinstance(value,dict): if len(args)==0: PrintDict(value,level=0, col=col) else: print '%s[%s]%s= ...' % (c1,']['.join(args),c2) PrintDict(value,level=1, col=col) else: print '%s[%s]%s= %r' % (c1,']['.join(args),c2, value) elif command=='set': t.SetAttr(*args) print 'Set:' Run(t,'show',*(args[:-1])) elif command=='del': t.DelAttr(*args) print 'Deleted: [%s]' % (']['.join(args)) elif command=='savemem': file_name= args[0] if len(args)>0 else MEMORY_FILE if os.path.exists(file_name): print 'File %r exists. Do you want to overwrite?' % file_name if not t.AskYesNo(): return SaveYAML(t.GetAttrOr({},'memory'), file_name) print 'Saved memory into: %r' % file_name elif command=='loadmem': file_name= args[0] if len(args)>0 else MEMORY_FILE if not os.path.exists(file_name): CPrint(4,'Memory file does not exist:',file_name) return if t.HasAttr('memory'): print 'Memory exists. Do you want to load from %r?' % file_name if not t.AskYesNo(): return t.AddDictAttr('memory', LoadYAML(file_name)) print 'Loaded memory from: %r' % (file_name) elif command=='dump': file_name= args[0] if os.path.exists(file_name): print 'File %r exists. Do you want to overwrite?' % file_name if not t.AskYesNo(): return SaveYAML(t.GetAttrOr({}), file_name) print 'Saved attributes into: %r' % file_name elif command=='load': file_name= args[0] print 'Do you want to load attributes from %r?' % file_name if not t.AskYesNo(): return t.AddDictAttr(LoadYAML(file_name)) print 'Loaded attributes from: %r' % (file_name) else: print 'Invalid command' print Help()
class Product(object): def __init__(self, price, item_name, weight, brand, status="for sale"): self.price = price self.item_name = item_name self.weight = weight self.brand = brand self.status = status # print self def display_all(self): print self return self def __repr__(self): return "Price: ${}, Item name: {}, Weight: {}, Brand: {}, Status: {}".format(self.price, self.item_name, self.weight, self.brand, self.status) def sold(self): self.status = "Sold" print self return self def tax(self): self.price += self.price * .10 print self return self def returns(self, condition): self.condition = condition if self.condition == "defective": self.price = 0 self.status = "defective" # return self elif self.condition == "in box": self.status = "like new" # return self elif self.condition == "opened": self.status = "used" self.price = (self.price *.80) return self if __name__ == "__main__": Motor_oil = Product(price = 25, item_name = "Motor Oil", weight = "1 quart", brand = "Penzoil") # print Motor_oil print Motor_oil.returns("opened")