text
stringlengths
37
1.41M
#81 # Time: O(logn) # Space: O(1) # Follow up for "Search in Rotated Sorted Array": # What if duplicates are allowed? # # Would this affect the run-time complexity? How and why? # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # # Write a function to determine if a given target is in the array. # # The array may contain duplicates. class binarySearchSol(): def searchInRotatedArrayII(self,nums,target): left,right=0,len(nums)-1 while left<=right: mid=(left+right)//2 if nums[mid]==target: return True #elif nums[left]==nums[mid]: # left+=1 elif (nums[mid]>=nums[left] and nums[left]<=target<nums[mid]) or \ (nums[mid]<nums[left] and not(nums[mid]<target<=nums[right])): right=mid-1 else: left=mid+1 return False
#111 # Time: O(n) # Space: O(h), h is height of binary tree # Given a binary tree, find its minimum depth. # # The minimum depth is the number of nodes along the shortest path # from the root node down to the nearest leaf node. class TreeNode(): def __init__(self,val): self.val=val; self.right=None self.left=None class treeSol(): def minDepthOfTree(self,root): if not root: return 0 if root.left and root.right: return min(self.minDepthOfTree(root.left),self.minDepthOfTree(root.right))+1 else: return max(self.minDepthOfTree(root.left),self.minDepthOfTree(root.right))+1
#122 # Time: O(n) # Space: O(1) # Say you have an array for which the ith element # is the price of a given stock on day i. # Design an algorithm to find the maximum profit. # You may complete as many transactions as you like # (ie, buy one and sell one share of the stock multiple times). # However, you may not engage in multiple transactions at the same time # (ie, you must sell the stock before you buy again). class greedySol(): def bestTimeBuySellStock(self,prices): max_profit=0 for day in range(len(prices)-1): max_profit+=max(0,prices[day+1]-prices[day]) return max_profit
#143 # Time: O(n) # Space: O(1) # Given a singly linked list L: L0→L1→…→Ln-1→Ln, # reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… # # You must do this in-place without altering the nodes' values. # # For example, # Given {1,2,3,4}, reorder it to {1,4,2,3}. class ListNode(): def __init__(self,val): self.val=val self.next=None def __repr__(self): return '{}->{}'.format(self.val,repr(self.next)) class listSol(): def reorderList(self,head): slow,fast=head,head while fast and fast.next: prev,fast,slow=slow,fast.next.next,slow.next prev.next=None while slow: prev.next,slow.next,slow=slow,prev.next,slow.next head2,prev.next=prev.next,None dummy=ListNode(-1) cur=dummy while head and head2: cur.next,head=head,head.next cur=cur.next cur.next,head2=head2,head2.next cur=cur.next cur.next=head or head2 return dummy.next
#7 # Space: O(1) # Given a 32-bit signed integer, reverse digits of an integer. # # Example 1: # Input: 123 # Output: 321 # Example 2: # Input: -123 # Output: -321 # Example 3: # Input: 120 # Output: 21 # # Note: # Assume we are dealing with an environment # which could only hold integers within the 32-bit signed integer range. # For the purpose of this problem, # assume that your function returns 0 when the reversed integer overflows. class mathSol(): def reverseInteger(self,num): if num<0: return -self.reverseInteger(-num) reversed_int=0 while num: reversed_int=reversed_int*10+num%10 num//=10 return reversed_int if reversed_int <= 0x7fffffff else 0
#285 # Time: O(h) height of BST # Space: O(1) # Given a binary search tree and a node in it, # find the in-order successor of that node in the BST. # # Note: If the given node has no in-order successor # in the tree, return null. class TreeNode(): def __init__(self,val): self.val=val; self.right=None self.left=None class binarySearchTree(): def inOrderSuccessorInBST(self,root,node): if node.right: node=node.right while node.left: node=node.left return node successor=None while root and root!=node: print(root.val) print('node ',node.val) if root.val>node.val: successor=root root=root.left else: root=root.right return successor
#206 # Time: O(n) # Space: O(1) # Reverse a singly linked list. class ListNode(): def __init__(self,val): self.val=val self.next=None def __repr__(self): return '{}->{}'.format(self.val,repr(self.next)) class ListSol(): def reverseListI(self,head): dummy=ListNode(-1) cur=head while cur: dummy.next,cur.next,cur=cur,dummy.next,cur.next return dummy.next
#71 # Time: O(n) # Space: O(n) # Given an absolute path for a file (Unix-style), simplify it. # # For example, # path = "/home/", => "/home" # path = "/a/./b/../../c/", => "/c" class stackSol(): def simplifyPath(self,path): split_path=path.split('/') simplify_path=[] for path_elem in split_path: if path_elem=='..' and simplify_path: simplify_path.pop() elif path_elem!='..' and path_elem!='.' and path_elem: simplify_path.append(path_elem) return '/'+'/'.join(simplify_path)
#Generate a random number with a seed between a range of two numbers - Both Integer and Decimal from random import seed from random import randint from random import uniform class GenNumWithSeed: @staticmethod def random_int(a, b, nut): seed(nut) if isinstance(a, float): return GenNumWithSeed.random_float return randint(a, b) @staticmethod def random_float(a, b, nut): seed(nut) return uniform(a, b)
def median(a, b, c, d, e): try: a = int(a) b = int(b) c = int(c) d = int(d) e = int(e) median_list = [a, b, c, d, e] length = len(median_list) sorted_median_list = sorted(median_list) return sorted_median_list[2] except ZeroDivisionError: print("Error - Cannot divide by 0") except ValueError: print("Error - Invalid data inputs")
"""Openrouteservice API function to perform API calls in the Truck class.""" import requests from config import ORS_URL, ORS_HEADERS def get_direction(start: dict, end: dict): """Make API call to OpenRouteService API to generate directions. Args: start (dict): Starting point, contains keys lat and lng with matching lattitude and longitude of point. end (dict): End point, contains keys lat and lng with matching lattitude and longitude of point. Returns: dict: JSON associated with returned call """ params = { "start": ",".join(map(str, [start['lng'], start['lat']])), "end": ",".join(map(str, [end['lng'], end['lat']])) } call = requests.get(ORS_URL, params=params, headers=ORS_HEADERS) return call.json()
def eratosthenes_sieve(N): # Increment once in order to remove redundancy N += 1 prime = [True] * (N) primes_tab = [2] for c in range(3, N, 2): if prime[c] == True: primes_tab.append(c) # Mark all multiples of c as composite for mul_c in range(c*c, N, c): prime[mul_c] = False return primes_tab if __name__ == '__main__': eratosthenes_sieve(500)
import asyncio #To inicate that the function coroutine we must add async before the def async def foo(): for i in range(10): #Await means to wait until that line of code is finished #Note that we can only put await if it's in a coroutine function await asyncio.sleep(1) print(1) async def fee(): print('start task 1') #Once again asyncio.sleep is just imitating an action that takes time to get done await asyncio.sleep(5) #after a certain amont of time this will indicate if it's finished print('task 1 is done!') async def fees(): print('start task 2') await asyncio.sleep(4) print('task 2 done!') async def main(): #with task it can switch between them if the current function is not needed to run task1 = asyncio.create_task(fee()) task2 = asyncio.create_task(foo()) task3 = asyncio.create_task(fees()) #This await lines on the task is an indicator that it must finish it, If you didn't add awaits the functions will not be finished await task2 await task1 await task3 #To run a async function use asyncio.run asyncio.run(main())
import math r = int(input('r: ')) s = round(math.pi * r * r, 3) p = round(2 * math.pi * r, 3) print('S: ', s) print('P: ', p)
year = int(input('input an year: ')) if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: print(year, 'liigaasta') else: print(year, 'pole liigaasta')
""" 用类和面向对象的思想,“描述”生活中任意接触到的东西 (比如动物、小说里面的人物,不做限制,随意发挥),数量为5个。 """ #描述狗的类 class Dog: #构造方法,传入种类,颜色 def __init__(self,dog_type,dog_colour): #种类 self.dog_type = dog_type #颜色 self.dog_colour = dog_colour #看门 def watch_door(self): print(f"{self.dog_type}可以在家看门") #颜值 def level_of_appearance(self): print(f"{self.dog_colour}的{self.dog_type}最可爱") #公司类 class Company: #构造方法 def __init__(self,company_name,company_nature): #公司名称 self.company_name = company_name # 公司性质 self.company_nature = company_nature #公司基本信息 def information(self): print(f"{self.company_name}是{self.company_nature}的一个公司") #公司地址,传入公司地址company_address def address(self,company_address): print(f"{self.company_name}位于{company_address}") #手机类 class Mobile_Phone: #构造方法,传入手机的型号model def __init__(self,model): self.model = model #所属品牌,传入品牌brand def modile_phone_brand(self,brand): print(f"{self.model}属于{brand}的手机") #手机综合评价,传入综合评分 def modile_phone_evaluate(self,score): print(f"{self.model}的综合评分为{score}") #学生类 class student: #构造方法,传入学生的姓名 def __init__(self,name): self.name = name #学生的年级,传入学生的年级grade def student_grade(self,grade): print(f"{self.name}现在在上{grade}") #学生的学校,传入学生的学校名称school_name def student_school_name(self,school_name): print(f"{self.name}就读于{school_name}") #游戏类 class game: #构造方法,传入游戏的英雄名称name def __init__(self,name): self.name = name #判断类型,传入类型type def hero_type(self,type): print(f"{self.name}属于{type}的英雄") #适合位置,传入位置参数position def hero_position(self,position): print(f"{self.name}适合打{position}")
from random import randint # Number of words you want to get in your password word_num = 5 # Import and organize the dictionaly of words d = {} with open("diceware.wordlist.asc", "r") as f: for item in f: ssplit = item.split() key = ssplit.pop(0) d[key] = ssplit # Generate and print! random_num_sequence = '' random_word_sequence = '' for i in range(word_num): current = '' for i in range(5): random_num_sequence = random_num_sequence + str(randint(1, 6)) current = current + str(randint(1, 6)) random_num_sequence = random_num_sequence + ' ' random_word_sequence = random_word_sequence + str(d[current][0]) + ' ' print (random_num_sequence) print (random_word_sequence)
# A few handy functions # Converts input to lower case, splits words into a list def get_smart(prompt): raw_input = input(prompt) # Convert the input to lower case: smooth_input = raw_input.lower() # Convert the lower case input into a list: input_list = smooth_input.split() # print(input_list) # for testing return(input_list) # Checks whether *name* appears in *list* def is_in(name, list): if name in list: return(True) else: return(False) # Sample functions def eat(fruit): print('OK, you ate the', fruit) def take(fruit): print('OK, you took the', fruit) def peel(fruit): print('OK, you peeled the', fruit) def throw(fruit): print('OK, you threw the', fruit) # Example - first, a familiar list, then a new one: fruit = ['apples', 'oranges', 'pears', 'bananas'] commands = ['take', 'peel', 'throw', 'eat'] # Get user input, e.g., take apples user_command = get_smart("Enter a command: ") # Check command - *False* if the command is valid if not is_in(user_command[0], commands): print(user_command[0], 'is a not a command I recognize') print('I know these commands: ', commands) # Check fruit - *False* if the fruit is valid elif not is_in(user_command[1], fruit): print(user_command[1], 'is a not a fruit I recognize') print('I know these fruits: ', fruit) # If they're both *False,* then else: print('\n->', *user_command, '<- is legit!\n') # FYI, this is pure magic: globals()[user_command[0]](user_command[1])
# -*- coding: utf-8 -*- import re def word_length(sentence): return sentence.count(' ') + 1 def tokenize_sentence_and_filte_tokens( text_str, tokenizer, token_filters, ): tokenized_text_lst = tokenizer.cut(text_str) filted_tokens = [] for token in tokenized_text_lst: filted_tokens.append( token_filters(token) ) while ' ' in filted_tokens: filted_tokens.remove(' ') while '' in filted_tokens: filted_tokens.remove('') return ' '.join(filted_tokens) def set_sentence_splitting_token(sentence): sentence = re.sub('[^\w\d ]', ';', sentence) sentence = re.sub(';+', ';', sentence) sentence = re.sub('^;+|;+$', '', sentence) sentence = re.sub(' +', ' ', sentence) sentence = re.sub('^ +| +$', '', sentence) return sentence.lower() def clean_sentence_splitting_token(sentence): sentence = re.sub(';', ' ', sentence) sentence = re.sub(' +', ' ', sentence) sentence = re.sub('^ +| +$', '', sentence) return sentence.lower() def split_sentence( sentence, min_sentence_length=30, max_sentence_length=200 ): splitted_sentences = [] sentence = re.sub(' ;', ';', sentence) short_sentences = sentence.split(';') short_sentence_list = [] sentence_length = 0 for short_sentence in short_sentences: short_sentence_length = word_length(short_sentence) if sentence_length + short_sentence_length < max_sentence_length: sentence_length += short_sentence_length short_sentence_list.append(short_sentence) elif sentence_length < min_sentence_length: short_sentence_list.append(short_sentence) splitted_sentences.append(' '.join(short_sentence_list)) short_sentence_list = [] sentence_length = 0 else: splitted_sentences.append(' '.join(short_sentence_list)) short_sentence_list = [short_sentence] sentence_length = short_sentence_length if sentence_length > 0 and sentence_length < min_sentence_length: splitted_sentences[-1] += ' ' + ' '.join(short_sentence_list) elif sentence_length >= min_sentence_length: splitted_sentences.append(' '.join(short_sentence_list)) return splitted_sentences def split_document( document, tokenizer, token_filters, min_sentence_length=30, max_sentence_length=200 ): confident_splitting_tokens = [ '。', '\n', '\\\\n', '!', '\![^\w\d]', '?', '\?[^\w\d]', '\.[^\w\d]' ] sentences = re.split('|'.join(confident_splitting_tokens), document) clean_sentences = [] for sentence in sentences: sentence = set_sentence_splitting_token(sentence) sentence = tokenize_sentence_and_filte_tokens( sentence, tokenizer, token_filters ) sentence = re.sub(' ; ', ' ;', sentence) sentence_word_length = word_length(sentence) if sentence_word_length < min_sentence_length: continue elif sentence_word_length > max_sentence_length: splitted_sentences = split_sentence( sentence, min_sentence_length, max_sentence_length ) for splitted_sentence in splitted_sentences: clean_sentences.append(splitted_sentence) else: sentence = clean_sentence_splitting_token(sentence) clean_sentences.append(sentence) return clean_sentences
# Caesar cipher import string def encrypt(s, n): letters = string.ascii_uppercase s_encrypted = "" key = {} for i in range(0, 26): key.update({letters[i]:letters[(i+n)%26]}) for v in s.upper(): s_encrypted+=key[v] return s_encrypted if __name__ == "__main__": s = raw_input("Enter a string to encrypt: ") n = int(raw_input("Enter an offset number: ")) print "%s shifted %d is %s" %(s, n, encrypt(s, n))
n = int(input("Enter rows: ")) for i in range(0, n): for j in range(0, i+1): print("x", end="") print() print("Hola mundo")
from ps4a import * import time # Computer chooses a word def compChooseWord(hand, wordList, n): """ Given a hand and a wordList, find the word that gives the maximum value score, and return it. This word should be calculated by considering all the words in the wordList. If no words in the wordList can be made from the hand, return None. hand: dictionary (string -> int) wordList: list (string) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: string or None """ # Create a new variable to store the maximum score seen so far (initially 0) bestScore = 0 # Create a new variable to store the best word seen so far (initially None) bestWord = None # For each word in the wordList for word in wordList: # If you can construct the word from your hand if isValidWord(word, hand, wordList): # find out how much making that word is worth score = getWordScore(word, n) # If the score for that word is higher than your best score if (score > bestScore): # update your best score, and best word accordingly bestScore = score bestWord = word # return the best word you found. return bestWord # # Computer plays a hand # def compPlayHand(hand, wordList, n): """ Allows the computer to play the given hand, following the same procedure as playHand, except instead of the user choosing a word, the computer chooses it. 1) The hand is displayed. 2) The computer chooses a word. 3) After every valid word: the word and the score for that word is displayed, the remaining letters in the hand are displayed, and the computer chooses another word. 4) The sum of the word scores is displayed when the hand finishes. 5) The hand finishes when the computer has exhausted its possible choices (i.e. compChooseWord returns None). hand: dictionary (string -> int) wordList: list (string) n: integer (HAND_SIZE; i.e., hand size required for additional points) """ # Keep track of the total score totalScore = 0 # As long as there are still letters left in the hand: while (calculateHandlen(hand) > 0) : print("Current Hand: ", end=' ') displayHand(hand) word = compChooseWord(hand, wordList, n) if word == None: # End the game (break out of the loop) break else : if (not isValidWord(word, hand, wordList)) : print('This is a terrible error! I need to check my own code!') break else : score = getWordScore(word, n) totalScore += score print('"' + word + '" earned ' + str(score) + ' points. Total: ' + str(totalScore) + ' points') hand = updateHand(hand, word) print() print('Total score: ' + str(totalScore) + ' points.') # # Problem #6: Playing a game # # def playGame(wordList): print("Welcome to the Word Scramble Game 'You Vs Computer'!!!\n") previoushand={} gameplayedflag=0 while True: prompt=input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ") if prompt not in 'ner': print("Invalid input, Please Try again") continue if prompt=='e': break if prompt=='n': gameplayedflag=1 while True: whoplays_prompt=input("Enter u to have yourself play, c to have the computer play: ") if whoplays_prompt not in "uc": print("Invalid Entry,only u and c response allowed") continue else: break if whoplays_prompt=="u": hand=dealHand(HAND_SIZE) previoushand=hand.copy() playHand(hand,wordList,HAND_SIZE) elif whoplays_prompt=="c": hand=dealHand(HAND_SIZE) previoushand=hand.copy() compPlayHand(hand,wordList,HAND_SIZE) else: print("invalid Entry") continue if prompt=='r': if gameplayedflag==0: print("You have not played a hand yet. Please play a new hand first!") print() continue hand=previoushand while True: whoplays_prompt=input("Enter u to have yourself play, c to have the computer play: ") if whoplays_prompt not in "uc": print("Invalid Entry,only u and c response allowed") continue else: break if whoplays_prompt=="u": playHand(hand,wordList,HAND_SIZE) elif whoplays_prompt=="c": compPlayHand(hand,wordList,HAND_SIZE) # # Build data structures used for entire session and play game # if __name__ == '__main__': wordList = loadWords() playGame(wordList)
""" Faça uma prova de matemática para crianças que estão aprendendo a somar números inteiros menores que 100. Escolha números aleatórios entre 1 e 100, e mostre na tela a pergunta: qual é a soma de a + b, onde a e b são os números aleatórios. Peça a resposta. Faça cinco perguntas ao aluno, e mostre para ele as perguntas e as respostas corretas, além de quantas vezes o aluno acertou. """ import random pergunta = 1 acerto = 0 respostas_certas = [] while pergunta <=5: a = random.randint(1, 100) b = random.randint(1, 100) resposta = int(input(f'qual é a soma de {a} + {b}? ')) respostas_certas.append(f'soma de {a}+{b} = {a+b}') if resposta == (a+b): acerto += 1 pergunta += 1 print('\nRespostas certas:') for i in range(5): print(respostas_certas[i]) print(f'\nVocê acertou {acerto} perguntas.')
""" Leia um valor em segundos, e imprima-o em horas, minutos e segundos. """ total_segundos = int(input('digite um valor em segundos: ')) segundo = total_segundos % 60 minuto = (total_segundos // 60) % 60 hora = (total_segundos // 60) // 60 print(f'{hora} hora(s), {minuto} minuto(s) e {segundo} segundo(s)')
""" Faça um programa que receba dois numeros e mostre o maior. Se por acaso, os dois numeros forem iguais, imprima a mensagem 'Numeros iguais'. """ num1 =int(input('digite um numero: ')) num2 =int(input('digite outro numero: ')) if num1 > num2: print(f'O numero {num1} é maior.') elif num1 == num2: print(f'Numeros iguais.') else: print(f'O numero {num2} é maior.')
""" Faça um programa que leia 10 inteiros positivos, ignorando não positivos, e imprima sua média. """ soma = 0 cont = 0 for i in range(10): number = int(input(f'digite o valor {i+1}/10: ')) if number >= 0: soma += number cont += 1 print(f'A media dos valores positivos eh igual a {soma/cont:.2f}')
""" Faça um programa que receba um numero inteiro e verifique se este numero é par ou impar. """ num = int(input('digite um numero: ')) if num % 2 == 0: print('O numero digitado é par.') else: print('O numero digitado é impar.')
""" Faça um programa que leia um número inteiro positivo impar N e imprima todos os numeros impares de N até 1 em ordem decrescente. """ num = 60 for i in range(num-1, 0, -2): print(i)
""" Faça um programa que leia 10 inteiros e imprima sua média. """ soma = 0 for i in range(10): number = int(input(f'digite o valor {i+1}/10: ')) soma += number print(f'A media dos valores eh igual a {soma/10:.2f}')
""" Faça um programa que mostre ao usuário um menu com 4 opções de operações matemáticas (as básicas, por exemplo). O usuário escolhe uma das opções e o seu programa então pede dois valores numéricos e realiza a operação, mostrando o resultado e saindo. """ import os print('ESCOLHA UMA DAS OPÇÕES A SEGUIR:') print('[1] SOMA') print('[2] SUBTRAÇÃO') print('[3] MULTIPLICAÇÃO') print('[4] DIVISÃO') operacao = int(input('\n\n\nDigite sua escolha: ')) num1 = int(input('digite um valor:')) num2 = int(input('digite outro valor:')) if operacao == 1: print(f'O resultado é {num1 + num2} .') if operacao == 2: print(f'O resultado é {num1 - num2} .') if operacao == 3: print(f'O resultado é {num1 * num2} .') if operacao == 4: print(f'O resultado é {num1 / num2} .') else: print('Escolha de operação inválida')
""" Escreva um programa que, dado o valor da venda, imprima a comissão que deverá ser paga ao vendedor. Para calcular a comissão, considere a tabela abaixo: VENDA MENSAL COMISSÃO Maior ou igual a R$100.000,00 R$700,00 + 16% das vendas Menor que R$100.000,00 e maior ou igual a R$80.000,00 R$650,00 + 14% das vendas Menor que R$80.000,00 e maior ou igual a R$60.000,00 R$600,00 + 14% das vendas Menor que R$60.000,00 e maior ou igual a R$40.000,00 R$550,00 + 14% das vendas Menor que R$40.000,00 e maior ou igual a R$20.000,00 R$500,00 + 14% das vendas Menor que R$20.000,00 R$400,00 + 14% das vendas """ venda = float(input('Digite o valor da venda(R$): ')) if venda >= 100.000: print(f'Valor da comissão: R${700 + (venda * 0.16):.2f}') elif 80.000 <= venda < 100.000: print(f'Valor da comissão: R${650 + (venda * 0.14):.2f}') elif 60.000 <= venda < 80.000: print(f'Valor da comissão: R${600 + (venda * 0.14):.2f}') elif 40.000 <= venda < 60.000: print(f'Valor da comissão: R${550 + (venda * 0.14):.2f}') elif 20.000 <= venda < 40.000: print(f'Valor da comissão: R${500 + (venda * 0.14):.2f}') else: print(f'Valor da comissão: R${400 + (venda * 0.14):.2f}')
""" Faça um programa que leia um número inteiro positivo N e imprima todos os numeros naturais de N até 0 em ordem decrescente. """ num = 60 for i in range(num, -1, -1): print(i)
""" Leia a temperatura em graus Fahrenheit e apresente-a em graus Celsius. A fórmula de conversão é: C = 5.0 * (F - 32.0) / 9.0, sendo C a temperatura em Celsius e F a temperatura em Fahrenheit . """ fahrenheit = float(input('digite a temperatura em graus Fahrenheit: ')) celsius = 5.0 * (fahrenheit - 32.0) / 9.0 print(f'a temperatura digitada, em Celsius é {celsius} graus')
#Faça a leitura de três valores e apresente como resultado a soma dos quadrados dos três valores obtidos. num1 = 12 num2 = 15 num3 = 18 resultado = (num1**2) + (num2**2) + (num3**2) print(resultado)
""" Faça um programa que leia um valor N inteiro e positivo, calcule e mostre o valor E, conforme a fórmula a seguir: E = 1+1/1! + 1/2! + 1/3! +...+1/n! """ def fatorial(num): n = num fat = 1 i = 2 while i <= n: fat = fat * i print(fat) i += 1 return fat print(0%2)
""" Leia um valor de área em hectares e apresente-o convertido em metros quadrados m². A fórmula de conversão é: M = H * 10000, sendo M a área em metros quadrados e H a área em hectares. """ hectares = float(input('digite um valor de área em hectares: ')) m2 = hectares * 10_000 print(f'o valor convertido em metros quadrados m² é igual a {m2:.2f} .')
# Leia um numero inteiro e imprima a soma do sucessor de seu triplo com o antecessor de seu dobro. num = int(input('digite um numero inteiro: ')) print(f'a soma do sucessor de seu tripo com o antecessor do seu dobro é igual a {(num*3+1)+(num*2-1)}')
class Parent(): def __init__(self, last_name, eye_color): print("Parent Constructor called") self.last_name=last_name self.eye_color=eye_color def show_info(self): print(self.last_name) print(self.eye_color) class Child(Parent): def __init__(self, last_name, eye_color, number_of_toys): print("Child contructor called") Parent.__init__(self, last_name, eye_color) self.number_of_toys=number_of_toys #billy_cyrus= Parent("Cyrus","blue") #print(billy_cyrus.last_name) miley_cyrus= Child("Cyrus", "green", 18) miley_cyrus.show_info()
class Jarra: def __init__(self,cap): self.capacidad=cap self.contenido=0 def llena(self): self.contenido=self.capacidad def vacia(self): self.contenido=0 def capacidad(self): return self.capacidad def contenido(self): return self.contenido def vaciaen(self,Jarra): if(Jarra.capacidad-Jarra.contenido>=self.capacidad): Jarra.contenido= self.contenido self.contenido=0 else: self.contenido=self.contenido-(Jarra.capacidad-Jarra.contenido) Jarra.contenido=Jarra.capacidad class JarraCristal(Jarra): def romperse(self): print 'La jarra se ha roto' #Main j=Jarra(7) j2=Jarra(5) j3= JarraCristal(5) print 'J3CAP: ' + str(j3.capacidad) print 'J3CONT: ' + str(j3.contenido) j.llena() j.vaciaen(j2) print 'J1: '+ str(j.contenido) print 'J2: '+ str(j2.contenido)
#leet code - decode string - 394 - https://leetcode.com/problems/decode-string/ #Time complexity -O(N) #space complexity-O(N) class Solution(object): def decodeString(self, s): """ :type s: str :rtype: str """ stack=[] currstr="" currnum="" for i in s: #case1 if i.isdigit(): currnum=currnum+i #case2: elif i=='[': stack.append((int(currnum),currstr)) currnum,currstr="","" #case3 elif i==']': n,prev=stack.pop() currstr=prev+n*currstr #case4 else: currstr=currstr+i return currstr
class Solution: def findMin(self, nums: List[int]) -> int: l, r = 0, len(nums) - 1 while l < r: mid = l + (r - l) // 2 if nums[mid] > nums[r]: l = mid + 1 else: r = mid # At this point, left and right converge to a single index (for minimum value) since # our if/else forces the bounds of left/right to shrink each iteration: # When left bound increases, it does not disqualify a value # that could be smaller than something else (we know nums[mid] > nums[right], # so nums[right] wins and we ignore mid and everything to the left of mid). # When right bound decreases, it also does not disqualify a # value that could be smaller than something else (we know nums[mid] <= nums[right], # so nums[mid] wins and we keep it for now). # So we shrink the left/right bounds to one value, # without ever disqualifying a possible minimum return nums[l]
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: lenA = self.calculate_len(headA) lenB = self.calculate_len(headB) while lenA != lenB: if lenA > lenB: headA = headA.next lenA -= 1 else: headB = headB.next lenB -= 1 while headA != headB: headA = headA.next headB = headB.next return headA def calculate_len(self, head): length = 0 while head is not None: length += 1 head = head.next return length
#multiple for to build comprehensive a = [(x,y) for x in range(5) for y in range(5) if (x+y) % 2 == 0] print(a) b = [(x,y) for x in range(5) for y in range(5) if(x+y) % 2 == 0 and x!=y] print(b)
number_list = [3, 41, 12, 9, 74, 15] count = 0 total = 0 for number in number_list: count += 1 total += number print(number) print("Count: ",count) print("Total: ",total)
# d = { # "Name": "Guido", # "Age": 56, # "BDFL": True # } # for a,b in d.items(): # print(a,b) # for a in d.keys(): # print(a) # for b in d.values(): # print(b) # #create a comprehesive list # my_list = [x**3 for x in range(1,11) if x % 2 != 0] # my_list = [x**3 for x in range(1,11) if x % 4 == 0] # print(my_list) squares = [x**2 for x in range(1,11)] a = filter(lambda x: x >= 30 and x <= 70,squares) print (a)
import pandas as pd df = pd.read_csv('glassdoor_jobs.csv') df.head() #cleaning things to do #salary parsing #company name text only #state field and #age of company #parsing of job description (python etc) #Salary parsing df['hourly'] = df['Salary Estimate'].apply(lambda x: 1 if 'per hour' in x.lower() else 0) df['employer_provided'] = df['Salary Estimate'].apply(lambda x: 1 if 'employer provided salary:' in x.lower() else 0) #1. Remove the rows which have -1 as salary value df = df[df['Salary Estimate'] != '-1'] #2. Salary Estimate Column remove the text - a. Can use Regex or lambda function to replace characters with blank values salary = df['Salary Estimate'].apply(lambda x: x.split('(')[0]) minus_kd = salary.apply(lambda x: x.replace('K' ,'').replace('$','')) #3. Clean salary data min_hr = minus_kd.apply(lambda x: x.lower().replace('per hour','').replace('employer provided salary:','')) #4.Extract higher and lower salary values and find average df['min_salary'] = min_hr.apply(lambda x: int(x.split('-')[0])) df['max_salary'] = min_hr.apply(lambda x: int(x.split('-')[1])) df['avg_salary'] = (df['min_salary']+df['max_salary'])/2 #5.Remove rating from end of the company name if exits else don't df['company_txt'] = df.apply(lambda x: x['Company Name'] if x['Rating']<0 else x['Company Name'][:-4],axis=1) #6. State Column df['State'] = df['Location'].apply(lambda x:x.split(',')[1]) counts = df['State'].value_counts() #jobs in the each state counts #7.find the count of jobs in headquarters df['same_state'] = df.apply(lambda x: 1 if x['Location'] == x['Headquarters'] else 0,axis=1) df #8.Age of Company df['age'] = df['Founded'].apply(lambda x: x if x<1 else 2020 - x) df #9.parsing of JD for finding python,aws etc df['python_ct']=df['Job Description'].apply(lambda x:1 if 'python' in x.lower() else 0) python_ct = df['python_ct'].value_counts() df['rstudio_ct']=df['Job Description'].apply(lambda x:1 if 'r-studio' in x.lower() or 'r studio' in x.lower() else 0) rstudio_ct = df['rstudio_ct'].value_counts() df['spark_ct']=df['Job Description'].apply(lambda x:1 if 'spark' in x.lower() else 0) spark_ct= df['spark_ct'].value_counts() df['aws_ct']=df['Job Description'].apply(lambda x:1 if 'aws' in x.lower() else 0) aws_ct= df['aws_ct'].value_counts() df['excel_ct']=df['Job Description'].apply(lambda x:1 if 'excel' in x.lower() else 0) excel_ct= df['excel_ct'].value_counts() #c= df.columns #10. Drop the 1st column df_final = df.drop(['Unnamed: 0'], axis=1) df_final df_final.to_csv('salary_cleaned_data.csv', index = False) #pd.read_csv('salary_cleaned_data.csv')
from sys import stdin class ComplexNumber: def __init__(self, real=0, imaginary=0): self.real = real self.imaginary = imaginary def __add__(self, another): return ComplexNumber(self.real + another.real, self.imaginary + another.imaginary) def __sub__(self, another): return ComplexNumber(self.real - another.real, self.imaginary - another.imaginary) def __mul__(self, another): return ComplexNumber( self.real * another.real - self.imaginary * another.imaginary, self.real * another.imaginary + self.imaginary * another.real) def __truediv__(self, another): sqr = another.sqr() tmp = self * ComplexNumber(another.real, -another.imaginary) return ComplexNumber(tmp.real / sqr, tmp.imaginary / sqr) def __str__(self): if self.imaginary == 0: return "%.2f" % self.real elif self.real == 0: return "%.2fi" % self.imaginary else: if self.imaginary > 0: return "%.2f + %.2fi" % (self.real, self.imaginary) else: return "%.2f - %.2fi" % (self.real, abs(self.imaginary)) def sqr(self): return (self.real ** 2) + (self.imaginary ** 2) pass for line in stdin.readlines(): print(eval(line.strip()))
ulang="y" while ulang=="y" or ulang =="Y": print("===========================") print(" Pembelian printer") print("===========================") u=1 u =input(" Masukkan Banyak Printer = ") n=int(u) harga = n * 660000 print(" Total Harga Pembelian Printer= Rp.",harga) ulang = input(" Ulang program? y/t = ") if ulang=="t" or ulang=="T": break
class Application(): def sum(self,n,m): return n+m def subtract(self,n,m): return n-m def multiply(self,n,m): return n*m def divide(self,n,m): return n/m def power(self,n,m): p=1 if m >=0: for i in range(m): p=p*n else: m*=-1 for i in range(m): p=p/n return p def calcval(self, c, v): if v == '+' or v == '-': return 0 + c * 3 if v == '*' or v == '/': return 1 + c * 3 if v == '^': return 2 + c * 3
print(input_shape) input_img = Input(shape=input_shape) network = Conv2D(32, kernel_size=(3, 3), activation='relu',input_shape=input_shape) (input_img) network = Conv2D(64, kernel_size=(3, 3), activation='relu') (network) network = Flatten() (network) network = Dense(512, activation='relu') (network) network = Dense(1, activation='linear') (network) model = Model(input_img, network)
from collections import MutableSequence class Node(object): """ A node that holds a value and possibly connects to a next node. """ def __init__(self, value, next_node=None): self.value = value self.next = next_node class LinkedList(MutableSequence): """ A list where items are linked to each other. """ def __init__(self, head=None): self.__head = head self.__length = 0 def append(self, value): self.insert(self.__length, value) def insert(self, index, value): if index == 0: self.__head = Node(value, next_node=self.__head) else: current_node = self.__get_node_at(index - 1) new_node = Node(value) if current_node.next is not None: new_node.next = current_node.next.next current_node.next = new_node self.__length += 1 def remove(self, value): current_node = self.__head previous = None while current_node is not None: if current_node.value == value: break previous = current_node current_node = current_node.next if previous == None: self.__head = current_node.next else: previous.next = current_node.next self.__length -= 1 def pop(self, index): popped_node = None if index == 0: popped_node = self.__head self.__head = self.__head.next else: current_node = self.__get_node_at(index - 1) popped_node = current_node.next current_node.next = current_node.next self.__length -= 1 return popped_node.value # ========================= # List interface # ========================= def reverse(self): previous = None current_node = self.__head while current_node is not None: next_node = current_node.next current_node.next = previous previous = current_node current_node = next_node self.__head = previous def sort(self, cmp=None, key=None, reverse=False): sorted_list = sorted(self, cmp=cmp, key=key, reverse=reverse) # Clear the linked list self.__clear() # Extend by adding the sorted list from earlier self.extend(sorted_list) # ========================= # Emulating container type # ========================= def __contains__(self, value): current_node = self.__head found = False while current_node is not None and not found: if current_node.value == value: found = True else: current_node = current_node.next return found def __len__(self): return self.__length def __iter__(self): current_node = self.__head while current_node is not None: yield current_node.value current_node = current_node.next def __getitem__(self, index): current_node = self.__get_node_at(index) return current_node.value def __setitem__(self, index, value): self.insert(index, value) self.pop(index + 1) def __delitem__(self, index): self.pop(index) def __str__(self): representation = "[" current_node = self.__head while current_node is not None: representation += "{}".format(current_node.value) current_node = current_node.next if current_node is not None: representation += ", " representation += "]" return representation # ========================= # Internal functions # ========================= def __get_node_at(self, index): if index > self.__length > 0 or (index < 0 and abs(index) > (self.__length + 1)): raise IndexError(index) current_node = self.__head # Support for negative indexes as indexes from end-to-start if index < 0: index = self.__length - abs(index) for _ in xrange(index): current_node = current_node.next return current_node def __clear(self): self.__head = None self.__length = 0
from day5_data import DATA as DATA # Faster to loop over entire data and mark pairs for deletion than # deleting them immediately when they are detected. def reduce(data): changed = True while changed: changed = False; for i in range(1, len(data)): if data[i] != data[i-1] and data[i].upper() == data[i-1].upper(): data[i] = "-" data[i-1] = "-" changed = True data = [i for i in data if i != "-"] return data def main(data): arr = [c for c in data] print "Before " + str(len(arr)) + " units, now " + str(len(reduce(arr))) + " units" if __name__ == "__main__": main(DATA)
from day1_data import DATA as DATA def main(data): freq = 0; hist = {} hist[freq] = True while True: for i in data: freq += i if freq in hist: print "Freq: " + str(freq) + " appeared twice" return hist[freq] = True if __name__ == "__main__": main(DATA)
import csv def read_data(): patches = [] with open('day3_data.txt') as csvfile: reader = csv.reader(csvfile, delimiter = " ") for row in reader: coord = row[2].split(',') x = int(coord[0]) y = int(coord[1].split(':')[0]) coord = row[3].split('x') w = int(coord[0]) h = int(coord[1]) patches.append([x,y,w,h]) return patches def max_size(patches): limits = [max(i[0] for i in patches), max(i[1] for i in patches), max(i[2] for i in patches), max(i[3] for i in patches)] return limits[0] + limits[2], limits[1] + limits[3] def fill_canvas(patches, canvas): for p in patches: for x in range(p[0], p[2] + p[0]): for y in range(p[1], p[3] + p[1]): canvas[y][x] += 1 return canvas def count_overlap(canvas): c = 0 for i in canvas: for j in i: if j > 1: c += 1 return c def main(): c = read_data() x_max, y_max = max_size(c) # Use a canvas that starts with 0,0 for simpler indexing even if x_max or y_max > 0 canvas = [] for unused in range(0, y_max): canvas.append([0 for unused in range(0, x_max)]) canvas = fill_canvas(c, canvas) print "Overlapping sq in: " + str(count_overlap(canvas)) if __name__ == "__main__": main()
def palindrome(str): split_str = list(str) print split_str my_dict = {} for i in range(0, len(split_str)): #print split_str[i] bool = False if split_str[i] in my_dict: my_dict[split_str[i]] = my_dict[split_str[i]]+1 else: my_dict[split_str[i]] = 1 print my_dict countone = 0 for j in my_dict: #print my_dict.get(j) if my_dict.get(j)%2 != 0: countone = countone+1 if countone != 1: return False return True print(palindrome('livci'))
import pandas as pd import numpy as np import sklearn from sklearn import linear_model from sklearn.utils import shuffle import matplotlib.pyplot as pyplot import pickle from matplotlib import style #read data and each data value is seperated by a comma(",") data = pd.read_csv("heart.csv",sep=",") """ Binary 0=No,Woman,Alive, 1=Yes,Men,Dead - age: age of the patient (years) - anaemia: decrease of red blood cells or hemoglobin (boolean) - high blood pressure: if the patient has hypertension (boolean) - creatinine phosphokinase (CPK): level of the CPK enzyme in the blood (mcg/L) - diabetes: if the patient has diabetes (boolean) - ejection fraction: percentage of blood leaving the heart at each contraction (percentage) - platelets: platelets in the blood (kiloplatelets/mL) - sex: woman or man (binary) - serum creatinine: level of serum creatinine in the blood (mg/dL) - serum sodium: level of serum sodium in the blood (mEq/L) - smoking: if the patient smokes or not (boolean) - time: follow-up period (days) - [target] death event: if the patient deceased during the follow-up period (boolean) """ #selected attributes from data data = data[["Death","high_blood_pressure","creatinine_phosphokinase","serum_sodium","time","ejection_fraction"]] #print data of selected columns first 5 rows print(data.head()) #predict if they wiill die or not before the follow up period prediction = "Death" #return new data frame that doesnt have Death #Attributes X=np.array(data.drop([prediction], 1)) #Labels Y=np.array(data[prediction]) x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X,Y,test_size = 0.1) bestData=0 #Run alogirthim 50 times, and choose the highest accuracy for _ in range(50): #0.1= split 10% of test data x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X,Y,test_size = 0.1) linear = linear_model.LinearRegression() linear.fit(x_train,y_train) accuracy=linear.score(x_test,y_test) if accuracy>bestData: bestData=accuracy #pickle file with open("grades.pickle","wb") as f: pickle.dump(linear,f) print("Best Accuracy:",bestData) pickle_in=open("grades.pickle","rb") linear = pickle.load(pickle_in) print("Coe: \n",linear.coef_) print("Int: \n", linear.intercept_) predictions = linear.predict(x_test) for x in range(len(predictions)): print(predictions[x],x_test[x],y_test[x]) #Xlabel b="time" style.use("ggplot") pyplot.scatter(data[b],data["Death"]) pyplot.xlabel(b) pyplot.ylabel("Death") pyplot.show()
file = open('input.txt') lines = file.read().splitlines() trees = 0 position = 3 for line in lines[1:]: if line[position] == '#': trees = trees + 1 position = (position + 3) % 31 print(trees)
def to_char_arrays(text, w): """sets the words from input string into one or more character arrays of length w :param text: input string :param w: maximum length of array :type text: str :type w: int :return list of character arrays :rtype list of str """ words = text.split() array_list = [] if words: char_arr = words[0] # assign first word else: char_arr = '' for word in words[1:]: # for remaining words temp = ' ' + word if len(char_arr + temp) <= w: # if second word fits char_arr += temp else: # add to new array array_list.append(char_arr) char_arr = word array_list.append(char_arr) return array_list
__author__="JimmyMo" __date__ ="$Aug 31, 2013 8:33:23 PM$" list = [123, "abc", 1.23] list.append('ni') p = list.pop(0) list.sort() print list; list.reverse() list.insert(0, 'aaa') print list.count('aaa') print list; print p; print range(len(list)) for i in list: print i for i in range(len(list)): print i print "------------------end of "+__name__+".py------------------"
"""Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input().""" input_list = input("Введите через пробел элементы списка: ") input_list = input_list.split(" ") for index in range(0, len(input_list)-2, 4): input_list[index], input_list[index+1] = input_list[index+1], input_list[index] print(input_list)
import pygame pygame.init() gameDisplay = pygame.display.set_mode((800,600)) #pygame.display.set_mode sets the game window size. #Arguments are passed in as a tuple pygame.display.set_caption("The Game Name") #pygame.display.set_caption sets the game display name #The name appears on the game display window clock = pygame.time.Clock() #pygame.time.Clock() defines the game clock #Times things in the game crashed = False while not crashed: for event in pygame.event.get(): #pygame.event.get() Checks for events(grabs events) #Mouse position, key strokes etc #Gets events per frame per second if event.type == pygame.QUIT: #pygame.QUIT identifies if player want to quit. #Quiting is by pressing the 'x' button on window crashed = True print(event) pygame.display.update() #Generally, all calculations happen in the background and after they are done they are displayed in a new frame #pygame.display.update() checks for all the events that have happened in the loop and updates the display frame clock.tick(60) pygame.quit() quit()
import math print("Input de radius of a circle: ", end="") r = float(input()) print("The area of a circle of radius", str(r), "is: ", math.pi*r**2)
s = input() left = int(s[:2]) right = int(s[2:]) ans = "NA" if 0 < left <13: if 0 < right < 13: ans = "AMBIGUOUS" else: ans = "MMYY" else : if 0 < right < 13: ans = "YYMM" print(ans)
n, a, b, c, d = map(int, input().split()) string = input() if "##" in string[a-1:c] or "##" in string[b-1:d]: print("No") elif c < d: print("Yes") else : if "..." in string[b-2:d+1]: print("Yes") else : print("No")
from collections import deque class vertex: def __init__(self, mark, val=None, firstEdge=None): self.mark = mark self.val = val self.firstEdge = firstEdge self.isVisited = False def __str__(self): try: int(self.mark) return 'v' + str(self.mark) except: return str(self.mark) def __repr__(self): li = [] arc = self.firstEdge while arc != None: li.append(arc) arc = arc.outNextEdge return str(self) + ' to:' + str([str(i.inArrow) for i in li]) class edge: def __init__(self, outArrow, inArrow, outNextEdge=None, inNextEdge=None, weight=1): self.weight = weight self.inNextEdge = inNextEdge self.outNextEdge = outNextEdge self.outArrow = outArrow self.inArrow = inArrow self.isVisited = False def __str__(self): return '--' + str(self.weight) + '-->' def __repr__(self): return str(self) class graph: def __init__(self): self.vertexs = {} self.edges = {} def __getitem__(self, i): return self.vertexs[i] def __setitem__(self, i, x): self.vertexs[i] = x def __iter__(self): return iter(self.vertexs.values()) def __bool__(self): return len(self.vertexs) != 0 def addVertex(self, i): if not (i, vertex) and i not in self.vertexs: self.vertexs[i] = vertex(i) if isinstance(i, vertex) and i not in self.vertexs: self.vertexs[i.mark] = i def isConnected(self, v, u): v = self.__getVertex(v) u = self.__getVertex(u) arc = v.firstEdge while arc != None: if arc.inArrow == u: return True arc = arc.inNextEdge return False def __getVertex(self, v): if not isinstance(v, vertex): if v not in self.vertexs: self.vertexs[v] = vertex(v) return self.vertexs[v] return v def addEdge(self, v, u, weight=1): v = self.__getVertex(v) u = self.__getVertex(u) arc = v.firstEdge while arc != None: #examine that if v,u have been already connected if arc.inArrow == u: return arc = arc.outNextEdge newEdge = edge(v, u, v.firstEdge, u.firstEdge, weight) self.edges[(v.mark, u.mark)] = newEdge v.firstEdge = newEdge def delEdge(self, v, u): if not isinstance(v, vertex): v = self.vertexs[v] if not isinstance(u, vertex): u = self.vertexs[u] self._unrelated(v, u) del self.edges[(v.mark, u.mark)] def _unrelated(self, v, u): if v.firstEdge == None: return if v.firstEdge.inArrow == u: v.firstEdge = v.firstEdge.outNextEdge else: arc = v.firstEdge while arc.outNextEdge != None: if arc.outNextEdge.inArrow == u: arc.outNextEdge = arc.outNextEdge.outNextEdge break def reVisit(self): for i in self.vertexs: self.vertexs[i].isVisited = False for i in self.edges: self.edges[i].isVisited = False def __str__(self): arcs = list(self.edges.keys()) arcs = [ str(i[0]) + '--->' + str(i[1]) + ' weight:' + str( self.edges[i].weight) for i in arcs ] s = '\n'.join(arcs) return s def __repr__(self): return str(self) def notIn(self, v): if (isinstance(v, vertex) and v.mark not in self.vertexs) or v not in self.vertexs: return True return False def minPath(self, v, u): '''dijstra''' self.reVisit() if self.notIn(v) or self.notIn(u): return [], 0 v = self.__getVertex(v) u = self.__getVertex(u) if v.firstEdge == None: return [], 0 q = deque([v]) last = {i: None for i in self} distance = {i: 1 << 30 for i in self} distance[v] = 0 while len(q) != 0: cur = q.popleft() cur.isVisited = True arc = cur.firstEdge while arc != None: to = arc.inArrow if not to.isVisited: q.append(to) if distance[to] > distance[cur] + arc.weight: last[to] = cur distance[to] = distance[cur] + arc.weight arc = arc.outNextEdge cur = u path = [] while cur != None and cur != v: path.append(cur.mark) cur = last[cur] if cur == None: return [], 0 path.append(v.mark) return path[::-1], distance[u] def hasVertex(self, mark): return mark in self.vertexs def display(self): print('vertexs') for i in self.vertexs: print(self.vertexs[i].__repr__()) print('edges') for i in self.edges: arc = self.edges[i] print(str(arc.outArrow) + str(arc) + str(arc.inArrow))
#!/usr/bin/env python # -*-coding:UTF-8-*- #多态:不同对象对同一方法响应不同的行动 #斐波那契数列/黄金分割数列 def num_1 (): a,b = 0,1 while b < 70: print(b,end=' ') #print(a) a,b = b,a+b #num_1() # def fad(n): # if n==1 or n==2: # return 1 # else: # return fad(n-1)+fad(n-2) # result = fad(10) # if result != -1: # print(result) #变量属性 def number (): a,b,c,d,=20,5.5,True,4+3j print(type(a),type(b),type(c),type(d)) #number() def string (): s = "Yes,he doesn't" print(s*2,type(s),len(s)) #string() def List1 (): a = [1,2,3,4,5] b = [6,7,8,9] c = [9,8,2,6,5] d = c[:] f = [9,5,4,6,2,45,6] print(list(zip(f,c))) # 排序 d.sort() print('d=',d) c.sort(reverse=True) print('c1=',c) # 翻转 c.reverse() print('c=',c) #添加 a.append('555') b.extend(['sss','ddd']) a.insert(1,'s') #删除 a.remove('555') del b[4] s = b.pop(4) #打印 print('a=',a) print('b=',b) print('a+b',a+b) #修改第一位数字赋值9 a[0] = 9 print(a) a[2:5] = [] print('a=',a) #List1() #集合 def sets(): a = {'tom','jion','tom','jack'} print(a) print('tom' in a) x = {'a','c','s','a','d','x','s'} y = {'c','s','k','r'} print(x,y) print('差集:',x-y) print('并集:',x|y) print('交集:',x&y) print('不同时存在:',x^y) #sets() #集合自动去重,可以用集合来去重,不可变集合--frozenset() def set_1(): s1 = {1,2,3,4,5,8,6,5,2,1,3,5,8,9,4} print(s1) s2= [1,2,3,4,5,8,6,5,2,1,3,5,8,9,4] s3 = list(set(s2)) print(s3) #set_1() #字典 def dic(): dic = {} tel = {'jack':1557,'tom':1320,'rose':1886} print(tel) tel['may'] = 4555 print(tel) tel_1 = {'jack':1888} print(tel.update(tel_1)) print(list(tel.keys())) x = {z: z**2 for z in (2,4,6,8,10)} print ((x)) #dic() #clear--删除字典 copy--拷贝 fromkeys--键值 pop--栈弹出 get--宽松访问 update--更新 #keys()--返回字典键的应用 values()-- items()-- setdefault--不存在便添加 def counter (): sum = 0 counter = 1 while counter <=100: sum = sum + counter counter = counter +1 print("sum of 1 until 100:%d"%sum) #counter() #print( list(range(0,50,3))) #print([str(round(355/113, i)) for i in range(1, 17)]) #print(355/113) #遍历 def bianli (): A = {'tom':173,'jie':160,'h':155} for k,s in A.items(): print(k,s) for i,j in enumerate(A): print(i,j) #反向遍历 for i in reversed(range(1,10,2)): print(i) #要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值 basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for f in sorted(set(basket)): print(f) #bianli() #平方立方表 def lifang (): for x in range (1,11): print(repr(x).rjust(2),repr(x*x).rjust(3),end=' ') print(repr(x*x*x).rjust(4)) print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x)) #lifang() #递归调用自身 def recursion(n): print(n) recursion(n+1) #recursion(1) #二分查找 date = list(range(200)) def search(n,low,high,d): mid = int((low+high)/2) if low ==high: print('not find') return if d[mid] > n: print("go left:",low,high,d[mid]) search(n,low,mid,d) elif d[mid] < n: print("go right:",low,high,d[mid]) search(n,mid+1,high,d) else: print('find it:',d[mid]) #search(25,0,len(date),date) import numpy as np def matrix2(): a = np.array([ [1,2,1], [3,8,1], [0,4,1] ]) print(a[:,1]) #所有行,列索引为一 print(a[:,0:2]) #所有行,列索引为0,1 print(a[1:3,:]) #所有列,行是行的所有1,2 print(a[1:3,0:2]) #行索引为1,2,列索引为0,1 print(a==1) b = (a[:,1]>=3) #在所有行,列为2,大于等于3 print(b) print(a[b,:]) s = (a[0:1,:]) print(s.sum()) #axis=1,计算行值,以列展示 print(a.sum(axis=1)) #axis=0,计算列值,结果以行展开 print(a.sum(axis=0)) """ sum():计算数组元素的和;对于矩阵计算的结果为一个一维数组,需要指定行或者列; mean():计算数组元素的平均值;对于举证计算的结果为一个一位数组,需要指定行或者列; max():计算数组元素的最大值;对于矩阵计算结果为一个一维数组,需要指定行或者列。 用于这些统计方法的数值类型必须是int或者float。 """ #matrix2() import time import datetime def datetext(): #24小时制 a = time.strftime("%Y/%m/%d %A %H:%M:%S") print(a) #12小时制 s = time.strftime('%I:%M:%S') print(s) d = datetime.datetime.now() print('当前时间:%s'%d.isoformat()) #datetext() """ %a 星期几的简写 %A 星期几的全称 %b 月分的简写 %B 月份的全称 %c 标准的日期的时间串 %C 年份的后两位数字 %d 十进制表示的每月的第几天 %D 月/天/年 %e 在两字符域中,十进制表示的每月的第几天 %F 年-月-日 %g 年份的后两位数字,使用基于周的年 %G 年分,使用基于周的年 %h 简写的月份名 %H 24小时制的小时 %I 12小时制的小时 %j 十进制表示的每年的第几天 %m 十进制表示的月份 %M 十时制表示的分钟数 %n 新行符 %p 本地的AM或PM的等价显示 %r 12小时的时间 %R 显示小时和分钟:hh:mm %S 十进制的秒数 %t 水平制表符 %T 显示时分秒:hh:mm:ss %u 每周的第几天,星期一为第一天 (值从0到6,星期一为0) %U 第年的第几周,把星期日做为第一天(值从0到53) %V 每年的第几周,使用基于周的年 %w 十进制表示的星期几(值从0到6,星期天为0) %W 每年的第几周,把星期一做为第一天(值从0到53) %x 标准的日期串 %X 标准的时间串 %y 不带世纪的十进制年份(值从0到99) %Y 带世纪部分的十制年份 %z,%Z 时区名称,如果不能得到时区名称则返回空字符。 %% 百分号 """ def s2q(s:int)->int: input_s = [] # 申请一个入栈 output_s = [] # 申请一个出栈 res = [] for c in s: input_s.append(c) # 压入栈 while input_s: # 代码整洁之道 output_s.append(input_s.pop()) # 不为空就一直往外弹 while output_s: #res = [] # 如果每次都写在里面泽每次循环时都申请一个[] res.append(output_s.pop()) #print(res) #print(id(res)) # 打印内存地址可以发现规律 #return res, id(res) # 默认只会输出第一次的循环,优先级的概念 return res #print(s2q("asdhfkh")) from wordcloud import WordCloud import matplotlib.pyplot as plt #词云 #读取文件,文档位于此python同以及目录下 def word(): f = open(u'text.txt','r',encoding='utf-8').read() f = f.lower() wordcloud = WordCloud( background_color="white", #设置背景为白色 width=800, #设置图片的宽度 height=660, #设置图片的高度 margin=2 #设置图片的边缘 ).generate(f) plt.imshow(wordcloud) # 绘制图片 plt.axis("off") #消除坐标轴 plt.show() # 展示图片 wordcloud.to_file('text.png') # 保存图片 #word() #条件表达式(三元操作符) def small_text(): x,y = 4,5 small = x if x < y else y print(small) #这两种用法相等 if x > y: small = x else: small = y print(small) # 语法: x if 条件 else y #small_text() ''' assert 3<4 断言 for x in range(): range([strat,] stop,[step=1]) 开始 结束 步数 ''' def continue_text(): for i in range(1,10): if i%2 != 0: print(i) continue i +=2 print(i) #continue_text() #数据过滤,返回True #print(list(filter(None,[1,0,False,True]))) def odd_1(): def odd(x): return x % 2 temp = range(10) show = filter(odd,temp) print(list(show)) #print(list(filter(lambda x :x % 2,range(10)))) #odd_1() #print(list(map(lambda x : x * 2,range(10)))) #阶乘 # def factorial(n): # result = n # for i in range(1,n): # result *=i # return result # num = int(input('阶乘数字:')) # re = factorial(num) # print('%d阶乘是:%d'%(num,re)) #递归 def factor(): def factorial(n): if n ==1: return 1 else: return n * factorial(n-1) num = int(input('整数:')) resu = factorial(num) print(resu) #factor() #阶乘 def jiecheng(): num = int(input('阶乘整数:')) for i in range(1,num): num *= i print('结果:',num) #jiecheng() #汉诺塔解法 def hannuo(): def hanoi(n,x,y,z): if n ==1: print(x,'-->',z) else: hanoi(n-1,x,z,y) print(x,'-->',z) hanoi(n-1,y,z,x) n = int(input('层数')) hanoi(n,'x','y','z') #hannuo() # import os # import time # a = time.localtime(os.path.getatime("C:\Program Files\Adobe\Adobe Premiere Pro CC 2017")) # print(a) # try: # file_name = input('>') # with open(file_name+'.txt') as f: # for i in f: # print(i) # except OSError as a: # print(str(a)) # exit(-1) #用1234四个数组成的所有不重复的三位数有多少个 def num_2(): a = 0 for i in range(1,5): for j in range(1,5): for k in range(1,5): if i != j and i !=k and j != k: a +=1 print(str(i) + str(j) + str(k),end=' ') print() print('共有'+str(a)+'个') #num_2() #求两个数的最小公倍数和最大公约数 def gongyueshu(): a,b = int(input('输入一个数字:')),int(input('输入第二个数字:')) for i in range(a,0,-1): if a%i==0 and b%i==0: print('最大公约数:'+str(i),'最小公倍数:'+str(a*b//i)) break #gongyueshu() #奇偶分离,出栈 def num_4(): num = [16,448,54,23,56,154,979,1184] num.append(51) # 末尾添加 num.sort()#排序 print(num) num_1 = [] num_2 = [] while len(num)>0: nums = num.pop() if(nums %2 == 0): num_1.append(nums) else: num_2.append(nums) print(num_1) print(num_2) # num_4() #已知x为非空列表,执行y=x[:]之后,id(x[0])==id(y[0])的值为多少 # x=[5] # y = x[:] # print(id(x[0]==id(y[0]))) # # rq = __import__('requests') # from bs4 import BeautifulSoup # url = 'https://scrapy-chs.readthedocs.io/zh_CN/0.24/topics/exporters.html' # hea = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0'} # html = rq.get(url=url,headers=hea) # html.encoding='utf-8' # print(str(html.text)) r = __import__('random') class Fish: def __init__(self): self.x = r.randint(0,10) self.y = r.randint(0,10) def move(self): self.x -=1 self.y -=2 print('位置:',self.x,self.y) class Glodfish(Fish): pass class Carp(Fish): pass class Salomn(Fish): pass class Shark(Fish): def __init__(self): super().__init__() self.hungry = True def eat(self): if self.hungry: print('eat') self.hungry=False else: print('no') # a =Fish() # a.move() # a.move() # b = Shark() # b.eat() # b.eat() # c = Salomn() # c.move() # c.move() pass import datetime def dayofyear(): year = input("请输入年份: ") month = input("请输入月份: ") day = input("请输入天: ") date1 = datetime.date(year=int(year),month=int(month),day=int(day)) date2 = datetime.date(year=int(year),month=1,day=1) return (date1-date2).days+1 #print(dayofyear()) # from sys import getrefcount # s = getrefcount('aa') # print(s) from time import time, localtime, sleep class Clock(object): """数字时钟""" def __init__(self, hour=0, minute=0, second=0): self._hour = hour self._minute = minute self._second = second @classmethod def now(cls): ctime = localtime(time()) return cls(ctime.tm_hour, ctime.tm_min, ctime.tm_sec) def run(self): """走字""" self._second += 1 if self._second == 60: self._second = 0 self._minute += 1 if self._minute == 60: self._minute = 0 self._hour += 1 if self._hour == 24: self._hour = 0 def show(self): """显示时间""" return '%02d:%02d:%02d' % \ (self._hour, self._minute, self._second) def main(): # 通过类方法创建对象并获取系统时间 clock = Clock.now() while True: print(clock.show()) sleep(1) clock.run() # if __name__ == '__main__': # main() class Person(object): """人""" def __init__(self, name, age): self._name = name self._age = age @property def name(self): return self._name @property def age(self): return self._age @age.setter def age(self, age): self._age = age def play(self): print('%s正在愉快的玩耍.' % self._name) def watch_av(self): if self._age >= 18: print('%s正在观看爱情动作片.' % self._name) else: print('%s只能观看《熊出没》.' % self._name) class Student(Person): """学生""" def __init__(self, name, age, grade): super().__init__(name, age) self._grade = grade @property def grade(self): return self._grade @grade.setter def grade(self, grade): self._grade = grade def study(self, course): print('%s的%s正在学习%s.' % (self._grade, self._name, course)) class Teacher(Person): """老师""" def __init__(self, name, age, title): super().__init__(name, age) self._title = title @property def title(self): return self._title @title.setter def title(self, title): self._title = title def teach(self, course): print('%s%s正在讲%s.' % (self._name, self._title, course)) def main(): stu = Student('王大锤', 15, '初三') stu.study('数学') stu.watch_av() t = Teacher('骆昊', 38, '老叫兽') t.teach('Python程序设计') t.watch_av() # if __name__ == '__main__': # main() from abc import ABCMeta, abstractmethod class Pet(object, metaclass=ABCMeta): """宠物""" def __init__(self, nickname): self._nickname = nickname @abstractmethod def make_voice(self): """发出声音""" pass class Dog(Pet): """狗""" def make_voice(self): print('%s: 汪汪汪...' % self._nickname) class Cat(Pet): """猫""" def make_voice(self): print('%s: 喵...喵...' % self._nickname) def main(): pets = [Dog('旺财'), Cat('凯蒂'), Dog('大黄')] for pet in pets: pet.make_voice() # if __name__ == '__main__': # main() #十大排序算法: #1.冒泡排序: list_1 = [1,9,84,65,12,48,65,15,35,45,87,16,49,156,45,165] #print(sorted(list_1)) def bubbleSort(arr): for i in range(1, len(arr)): for j in range(0, len(arr)-i): if arr[j] > arr[j+1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr #2.选择排序: def selectionSort(arr): for i in range(len(arr) - 1): # 记录最小数的索引 minIndex = i for j in range(i + 1, len(arr)): if arr[j] < arr[minIndex]: minIndex = j # i 不是最小数时,将 i 和最小数进行交换 if i != minIndex: arr[i], arr[minIndex] = arr[minIndex], arr[i] return arr #3插入排序: def insertionSort(arr): for i in range(len(arr)): preIndex = i-1 current = arr[i] while preIndex >= 0 and arr[preIndex] > current: arr[preIndex+1] = arr[preIndex] preIndex-=1 arr[preIndex+1] = current return arr #4希尔排序: def shellSort(arr): import math gap=1 while(gap < len(arr)/3): gap = gap*3+1 while gap > 0: for i in range(gap,len(arr)): temp = arr[i] j = i-gap while j >=0 and arr[j] > temp: arr[j+gap]=arr[j] j-=gap arr[j+gap] = temp gap = math.floor(gap/3) return arr #5归并排序: def mergeSort(arr): import math if(len(arr)<2): return arr middle = math.floor(len(arr)/2) left, right = arr[0:middle], arr[middle:] return merge(mergeSort(left), mergeSort(right)) def merge(left,right): result = [] while left and right: if left[0] <= right[0]: result.append(left.pop(0)); else: result.append(right.pop(0)); while left: result.append(left.pop(0)); while right: result.append(right.pop(0)); return result #6快速排序: def quickSort(arr, left=None, right=None): left = 0 if not isinstance(left,(int, float)) else left right = len(arr)-1 if not isinstance(right,(int, float)) else right if left < right: partitionIndex = partition(arr, left, right) quickSort(arr, left, partitionIndex-1) quickSort(arr, partitionIndex+1, right) return arr def partition(arr, left, right): pivot = left index = pivot+1 i = index while i <= right: if arr[i] < arr[pivot]: swap(arr, i, index) index+=1 i+=1 swap(arr,pivot,index-1) return index-1 def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] #7堆排序: def buildMaxHeap(arr): import math for i in range(math.floor(len(arr)/2),-1,-1): heapify(arr,i) def heapify(arr, i): left = 2*i+1 right = 2*i+2 largest = i if left < arrLen and arr[left] > arr[largest]: largest = left if right < arrLen and arr[right] > arr[largest]: largest = right if largest != i: swap(arr, i, largest) heapify(arr, largest) def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] def heapSort(arr): global arrLen arrLen = len(arr) buildMaxHeap(arr) for i in range(len(arr)-1,0,-1): swap(arr,0,i) arrLen -=1 heapify(arr, 0) return arr #8计数排序: def countingSort(arr, maxValue): bucketLen = maxValue+1 bucket = [0]*bucketLen sortedIndex =0 arrLen = len(arr) for i in range(arrLen): if not bucket[arr[i]]: bucket[arr[i]]=0 bucket[arr[i]]+=1 for j in range(bucketLen): while bucket[j]>0: arr[sortedIndex] = j sortedIndex+=1 bucket[j]-=1 return arr #将数组中的元素都向前移一个位置 def ahead_one(): a = [i for i in range(10)] b = a.pop(0) a.append(b) return a # if __name__ =="__main__": # print(ahead_one()) import random def make_score(num): score = [random.randint(0,100) for i in range(num)] return score def less_average(score): num = len(score) sum_score = sum(score) ave_num = sum_score / num less_ave = [i for i in score if i < ave_num] return len(less_ave) # if __name__=="__main__": # score = make_score(40) # print ("the number of less average is:",less_average(score)) # print ("the every socre is[from big to small]:",sorted(score,reverse=True)) #print(模块.__doc__)查看模块简介 #print(random.__doc__) #dir(模块) 查看模块全部函数 #print(dir(random)) #print(模块.__all__)查看可调用用函数 #print(random.__all__) #from 模块 import * 只会导入可用模块 #模块.__file__ 查看源代码位置 #print(random.__file__) class people: name ='' age = 0 __weight = 0 def __init__(self,n,a,w): self.name = n self.age = a self.__weight = w def speak(self): print("%s 说:我%d岁," %(self.name,self.age)) class student(people): grade ='' def __init__(self,n,a,w,g): people.__init__(self,n,a,w) self.grade = g def speak(self): print("%s 说:我%d岁,在读%d年级"%(self.name,self.age,self.grade)) class speaker(): topic = '' name = '' def __init__(self,n,t): self.name = n self.topic = t def speak(self): print("我是%s,是一个演说家,我想说的主题是%s"%(self.name,self.topic)) class sample(speaker,student): a = "" def __init__(self,n,a,w,g,t): student.__init__(self,n,a,w,g) speaker.__init__(self,n,t) # p = people('tom', 10, 30) # p.speak() # s = student('jin',10,60,3,) # s.speak() # test = sample('tim',25,80,4,"python") # test.speak()
import collections class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # 树其实相当于对列表的一个扩充 import collections class Node(object): def __init__(self, item): self.item = item # 不同于链表的是,连接区域不同,二叉树有左右两个子树的连接区域 self.left = None self.right = None class Tree(object): def __init__(self): self.root = None def add(self, item): # 不考虑头插和任意位置插,往完全二叉树努力,在最后位置插入新增加的数据 # 广度优先遍历,层次优先遍历, node = Node(item) if self.root is None: self.root = node return # 使用队列来解决问题,队列不为空 queue = [self.root] while queue: # 首先取出这个节点 cur_node = queue.pop(0) if cur_node.left is None: cur_node.left = node return else: queue.append(cur_node.left) if cur_node.right is None: cur_node.right = node return else: queue.append(cur_node.right) def breadth_travel(self): # 广度遍历,一层一层的搜索 if self.root is None: return queue = [self.root] while queue: cur_node = queue.pop(0) print(cur_node.item, end=" ") if cur_node.left is not None: queue.append(cur_node.left) if cur_node.right is not None: queue.append(cur_node.right) def preorder(self, node): # 递归实现先序遍历,把每断个子树都当做一棵树来判,这个时候的根节点是在变化的 # 这个也就是递归的终止条件 if node is None: return print(node.item, end=" ") self.preorder(node.left) self.preorder(node.right) def ineorder(self, node): # 递归实现中序遍历,把每个子树都当做一棵树来判断, # 都是一棵树,然后打印的都是根节点 # 这个时候的根节点是在变化的 # 这个也就是递归的终止条件 if node is None: return self.ineorder(node.left) print(node.item, end=" ") self.ineorder(node.right) def postorder(self, node): # 递归实现后序遍历,把每个子树都当做一棵树来判断, # 都是一棵树,然后打印的都是根节点 # 这个时候的根节点是在变化的 # 这个也就是递归的终止条件 if node is None: return self.postorder(node.left) self.postorder(node.right) print(node.item, end=" ") def maxDepth(self, root): if not root: return 0 nleft = self.maxDepth(root.left) nright = self.maxDepth(root.right) return nleft + 1 if nleft > nright else nright + 1 def maxDepth2(self, root): if not root: return 0 queue = collections.deque([root]) depth = 0 while queue: n = len(queue) for i in range(n): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) depth += 1 return depth if __name__ == "__main__": tree = Tree() tree.add(0) tree.add(1) tree.add(2) tree.add(3) tree.add(4) tree.add(5) tree.add(6) tree.add(7) tree.add(8) tree.add(9) tree.breadth_travel() print(" ") tree.preorder(tree.root) print(" ") tree.ineorder(tree.root) print(" ") tree.postorder(tree.root) print(" ") result = tree.maxDepth2(tree.root) print(result) # 学习一下广度优先搜索 #
from Linked_list.SingleLinkList import SingleNode, SingleLinkList class Solution: # 反转链表 def reverseList1(self, head): if head is None: return None pPre = None while head != None: pNext = head.next # 切换head的下一个节点,重新指向前一个元素, pre,head 分别向后移 head.next = pPre pPre = head head = pNext # 至于为什么返回的是pPre,因为pPrey一直继承的是head的值,循环迭代终止也在head return pPre def reverseList(self, head): # 这部分不对,要调整递归条件,head 指向倒数第二个节点 # head 指向空或者只有一个元素时,就直接返回 # newhead 则指向对 head的下一个节点调用的递归函数的头节点,此时,newhead 指向最后一个节点 # 然后 head的下一个节点的next指向head本身,相当于head节点移动到末尾的动作, if head is None or head.next is None: return head newHead = self.reverseList(head.next) # 这个问题没有解决是为什么,没有理解这个问题最小的情况是啥,没有考虑只有一个元素的情况 # 从而这个递归条件就没有设置正确 # 最小问题的解是什么,就是反转后的头节点返回,同时,直接解决子问题, # 回溯法,把head节点移动到末尾,同时最后一个节点为空 head.next.next = head head.next = None return newHead # 递归的解决,有两个部分 # 第一个部分,就是对于最基本的情况,也就是问题最小的那种情况,他的解是什么 # 头部节点后面跟着一个小的短的链表,走早最底的情况,就是链表的头部head为空,也就是整个链表为空 # 这个也相当于是递归的条件 # 接下来就是第二个部分,把原问题转换成更小的问题的一个过程 # 这个头结点后面跟的应该是那个链表中所有的值为val的节点删除后的剩余节点,本来,将问题规模转换成更小的 # 的问题的时候,就是将链表看成一个头结点后面挂着一个链表,一个头结点后面挂接了一个更短更小的链表, # 如果此时这个头结点就是要删的值,那就不要头结点了,直接传回已经删除节点的链表,否则,将头节点和链表连上,传回 def travel(self, head): # 遍历链表 cur = head while (cur != None): print(cur.item, end=' ') cur = cur.next print("\n") if __name__ == "__main__": h = Solution() li = SingleLinkList() # print(li.is_empty()) # print(li.length()) i = 0 while i < 5: li.append(i + 1) i += 1 li.travel() result = h.reverseList(li._head) h.travel(result) # print(result.item)
def merge_sort(alist): n = len(alist) if n <= 1: return alist mid = n//2 # left采用归并排序后形成的有序的新的列表 left_li = merge_sort(alist[:mid]) # right 采用归并排序后形成的有序的新的列表 right_li = merge_sort(alist[mid:]) # 将两个有序的子序列合并成一个新的整体 # merge(right,left) left_pointer, right_pointer = 0, 0 result = [] while left_pointer < len(left_li) and right_pointer < len(right_li): if left_li[left_pointer] < right_li[right_pointer]: result.append(left_li[left_pointer]) left_pointer += 1 else: result.append(right_li[right_pointer]) right_pointer += 1 # 退出循环的时候,就是有一边的序列已经为空,则将剩余的序列复制过来 result += left_li[left_pointer:] result += right_li[right_pointer:] return result if __name__ == "__main__": li = [23, 2, 56, 7, 2, 4, 5, 7, 889, 432, 234] print(li) print(merge_sort(li))
class SingleNode(object): """单链表的节点""" def __init__(self, item): # item存放数据元素 self.item = item # next 存放下一个节点的标识 self.next = None class SingleHasCycleLinkList(): # 对象属性 def __init__(self, node=None): # 可以设置默认参数 self._head = node if node: # 判断如果不是空的,就将自己给自己挂上去 node.next = node def is_empty(self): # 判断链表是否为空 return self._head is None def length(self): # 链表的长度 cur = self._head count = 0 while (cur != None): count += 1 cur = cur.next return count def add(self, item): # 在链表头部插入节点 node = SingleNode(item) node.next = self._head self._head = node def append(self, item): # 在链表尾部插入节点 # 直接传入数据,用户不需要关心节点信息 node = SingleNode(item) if self.is_empty(): # 就将链表的__head属性指向node self._head = node else: cur = self._head while (cur.next != None): cur = cur.next cur.next = node def travel(self): # 遍历链表 cur = self._head while (cur != None): print(cur.item, end=' ') cur = cur.next print("\n") def get(self, index): """ Get the value of the index-th node in the linked list. If the index is invalid, return -1. 找到对应索引的节点值 """ if index < 0 or index >= self.length(): return False if self.is_empty(): return False cur = self._head i = 0 while (i < index): i += 1 cur = cur.next return cur # 这个添加好像不合理,因为我传的参的是新值,重新形成一个新节点 def appendCycleNode(self, item, index): node = SingleNode(item) if self.is_empty(): # 就将链表的__head属性指向node self._head = node node.next = node else: cur = self._head while (cur.next != None): cur = cur.next cur.next = node pointnode = self.get(index) node.next = pointnode # 此为判断 def hasCycle(self): if self.is_empty() or self._head.next == None: return False slow = self._head fast = slow.next while fast != None and fast.next != None: if fast == slow: return True slow = slow.next if fast.next: fast = fast.next.next return False # 在链表存在环的情况下找到两者相遇的节点 # 快慢指针出发点不一致,先到达不同的位置,然后,两个同时出发,会到达环中任意一个节点 def MeetingNode1(self): if self.is_empty() or self._head.next == None: return None slow = self._head fast = slow.next while fast != None and fast.next != None: if fast == slow: return fast slow = slow.next if fast.next: fast = fast.next.next return None # 快慢指针同时从头结点出发 def MeetingNode2(self): if self.is_empty() or self._head.next == None: return None slow = self._head fast = self._head while fast != None and fast.next != None: slow = slow.next if fast.next: fast = fast.next.next if fast == slow: return fast return None # 关于找到环中节点的个数,所以要要求的相遇节点并不唯一,可以是环中的任意一个节点 def getCycleNode(self): if self.MeetingNode2() is None: return meetingNode = self.MeetingNode2() cur = meetingNode count = 1 while cur.next != meetingNode: cur = cur.next count += 1 return count # 关于找到环的第一个节点,从头结点到环节点和相遇节点到换节点的距离相同 def detectCycle(self): if self.MeetingNode2() is None: return None meetingNode = self.MeetingNode2() slow = self._head fast = meetingNode while slow != fast: slow = slow.next fast = fast.next return fast # fast = meetingNode # while slow != meetingNode: # slow = slow.next # meetingNode = meetingNode.next # return meetingNode def detectCycle2(self): if self.getCycleNode() is None: return p1 = self._head i = 0 while i < self.getCycleNode(): p1 = p1.next i += 1 p2 = self._head while p1 != p2: p1 = p1.next p2 = p2.next return p1 if __name__ == "__main__": li = SingleHasCycleLinkList() li.append(23) li.append(34) li.append(69) li.append(67) li.travel() li.appendCycleNode(89, 1) arr1 = li.MeetingNode2() # print(arr1.item) # li.add(45) # li.travel() arr = li.detectCycle2() print(arr.item) # print(li.getCycleNode()) # # 这部分测试通过 # li.append(3) # li.append(2) # li.append(0) # li.append(-4) # # li.append(5) # # # li.append(6) # li.travel() # # li.appendCycleNode(6, 2) # arr1 = li.MeetingNode2() # print(arr1) # arr = li.detectCycle() # print(arr.item)
class Solution(): def isIsomorphic(self,str,t): if s.strip()=='' or t.strip()=='': return False dict1 = {} dict2 ={} for i in range(len(str)): if (str[i] in dict1 and dict1[str[i]] != t[i]) or t[i] in dict2 and dict2[t[i]] != str[i]: return False dict1[str[i]] = t[i] dict2[t[i]] = str[i] return True if __name__ =='__main__': h = Solution() s= 'foo' t= 'bar' print(h.isIsomorphic(s,t))
class Node(object): """多层双向链表的节点""" def __init__(self, item): # item存放数据元素 self.item = item self.next = None self.prev = None self.child = None class Solution: def flatten(self, head: 'Node') -> 'Node': pre = None self.recursive(head, pre) return head def recursive(self,head, pre): if head is None: return child = head.child next1 = head.next if pre: pre.next = head head.prev = pre pre.child = None pre = head self.recursive(child, pre) self.recursive(next1, pre) def travel(self, head): cur = head while cur != None: print(cur.item, end=' ') cur = cur.next print('\n') if __name__ == "__main__": h = Solution() node1 = Node(1) head = node1 node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) node6 = Node(6) node7 = Node(7) node8 = Node(8) node9 = Node(9) node10 = Node(10) node11 = Node(11) node12 = Node(12) node1.next = node2 node2.next = node3 node2.prev = node1 node3.next = node4 node3.prev = node2 node3.child = node7 node4.next = node5 node4.prev = node3 node5.next = node4 node5.prev = node4 node6.prev = node5 node7.next = node8 node8.next = node9 node8.prev = node7 node8.child = node11 node9.next = node10 node9.prev = node8 node10.prev = node9 node11.next = node12 node12.prev = node11 result = h.flatten(head) h.travel(result)
"""! @brief Defines the Error classes""" ## # @file error_led.py # # @brief Defines the error class for computing the error between the sensors # # @section description_error Description # Defines the class and function for computing the error between the sensors and returns the good sensor id # # @section libraries_sensors Libraries/Modules # - numpy # # @section notes_error Notes # - The error_calculation function was implemented based on Li, Liang, and Wei Shi. "A fault tolerant model for multi-sensor measurement." Chinese Journal of Aeronautics 28.3 (2015): 874-882. import numpy as np class error_led(object): """! The Error class The error class is used to get the residual error/detect the noisy sensor and take the input from the less noiser sensor """ def __init__(self): """! The class initializer Initialises the parameters """ self.led_light = False self.sensor_return = 0 def error_calculation(self, ac_voltage_0, ac_voltage_1): '''! Calculates the error between sensors The function is used to calculate the error function. If the error value is greater than 0 then sensor 0 is faulty and if error value is negative then sensor 1 is faulty. @params in : ac_voltage of sensor 0, and ac_voltage of sensor 1 @return - error between sensor one and two ''' #From [1] #Equation of the sensor = y = kx + c #Sensor 0 - `adc1 = 0.5 + 0.1 * angle` #Sensor 1 - `adc2 = 1.0 + 0.08 * angle` #Calculate residual error alpha = (0.1/0.08) #ki/kj beta = 0.5 - ((0.1*1.0)/0.08) #ci - ki*cj / kj error = np.round(np.mean(ac_voltage_0 - ((alpha*ac_voltage_1) + beta))) if error == 0: print("Both the sensors are fine") elif error > 0: print("Sensor with channel id 0 is not working fine") self.led_light = True self.sensor_return = 0 elif error < 0: print("Sensor with channel id 1 is not working fine") self.led_light = True self.sensor_return = 1 return self.sensor_return def led_light_on(self): '''! Sets the LED in the panel to ON and OFF The function is used to switch on and off the LED light in the Dashboard @return - Switches on the light in the Dashboard ''' if self.led_light: print("LED LIGHT IS GLOWING......") else: print("LED LIGHT IS OFF AND EVERYTHING IS COOL.....")
#!/usr/bin/env python # coding: utf-8 # This project will explore a sample of German Ebay auto classifieds. The data needs to be cleaned and then analyzed. This project should help me to practice and better understand the details of working with pandas and cleaning data. # In[86]: import pandas as pd import numpy as np autos = pd.read_csv("autos.csv", encoding = "Latin-1") # In[87]: autos # In[88]: autos.info() autos.head() # There are a few fields which have null values that need to be cleared up. Going to need to clean the price column, odometer column, and possibly the dateCreated/LastSeen Columns. # In[89]: autos.columns # In[90]: cols = ['date_crawled', 'name', 'seller', 'offer_type', 'price', 'abtest', 'vehicle_type', 'registration_year', 'gearbox', 'power_ps', 'model', 'odometer', 'registration_month', 'fuel_type', 'brand', 'unrepaired_damage', 'ad_created', 'nr_of_pictures', 'postal_code', 'last_seen'] autos.columns = cols autos.head() # These changes were made to make some of the more obscure or long names easier to work with. dateCreated for example, it is fairly obscure what this field actually meant, could it be when the car was produced or some other information, or could it be when the ad was created. By changing the name to ad_created it makes it much easier to quickly understand what this field is meant to be. # In[91]: autos.describe() # It appears as if the nrOfPictures field is always 0. This field can be dropped. # # There are some strange values in the registration_year field since the min is 1000 and the max is 9999 and a car could not be registered for 7000+ years from now. # # There are also some strange values in the powerPS field since a car shouldnt be able to have 17700 PS of power so some rows may need to be removed. # # As I stated earlier, it appears the price and odometer fields which are currently strings will need to be cleaned and converted to floats/ints. # # Again, if we want to sort by date of posting or date last seen we will need to clean those fields and convert the dates to ints. # In[92]: autos['price'] = (autos['price'] .str.replace('$','') .str.replace(',','') .astype(float) ) autos['odometer'] = (autos['odometer'] .str.replace('km','') .str.replace(',','') .astype(float) ) autos.rename({'odometer': 'odometer_km'}, axis = 1, inplace = True) autos.head() autos = autos.drop(columns='nr_of_pictures') # In[93]: autos = autos[autos['price'].between(0,350000)] autos['price'].describe() autos = autos[autos['registration_year'].between(1900,2017)] # The odometer appears to follow a standard pattern with no outliers. However, the price had some inconsistencies. There were a few listings that had prices well into the millions and while some extremely high end cars can get into that range it is very uncommon to see them on a site like Ebay instead of at an auction. I capped the max price to 350000 which is the last value in the somewhat reasonable range. The next value is 990000, nearly 3x the price. I also left in all the cars that cost 0 dollars because it is not too uncommon for an old beatup car to be given away for free to someone that wants to fix it up. # # It appears that for the prices, most of them are $3000 or less. Most of the Mileage is 150000. # In[94]: (autos['date_crawled'] .value_counts(normalize=True, dropna=False) .sort_index(ascending=False) ) # The pages appear to have been crawled over the span of about a month. Not many listings were crawled at the same time since there are 48200 unique date times that listings were crawled. # In[95]: (autos['ad_created'] .value_counts(normalize=True, dropna=False) ) # Most of the listings appear to have been created in march and april, when the listings were crawled. However the earliest ones were created nearly a year before the crawling. # In[96]: (autos['last_seen'] .value_counts(normalize=True, dropna=False) #.sort_index(ascending=False) ) # Most listings were last seen around the end of the scraping period. However, there were still a lot of listings that ended throughout the period. # In[97]: autos['registration_year'].describe() # After cleaning the data, most cars were registered before 2008. The mean registration year is 2003 and only 25% were registered before 1999. # In[98]: autos['registration_year'].value_counts(normalize = True) * 100 # The most popular year of car being sold is 2000 with 2005 and 1999 just under 1% behind. # In[99]: brand_counts = autos["brand"].value_counts(normalize=True) top_20_brands = brand_counts.index[:20] print(top_20_brands) '''I am using the top 20 brands because that gives a good representation of not only the largest brands but some of the smaller brands.''' top_brands_mean_price = {} top_brands_mean_mileage = {} for brand in top_20_brands: selected_rows = autos[autos['brand'] == brand] top_brands_mean_price[brand] = selected_rows['price'].mean() top_brands_mean_mileage[brand] = selected_rows['odometer_km'].mean() top_brands_mean_mileage # Mini has the best resale price of the top 20 brands. BMW, Audi, and Mercedes all have good resale value and are close to equal. # In[100]: bmp_series = pd.Series(top_brands_mean_price) bmm_series = pd.Series(top_brands_mean_mileage) mileage_and_prices = pd.DataFrame(bmp_series, columns = ['mean_price']) mileage_and_prices['mean_mileage'] = bmm_series mileage_and_prices # Part of the reason Mini's are so valuable is because they have the least average miles. If Mini's average mileage were closer to the 130000 miles of BMW, Audi, and Mercedes I would expect it to be equal or less than their average prices. # # It also appears that most the cars being sold have between 100000 and 130000 miles. # In[101]: autos # In[102]: autos = autos.replace('andere','other') autos['seller'] = autos['seller'].str.replace('privat','private').str.replace('gewerblich','commercial') autos['offer_type'] = autos['offer_type'].str.replace('Angebot','offer').str.replace('Gesuch','Auction') autos['vehicle_type'] = (autos['vehicle_type'] .str.replace('kleinwagen','compact car') .str.replace('kombi', 'station wagon') ) autos['gearbox'] = autos['gearbox'].str.replace('manuell','manual').str.replace('automatik','automatic') autos['fuel_type'] = (autos['fuel_type'] .str.replace('benzin','gasoline') .str.replace('elektro','electric') ) autos['unrepaired_damage'] = autos['unrepaired_damage'].str.replace('nein','no').str.replace('ja','yes') # Converted all the German words to English here. # In[103]: autos['date_crawled'] = autos['date_crawled'].str.split(n=1,expand=True).iloc[:,0].str.replace('-','') autos['ad_created'] = autos['ad_created'].str.split(n=1,expand=True).iloc[:,0].str.replace('-','') autos['last_seen'] = autos['last_seen'].str.split(n=1,expand=True).iloc[:,0].str.replace('-','') # In[104]: mileage_groups = autos['odometer_km'].value_counts().index mean_price_for_mileage = {} for mileage in mileage_groups: selected_rows = autos[autos['odometer_km'] == mileage] mean_price_for_mileage[mileage] = selected_rows['price'].mean() mean_price_for_mileage # The price of a vehicle on average drops $1300 ever 10000km for the first 100000km, then it drops less aggresively at a rate of $850 per 10000km over 100000km. For some reason cars with only 5000km on them are very cheap. Perhaps a lot of cars in the 5000km have unrepaired damage. # In[105]: for mileage in [5000.0,10000.0]: selected_rows = autos[autos['odometer_km'] == mileage] print(mileage) print(selected_rows['unrepaired_damage'].value_counts(normalize = True)) # My previous hypothesis was correct, out of the cars in the 5000km category 20.25% of them have damage. While in the 10000km only 3.75% of the cars have damage. Lets look at what damage does to a vehicle's valuation. # In[111]: mean_price_for_mileage_undamaged = {} mean_price_for_mileage_damaged = {} for mileage in mileage_groups: selected_rows_undamaged = autos[(autos['odometer_km'] == mileage) & (autos['unrepaired_damage'] == 'no')] mean_price_for_mileage_undamaged[mileage] = selected_rows_undamaged['price'].mean() selected_rows_damaged = autos[(autos['odometer_km'] == mileage) & (autos['unrepaired_damage'] == 'yes')] mean_price_for_mileage_damaged[mileage] = selected_rows_damaged['price'].mean() mean_price_undamaged_series = pd.Series(mean_price_for_mileage_undamaged) mean_price_damaged_series = pd.Series(mean_price_for_mileage_damaged) damage_vs_undamaged = pd.DataFrame(mean_price_undamaged_series, columns = ['mean_price_undamaged']) damage_vs_undamaged['mean_price_damaged'] = mean_price_damaged_series damage_vs_undamaged['price_difference'] = damage_vs_undamaged['mean_price_undamaged'] - damage_vs_undamaged['mean_price_damaged'] damage_vs_undamaged['damaged_percent_value_of_undamged'] = (damage_vs_undamaged['mean_price_damaged'] / damage_vs_undamaged['mean_price_undamaged']) * 100 damage_vs_undamaged # As can be seen in the chart above, selling a damaged car causes a huge drop in price. You can see that the fewer miles on a car, the more of the value you lose when a car is sold damaged. There is almost a $20000 difference between damaged and
import numpy as np import cv2 import myLogger as log def _draw_dotted_line(img, pt1, pt2, color): """ Draws a dotted line between to points on an image :param img: The image to draw on :param pt1: Point 1 of the line (x, y) :param pt2: Point 2 of the line (x, y) :param color: The color of the line (same format as the image; BGR/RGB) """ dist = ((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2) ** .5 # Pythagorean Theorem pts = [] number_of_points = int(dist / 7) # To get an even number of points if number_of_points % 2 == 1: number_of_points += 1 for i in np.linspace(0, dist, number_of_points, endpoint=True): r = i / dist x = int((pt1[0] * (1 - r) + pt2[0] * r) + .5) y = int((pt1[1] * (1 - r) + pt2[1] * r) + .5) pts.append((x, y)) for i in np.arange(0, len(pts) - 1, 2): # Only, if an endpoint for the dash if available if len(pts) > i + 1: cv2.rectangle(img, (pts[i][0] - 1, pts[i][1] - 1), pts[i + 1], color, -1) def _draw_dashed_rect(img, pt1, pt2, color): """ Draws a dashed rectangle :param img: The image to draw on :param pt1: Upper left point of the rectangle (x, y) :param pt2: Lower right point of the rectangle (x, y) :param color: The color of the line (same format as the image; BGR/RGB) """ p1 = (pt1[0] - 1, pt1[1] - 1) p2 = (pt2[0] + 2, pt1[1] - 1) p3 = (pt2[0] + 2, pt2[1] + 2) p4 = (pt1[0] - 1, pt2[1] + 2) _draw_dotted_line(img, p1, p2, color) _draw_dotted_line(img, p2, p3, color) _draw_dotted_line(img, p1, p4, color) _draw_dotted_line(img, p4, p3, color) def _draw_mask(image, mask, color, alpha=0.5): """ Draws a binary mask onto an image :param image: The image to draw on :param mask: The binary mask to draw (Must be same size as the image) :param color: The color of the mask (same format as the image; BGR/RGB) :param alpha: Transparency of the mask """ for c in range(3): image[:, :, c] = np.where(mask == 1, image[:, :, c] * (1 - alpha) + alpha * color[c] * 255, image[:, :, c]) return image def draw_masks_on_image(image, boxes, masks, group_ids_mask=None, group_ids_bounding_box=None, draw_groups=False, draw_mask=False, draw_box=False, color=(0, 255, 255)): """ Draws masks, hitboxes and their group ids on an image :param image: The image to draw on :param boxes: The bounding boxes of all masks :param masks: The binary masks :param group_ids_mask: The id of the group the mask have been assigned based on the mask content :param group_ids_bounding_box: The id of the group the mask have been assigned based on the space between mask and bounding box :param draw_groups: Whether to show the group ids :param draw_mask: Whether to draw the masks :param draw_box: Whether to draw the bounding boxes :param color: The color of the mask (same format as the image; BGR/RGB) """ color_float = (color[0] / 255, color[1] / 255, color[2] / 255) # Number of instances nr_of_persons = boxes.shape[0] if not nr_of_persons: log.info("No persons on image") else: assert boxes.shape[0] == masks.shape[-1] masked_image = image.astype(np.uint8).copy() for i in range(nr_of_persons): if not np.any(boxes[i]): # Skip this instance. Has no bounding box. Likely lost in image cropping. continue # Draw hitbox if draw_box: y1, x1, y2, x2 = boxes[i] _draw_dashed_rect(masked_image, (x1, y1), (x2, y2), color) # Draw mask if draw_mask: mask = masks[:, :, i] masked_image = _draw_mask(masked_image, mask, color_float) # Print group number next to hitbox if draw_groups: text = '[' + str(i) + '] ' + str(group_ids_mask[i]) + '/' + str(group_ids_bounding_box[i]) # Simulate outline cv2.putText(masked_image, text, (boxes[i][1], boxes[i][0] - 1), cv2.FONT_HERSHEY_PLAIN, 0.8, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(masked_image, text, (boxes[i][1], boxes[i][0] - 1), cv2.FONT_HERSHEY_PLAIN, 0.8, color, 1, cv2.LINE_AA) return masked_image
a=int(input('a=')) b=int(input('b=')) kup=1 if a<b: for i in range(a,b+1): kup *= i print('Ko\'paytmasi',kup) else: print('A<B shartni qanoatlantirmaydi')
# -*- coding: utf-8 -*- """ For32. n butun soni berilgan (n > 0). Quyidagi ketma – ketlikning dastlabki n ta hadini chiqaruvchi programma tuzilsin. A 0 = 1; AK = (AK-1 + 1) / K; K = 1, 2, … Created on Fri Jun 25 18:33:00 2021 @author: Mansurjon Kamolov """ n = int(input('n=')) a=1 for i in range(1,n+1): a=(a+1)/i print('a'+str(i),'=',a)
# -*- coding: utf-8 -*- """ For16. n butun soni va a haqiqiy soni berilgan (n > 0). Bir sikldan foydalanib a ning 1 dan n gacha bo’lgan barcha darajalarini chiqaruvchi programma tuzilsin. Created on Thu Jun 24 19:37:20 2021 @author: Mansurjon Kamolov """ a = float(input('a = ')) n = int(input('n = ')) kup = 1 if n>0 : for i in range(1,n+1): kup*=a print(a,'ning',i,'- darajasi',kup) else: print('n>0 bo\'lishi kerak')
def largest_matrix(arr): # Write your code here if len(arr) == 0 or len(arr[0]) == 0: return 0 cache = [[0 for i in range(len(arr[0]))] for j in range(len(arr))] for i in range(len(arr)): cache[i][0] = arr[i][0] for j in range(len(arr[0])): cache[0][j] = arr[0][j] largest_size = 0 for i in range(1, len(arr)): for j in range(1, len(arr[i])): if arr[i][j] == 1 and arr[i - 1][j] == 1 and arr[i][j - 1] == 1 and arr[i - 1][j - 1] == 1: cache[i][j] = min(cache[i - 1][j], cache[i][j - 1], cache[i - 1][j - 1]) + 1 else: cache[i][j] = arr[i][j] largest_size = max(largest_size, cache[i][j]) return largest_size
#转义序列:\n \t \r \' \"... days = 'Mon Tue Wen Thu Fri Sat Sun' months = '\nJan\nFeb\nMar\nApr\nMay' print('Here are the days:', days) print('Here are the months:', months) #长字符串以行打印 print(''' There's something going on here. With the three double_quotes. We'll be able to type as much as we can. Even 4 lines if we want, or 5, or 6. ''')
#复习各种符号 #python中的关键字: #raise,yield,lambda #python数据类型 #strings,numbers,floats,lists,dicts,bytes,None,False,True #转义序列 #\a:响铃 #\b:退格 #\f:换页 #\r:回车 #\v:垂直制表符 #老式字符串格式方法,'%占位符'%替换内容 #替换整数 print('>>> ', '%d' % 25) print('>>> ', f'{25}') #替换浮点数 print('>>> ', '%.3f' % 3.1415926) #替换字符串 print('>>> ', '%s' % 13) #替换十六进制数 print('>>> ', '%x' % 15) #运算符 # + - * / // % > < = () 等等
import os # define function def read_file(filename): log = [] with open(filename, 'r', encoding='UTF-8-SIG') as f: for line in f: log.append(line.strip()) return log def formatting(log): person = None # just to prevent if there is no Allen or Tom in first line of chatlog # indicate that person has no value (null) # person = '123' # if person != '123': # formated.apend(person + ': ' + line) formated = [] for line in log: if line == 'Allen': person = 'Allen' continue # go directly into next loop elif line == 'Tom': person = 'Tom' continue # go directly into next loop if person: # if person has value formated.append(person + ': ' + line) return formated def write_file(outputname, formated): with open(outputname, 'w', encoding='UTF-8') as f: for line in formated: f.write(line + '\n') # define main function def main(): filename = input('Which log do you want to input? ') log = read_file(filename) formated = formatting(log) outputname = input('Output as? ') write_file(outputname, formated) # run main function if __name__ == '__main__': main()
# 0702_while.py password = 12345678 running = True while running: guess = int(input('Enter password: ')) if guess == password: print('Welcome to Facebook!') running = False else: print('Wrong password.') else: print('Not logging in.') print('Done')
# 0502_print.py # Fun with print() print('a', end = '\t') print('b', end = '\t') print('c', end = '\t') print('\nNew lines are \n. Understand?\n') print(r'\nNew lines are \n. Understand?\n') myName = 'Aaron' print(myName) _myAge = 41 print(_myAge) mySong = 'Blueming' print(mySong) # Variables in one line (;) i = 5; print(i); i = i + 6; print(i);
# 0501_format.py '''This is a long comment. We will learn `format` string. Ready? ''' age = 41 name = "Aaron" print('{1} is {0} years old.'.format(age, name)) print(name + ' is ' + str(age) + ' years old.') print('{name} is {age} years old.'.format(age = 28, name = 'IU')) name2 = 'IU' song = '가을아침' print(f'{name2}\'s best song is {song}!!!') print(name2 + "'s best song is " + song + '!'*30) print('{0:_^20}'.format(song)) print('{0:_^20} is {1:*^10}\s best song~! {2:@^7} loves her!' .format(song, name2, name))
# my_pizza.py def make_pizza(size, *toppings): """Summarize the pizza we are about to make.""" print(f"\nMaking a {size}cm pizza with: ") for t in toppings: if t.lower() == 'myulchi' or t.lower() == 'pineapple' or t.lower() == 'gochu': print(f"- NO {t}!") else: print(f"- {t}") make_pizza(12, "pepperoni", "cheese") make_pizza(12, "pepperoni", "cheese", "GOGUMA", "pineapple", "pickles", "mushrooms", "tomatoes", "ham", "sausage", "chicken", "gochu", "myulchi")
# 1202_robots.py class Robot: pop = 0 # 인구 def __init__(self, name): self.name = name print('{} 만드는 중'.format(self.name)) Robot.pop += 1 def die(self): print('{} 꺼지고 있어요.'.format(self.name)) Robot.pop -= 1 if Robot.pop == 0: print('{} 마지막이다.'.format(self.name)) else: print('로봇 {:d}개 남아요.'.format(Robot.pop)) def say_hi(self): print('안녕하세요. 내 이름은 {}입니다.'.format(self.name)) @classmethod def how_many(cls): print('로봇 {:d}개 남아요.'.format(Robot.pop)) robot1 = Robot('R2-D2') robot1.say_hi() Robot.how_many() robot2 = Robot('C-3PO') robot2.say_hi() Robot.how_many() print('로봇들은 지금 일 하고있다.') print('일이 다 끝났다.') robot1.die() robot2.die() Robot.how_many()
# ECar = 전기차 from Car import Car class ECar(Car): """ECar is a type of Car.""" def __init__(self, make, model, year, battery_size=75): super().__init__(make, model, year) self.battery = battery_size def get_battery(self): print(f"Your battery is a {self.battery}-kWh battery.") def get_range(self): if self.battery <= 75: range = 260 elif self.battery <= 100: range = 315 elif self.battery <= 1_0000_0000: range = "unlimited " print(f"You can drive {range}km!") ecar = ECar("tesla", "model x", 2024) print(f"My e-car is a {ecar.get_name()}.") ecar.get_battery() ecar.get_range() ecar.drive()
""" Level order traversal of a tree is breadth first traversal for the tree. printLevelorder(tree) 1) Create an empty queue q 2) temp_node = root /*start from root*/ 3) Loop while temp_node is not NULL a) print temp_node->data. b) Enqueue temp_node’s children (first left then right children) to q c) Dequeue a node from q and assign it’s value to temp_node """ def levelOrder(root): q = [] temp_node = root while temp_node: print(temp_node.info, end=' ') if temp_node.left: q.append(temp_node.left) if temp_node.right: q.append(temp_node.right) if len(q) > 0: temp_node = q.pop(0) else: return
# In this lecture we'll cover the usage of the with statement. # The with statement allows to close a file without using the close method. # The with statement defines a block, which will close the file once left. # In the block defined the variable file can be used with open("18_Text_File.txt", 'a') as file: file.write ("Line 4 \n") # The file will be closed automatically.
# EX 07: Translating addresses into geographic coordinates # The process of translating an address to a pair of coordinates is called # geo-coding. The reverse mechanism is called reverse geo-coding # To do this exercise you need to install the Geopy library # https://github.com/geopy/geopy import pandas import geopy df = pandas.read_csv ("http://pythonhow/supermarkets.csv") # Geopy needs an internet connection to use its module "geocoder", the one we # need for our purposes. # We need to use the tool Nominatim, included in the geocoders module from geopy.geocoders import Nominatim # We create a Nominatim variable nom = Nominatim (scheme='http') n = nom.geocode("3995 23rd St, San Francisco, CA 94114") # By using this method we receive a location, another data type # Location(3995, 23rd Street, Noe Valley, SF, # California, 94114, United States of America, (37.7529648, -122.4317141, 0.0)) # If the address inserted doesn't exist, nothing will be returned # From a location data type, we can extract latitude and longitude by using # the corresponding methods. lat = n.latitude lon = n.longitude # This is the way we translate an address into coordinates. # We want to do that by using the addresses included in the df dataframe # First, we want to edit the "Address" column in order to contain the # entire data we need to pass to the geocode method. df["Address"] = df["Address"]+", "+df["City"]+", "+ df["State"] + ", " + df["Country"] # On a Pandas DataFrame we don't need to iterate. Pandas allow to apply methods # on all the rows of a DataFrame. # The apply method allow us to do that. It takes as a parameter the function # to apply on each row. The parameter the function will take will change every # time a new row is considered. df ["Coordinates"] = df["Address"].apply(nom.geocode) # With this operation, we are going to create a new column called coordinates, in # which we put the result of nom.geocode(row), for each row of the dataframe. # The nom.geocode will get as a parameter the address, as indicated from df["Address"] # This way we put all the informations about the location, not only the coordinates in the dataframe. # To put the coordinates only: df["Latitude"] = df["Coordinates"].apply(lambda x: x.latitude if x != None else None) df["Longitude"] = df["Coordinates"].apply(lambda x: x.longitude if x != None else None) # With these two statements we are going to apply the function latitude and longitude for each row of the # dataframe. We are going to apply those functions on the Position object stored in df["Coordinates"] # If for some reason, the Coordinates value is None (maybe because the position cannot be # calculated, because of the unreal address in the dataset), the function must not be applied # This way, we avoid getting errors due to non-present data.
# In this lecture we are going to cover the different ways to import # datasets in pandas. We'll use file such as .xlsx, .csv, .json etc. # You can find some example files in the Resources folder. # In order to have a better data visualization, it is recommended to use # the Jupyter Notebook: http://jupyter.org/ # For this lecture, I used jupyter notebook, but you can do the same by using # a normal text editor, such as Atom or Notepad++. # I'll report here the lines of code I used, and the jupyter notebook file too # whose format is .ipynb import pandas df1 = pandas.read_csv("Resources/supermarkets.csv") print (df1) # Each file format has a header, which recognizes the column names. # If we want to ignore that, and consider the tuple containing the column names # equal to the others, we can do it by typing: df1 = pandas.read_csv ("Resources/supermarkets.csv", header=None) # Pandas will create a default header for column names # As you may have noticed, Python automatically sets an automatic ID. # If we want to set a custom ID, we can do by typing: df1 = df1.set_index("ID") # This way, Python will find for a column named "ID" and will use it as an index. print (df1) # If we want to know the dimension of the datasets in columns/rows: print (df1.shape) # In order to read a json file, we can do: df2 = pandas.read_json("Resources/supermarkets.json") # We can do the same for the index, as we did before: df2 = df2.set_index("ID") # Now, let's import an excel file (xlsx): df3 = pandas.read_excel("Resources/supermarkets.xlsx") # As you know, excel files can have multiple sheets. # They are identified by the parameter sheetname, which goes from 0 to N # with N the last sheet. df3 = pandas.read_excel("Resources/supermarkets.xlsx", sheetname=0) # Now, as you can see we have a txt file in the Resources folder. If we take a look # to it, we notice that it has its data separated by commas. So, in order to import # it in a DataFrame, we need to use the read_csv function (CSV = Comma Separated Value) df4 = pandas.read_csv("Resources/supermarkets-commas.txt") # Obviously, in a txt file, we can use the separator character we prefer. # To indicate it, we can use the separator parameter: df5 = pandas.read_csv ("Resources/supermarkets-semi-colons.txt", sep=';') # If we do not specify the separator for a txt file whom separator character # is different from the comma, Python won't recognize the dataset correctly. # Pandas allows to read online files as well! # For example, we can read a file host on a website: http://pythonhow.com/supermarkets.csv df6 = pandas.read_csv("http://pythonhow.com/supermarkets.csv") df7 = pandas.read_json("http://pythonhow.com/supermarkets.json")
# In this simple lesson we are going to print something on screen # We use the built in print function print("Hello world!") v = 3 v = v + 1 print("Second hello world")
# In this lecture we'll cover the fundamentals of loops. # A loop is basically a way to execute a statement multiple times. # Loops allow to save a lot of code, and avoid some replications. # In Python there are two different loops: for and while emails = ["foo@email.com", "me@gmail.com", "you@hotmail.com"] # If we want to print each item inside the list, we can do by using one print # function for each item of the list, but this implies some kind of replication of code. # The for loop is very useful in a case like this: for email in emails: print (email) # The previous two lines print the item of the list, for each item # Suppose that we want to print only the gmail addresses: for email in emails: if email.endswith("@gmail.com"): print (email) # We can do the same using the operator in: for email in emails: if "gmail" in email: print (email) # Now we are going to cover the usage of for loop with more lists simultaneously names = ["John", "Jack", "Amber"] email_domains = ["gmail.com", "hotmail.com", "yahoo.com"] for i,j in zip (names, email_domains): print(i,j) # zip function is used to access two or more lists contemporary
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html_doc,"html.parser") #print(soup.prettify()) print(soup.title.string) for link in soup.find_all('a'): print(link.get('href')) print(soup.get_text()) def match_class(target): def do_match(tag): classes = tag.get('class', []) return all(c in classes for c in target) return do_match html = """<div class="feeditemcontent cxfeeditemcontent"> <div class="feeditembodyandfooter"> <div class="feeditembody"> <span>The actual data is some where here</span> </div> </div> </div>""" soup = BeautifulSoup(html) print soup.find_all(match_class(["feeditemcontent", "cxfeeditemcontent"]))
import os os.chdir('E:\Datacamp\Python\Introduction to database in Python') from sqlalchemy import create_engine, select engine = create_engine("sqlite:///census.sqlite") connection = engine.connect() # Import packages from sqlalchemy import MetaData, Table # Creaate metadata metadata = MetaData() # Reflect census table from the engine: census census = Table("census", metadata, autoload=True, autoload_with=engine) #### FILTER DATA: SIMPLE # Create a select query: stmt stmt = select([census]) # Add a where clause to filter the results to only those for New York stmt = stmt.where(census.columns.state == "New York") # Execute the query to retrieve all the data returned: results results = connection.execute(stmt).fetchall() # Loop over the results and print the age, sex, and pop2008 for result in results: print(result.age, result.sex, result.pop2008) #### FILTER DATA: EXPRESSION # Create a query for the census table: stmt stmt = select([census]) # Define states states = ['New York', 'California', 'Texas'] # Append a where clause to match all the states in_ the list states stmt = stmt.where(census.columns.state.in_(states)) # Loop over the ResultProxy and print the state and its population in 2000 for cen in connection.execute(stmt): print(cen.state, cen.pop2000) #### FILTER DATA: ADVANCED # Import and_ from sqlalchemy import and_, or_ # Build a query for the census table: stmt stmt = select([census]) # Append a where clause to select people in NewYork who are 21 or 37 years old stmt = stmt.where( and_(census.columns.state == 'New York', or_(census.columns.age == 21, census.columns.age == 37 ) ) ) # Loop over the ResultProxy printing the age and sex for result in connection.execute(stmt): print(result.state, result.age)
import datetime import math database ={} balance = 100 def basicMenu(): print('These are the available options') print('1. Withdrawl') print('2. Deposit') print('3. Comlpaint') selectedOption = int(input('Please selct an opton: ')) return selectedOption def option(choice): global balance if(choice == 1): print('You selected %s' % choice) print('How much would you like to withdraw? \n') withdraw = int(input()) if( withdraw > balance): print("Error: withdrawl money is more than the balance.") elif(balance == 0): print("Error:No money in the bank. Pls, deposit first.") balance -= withdraw print('Balance : %d' , balance ) print('Take your cash') basicMenu() elif(choice == 2): print('You selected %d' % choice) print("How much would you like to deposit? ") deposit = int(input()) balance += withdraw print('Balance : %d' , balance ) basicMenu() elif(choice == 3): print('You selected %d ' % choice) print('What issue would you like to report? \n') complaint = input() print('"Thank you for contacting us."') basicMenu() else: print('Inavlaid option. Try again') basicMenu() #allowedUsers = ['Anu', 'Mike', 'John'] #allowedPassword = ["passwordAnu", "passwordMike", "passwordJohn"] #amounts = [5000, 4000, 3000] #name = input("what is your name? \n") #userId = allowedUsers.index(name) datetime_string = str(datetime.datetime.now()) print( ' ' + name + 'logged in on ATM_Mock_Project on ' + datetime_string) #if(name in allowedUsers): # userId = allowedUsers.index(name) # password = input( "Your password? \n") # if(password == allowedPassword[userId]): # print('Welcome %s' % name ) # print(datetime_string) # basicMenu() # else: # print('Password Incorrect, please try again') #else: # print('Name not found. Please try again') def init(): print('Welcome to BankPython!\n') have_account = int(input('Do you have account with us: 1(yes) and 2(no)\n')) if have_account == 1: login() elif have_account == 2: register() else: print('You have selected invalid option\n') init() def login(): global account_number_from_user print('*************** Login **************') account_number_from_user = int(input('what is your account number? \n')) is_valid_account_number = (account_number_from_user).isdecimal() if is_valid_account_number: password = input('what is your password? \n') user = database.authenticated_user(account_number_from_user, password) if user: bank_operation(user) print('Invalid account or password') login() else: print('Your account number is not valid. Please recheck again next time') init() def register(): print('******** Register **********') email = input('What is your email address? \n') first_name = input('What is your first name? \n') last_name = input('What is your last name? \n') password = input('Create password for yourself \n') #balance = int(input('How much money you want to put into the bank now? \n')) account_number = generation_account_number() is_user_created = database.create(account_number, first_name, last_name, email, password, str(0)) if is_user_created: print('Your account has been created') print('== ==== ====== ==== ==') print('your account no is %d' % account_number) print('Make sure you keep it safe and remember') print('== ==== ====== ==== ==') login() else: print('Something went wrong. Please retry!') register()
# lamada multiplication # lamda_multiplication.py #Lambda functions can take any number of arguments: #Multiply argument a with argument b and return the result: # [Running] python -u "/Users/anupama/Desktop/python/lamada_multiplication.py" 30 x = lambda a, b : a * b print(x(5, 6))
import re def unique_in_order(iterable): c = re.sub(r'(\S)\1+', '\\1', str(iterable)) if c.isdigit(): d = list(c) d = [int(i) for i in d] print(d) else: print(list(c)) unique_in_order('123777') unique_in_order('ABCDAB') #from itertools import groupby # def unique_in_order(iterable): # return [k for (k, _) in groupby(iterable)] # def unique_in_order(iterable): # result = [] # prev = None # for char in iterable[0:]: # if char != prev: # result.append(char) # prev = char # return result
with open("check64.txt") as f: check=f.read() with open('out64.txt') as f: out=f.read() def encrypt(text, crypto): key="" i=0 for x in text: key+=chr(ord(crypto[i])-ord(x)) i+=1 print(key) def decrypt(text,key): keylen = len(key) keyPos = 0 decrypted = "" for x in text: keyChr = key[keyPos] newChr = ord(x) newChr = chr((newChr - ord(keyChr)) % 255) decrypted += newChr keyPos += 1 keyPos = keyPos % keylen return decrypted with open('passre.txt') as f: password=f.read() with open('key.txt') as f: key=f.read() print(decrypt(password,key='alexandrovich')) #encrypt(check,out)