text
stringlengths
37
1.41M
str_1 = "lucidProgramming" str_2 = "LucidProgramming" str_3 = "lucidprogramming" def iterativeFindUpper(testStr): for c in testStr: if c == c.upper(): return c return None # print(iterativeFindUpper(str_1)) # print(iterativeFindUpper(str_2)) # print(iterativeFindUpper(str_3)) def recur...
""" Solver class to solve the Queen board using some algorithm """ from lib.problem.board import Board class Solver: """ Solving the Queen board by using algorithms defined Attributes ---------- __board : Board initial board __stepsClimbed : int number of steps taken in the s...
import os import cv2 import numpy as np def read_gt_file(path): """Read an optical flow map from disk Optical flow maps are stored in disk as 3-channel uint16 PNG images, following the method described in the KITTI optical flow dataset 2012 (http://www.cvlibs.net/datasets/kitti/eval_stereo_flow.php?b...
# When a class has its own functions, those functions are called methods. # method _description_ using print statements, prints out the name and age of the animal it’s called on. class Animal(object): """Makes cute animals.""" is_alive = True def __init__(self, name, age): self.name = name self.age = ag...
""" The main method for the program used to edit an excel file of wind turbine information Author: Patrick Danielson """ # Imports import pandas as pd import time_generation as tg import dataframe_manipulation as em # Method in progress to create new excel file with conditions given # Input: Excel file # Output: Cre...
# # @lc app=leetcode.cn id=188 lang=python3 # # [188] 买卖股票的最佳时机 IV # # https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/description/ # # algorithms # Hard (28.25%) # Likes: 143 # Dislikes: 0 # Total Accepted: 9.2K # Total Submissions: 32.4K # Testcase Example: '2\n[2,4,1]' # # 给定一个数组,它的第 i 个元素...
# # @lc app=leetcode.cn id=109 lang=python3 # # [109] 有序链表转换二叉搜索树 # # https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/description/ # # algorithms # Medium (69.56%) # Likes: 130 # Dislikes: 0 # Total Accepted: 16K # Total Submissions: 23K # Testcase Example: '[-10,-3,0,5,9]' # # 给定一个单链表...
# # @lc app=leetcode.cn id=814 lang=python3 # # [814] 二叉树剪枝 # # https://leetcode-cn.com/problems/binary-tree-pruning/description/ # # algorithms # Medium (71.50%) # Likes: 65 # Dislikes: 0 # Total Accepted: 5.1K # Total Submissions: 7.1K # Testcase Example: '[1,null,0,0,1]' # # 给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是...
import os def find_files(suffix, path): """ Finds all files beneath path with file name suffix. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ ls = os.listdir(path) files = [] for item in ls: ...
import os import Crypto.PublicKey.RSA import Crypto.Hash.SHA256 ''' Helpful routines for signing and verifying message signatures ''' def digest(message): digester = Crypto.Hash.SHA256.new() digester.update(message) return digester.digest() def genKeyPair(): return Crypto.PublicKey.RSA.generate(1024,...
''' Replace this file with your implementation from Assignment 1 ''' from UTXO import UTXO import CryptoUtil from Transaction import Transaction class TxHandler(object): ''' Collect transactions into a mutually valid set that can be used to mine a new block. ''' def __init__(self, pool): ...
# -*- coding: utf-8 -*- """ Created on Tue Jul 19 14:35:47 2016 @author: yifanli """ import turtle def main(): #filename = input("Please enter drawing filename: ") filename = "drawingSingle.txt" t = turtle.Turtle() screen = t.getscreen() file = open(filename,"r") for line ...
def make_shirt(size = 'large', shirt_msg = 'I love python'): """prints a msg about the shirt size and what it says""" print(f"The shirt size is {size} and the message on the shirt says {shirt_msg.title()}.") make_shirt('small','live life to the fullest') make_shirt(shirt_msg='the sun will rise again', size='me...
# traking down the speed of a alien that can move at different speeds alien_o = {'x_position': 0, 'y_position' : 25, 'speed': 'medium'} print(f"original position: {alien_o['x_position']}") if alien_o['speed'] == 'slow': x_increment = 1 elif alien_o['speed'] == 'medium': x_increment = 2 else : x_increment ...
num = input('Please enter the number of times you want to display hello world: ') for i in range(int(num)): print('Hello World!') for x in range(0,11,2): print(x)
# This program tells the user if the number # they enter is a multiple of ten print("Enter a number and I'll tell you if its a multiple of ten or not") num = input() num = int(num) if num % 10 == 0: print(f"The number {num} is a multiple of 10.") else: print(f"The number {num} is not a multiple of 10.")
prompt = "Enter the toppings your would like on your pizza: " active = True while active: message = input(prompt) if message == 'quit': active = False else: print(f"adding {message} to pizza.")
file_name = 'guest_book.txt' while True: name = input("Please enter your name here: ") if name == 'quit': break else: with open(file_name, 'a') as file_object: file_object.write(f"{name}\n") print(f"Hello {name}, you've been added to the guest book.")
name = 'Bob' age = 3000 # note this is on big block of code of the if and else if statement if name == 'Alice': print('Hi Alice') elif age < 12: print('You are not Alice, kiddo') elif age > 2000: print('Unlike you, Alice is not an undead, immortal vampire.') elif age > 100: print('You are not Alice, ...
pet_0 = { 'animal' : 'dog', 'breed' : 'husky', 'name' : 'rex', 'owner' : 'miguel', 'age' : 6 } pet_1 = { 'animal' : 'bird', 'breed' : 'parakeet', 'name' : 'lola', 'owner' : 'sarah', 'age' : 4 } pet_2 = { 'animal' : 'lizard', 'breed' : 'skink', 'name' : 'larry', ...
''' ## Summary: **Name:** Functionalize Maching Learning Procedure **Author:** Siyang Jing **Organization:** UNC-CH **License:** WTFPL **Reference:** 1. TensorFlow's keras tutorial 1. The author's other codes 1. Relevant numerous papers **Description:** This file prepares a function ML _Input_: * Parame...
import random KREWES = { 'orpheus': ['Emily','Kevin','Vishwaa','Eric','Jay'], 'rex': ['William','Joseph','Calvin','Ethan','Moody'], 'endymion': ['Grace','Nahi','Derek','Jun Tao','Connor'] } def rando(tn): print(random.choice(KREWES[tn])) tn = input("Enter team name: ") if tn in KREWES: rando(tn) el...
print("******************************************************************") print("PROGRAM STUDI : ILMU KOMPUTER ") print("MATA KULIAH : STRUKTUR DATA ") print("KELAS : 15.2A.31 ") print("TIM KELOMPOK 3 ") print(" 1. DIMAS RAMADHAN AGUSTINA (15200384)") p...
#!/usr/bin/python3 def uppercase(str): for word in str: if ord(word) >= 97 and ord(word) <= 122: word = chr(ord(word) - 32) print("{}".format(word), end="") print("")
#!/usr/bin/python3 """ Docstring """ def read_lines(filename="", nb_lines=0): """[summary] Args: filename (str, optional): [description]. Defaults to "". """ with open(filename) as file: line = 0 for i in file: line += 1 if nb_lines <= 0 or nb_lines >= lin...
import random def playPlusOrMinus(): random.seed() value = random.randint(1, 100) count = 0 found = False while not found: print ("Try a number : ") guess = int(input()) count += 1 if guess > value: print("Too big !") elif guess < value: ...
import time def job_1(): print("Job_1 Started") start = time.time() k = 0 for i in range(10000): for j in range(10000): k = i + j end = time.time() total = end - start print("Job_1 Completed in",total) def job_2(): print("Job_2 Started") start = t...
""" This file contains functions for transforming tensorflow tensors that represents images. These are used in order to get better-looking results when performing feature-visualizations. """ import tensorflow as tf import math # TODO: fill in the rest of the functions def random_param(param_list): random_index...
class Data: def __init__(self, data): tmp = data.split("|") self.name = tmp[0] self.age = tmp[1] self.grade = tmp[2] def print_age(self): print(self.age) def print_grade(self): print("%s님 당신의 점수는 %s입니다." % (self.name, self.grade)) data = Data("홍길...
f1 = open("test.txt", 'w') f1.write("Life is too shor!") f1.close() f2 = open("test.txt", 'r') print(f2.read()) f2.close() # close를 명시적으로 할 필요가 없는 with구문 with open("test.txt", 'w') as f1: f1.write("Life is too short!") with open("test.txt", 'r') as f2: print(f2.read()) # 'a' 모드...
input1 = input("첫번째 숫자를 입력하세요:") input2 = input("두번째 숫자를 입력하세요:") total = int(input1) + int(input2) print("두 수의 합은 %s 입니다" % total)
def mul(*args): result = 1 for n in args: result *= n print(result) mul(1,2,3,4,5)
import math a = float(input("Enter the value of a")) if(a>0): b= float(input("Enter the value of b")) c=float(input("Enter the value of c")) Uroot = (b*b)-(4*a*c) x1= (-b+math.sqrt(Uroot))/(2*a) x2 = (-b-math.sqrt(Uroot))/(2*a) print("The value of x1 and x2 is:") print(x1,x2); else: prin...
String1= "{l} {f} {g}".format(g="Geeks",f="For",l="Life") print("\nPrint String in order of Keyword: ") print(String1)
p =float(input("Enter the principal amount")) t = float(input("Enter the Time")) r = float(input("Enter the rate")) print("The simple interest is ",(p*t*r)/100)
def largest(arr,num): max=arr[0] for i in range(0,num): if(arr[i]>max): max=arr[i] return max arr=[] num=int(input("Enter the Array Size")) print("Enter the Array") for i in range(0,num): item=int(input()) arr.append(item) ans = largest(arr,num) print(arr) print("Largest num...
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ digits = 0 xCopy = int(str(x)[:]) #Used to form reversed integer power = len(str(abs(x))) - 1 for i in range(len(str(x))): #Runs on all digits of x digits += (ab...
# -*- coding: utf-8 -*- ''' Common utility methods for key concept extraction. ''' from nltk.corpus import stopwords as nltk_stopwords import unicodedata def ascii_approximation(s): """ Returns an ascii "approximation" to the given unicode string. @param s: The string to be approximated. """ if...
class MyTime(object): def __init__(self, time): self._time = time self._hours = int(self._time.split(':')[0]) self._minutes = int(self._time.split(':')[1]) self._seconds = int(self._time.split(':')[2]) def get_hours(self): return self._hours def get_minutes(self): ...
#!/usr/bin/env python # coding: utf-8 # <div class="licence"> # <span>Licence CC BY-NC-ND</span> # <span>François Rechenmann &amp; Thierry Parmentelat</span> # <span><img src="media/inria-25-alpha.png" /></span> # </div> # # `next_start_codon` and `next_stop_codon` # Let us now remember the algorithm that searches f...
import math i=0 num=0 ''' while i < 10 : i+=1 print("MisionTIC") while i<10: i+=1 print(i) ''' '''Realiza un programa que muestre los numeros impares que hay del 1 al 20 y final muestre la suma de todos ellos'''
"""This file defines the model for a user""" from datetime import datetime from werkzeug.security import check_password_hash from mongoengine import fields, Document, DoesNotExist class User(Document): """Defines a user model for the database Attributes: email: The unique email used to regi...
"""Code for solving a case of one-dimensional heat conduction in a rod with internal heat generation using 1D quadratic elements""" from __future__ import division import numpy as np from pylab import* """Inputs""" d = float(raw_input("Enter the diameter of the cross-sectional area of the rod(mm): ")) L = float(raw_in...
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.37 工具: python == 3.7.3 介绍: 熟悉pandas基本功能,参考《利用Python进行数据分析》5.2 """ import pandas as pd from pandas import Series, DataFrame import numpy as np """ 重建索引 """ print('Example 1:') obj = pd.Series([4.5, 7.3, -5.3, 3.6], index=['d', ...
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.36 工具: python == 3.7.3 介绍: 介绍Python集合,参考《利用Python进行数据分析》3.1.5 """ """ 集合 """ # 集合使用set()函数,其无序且元素唯一 print('Example 41:') print(set([2, 2, 2, 1, 3, 3])) # {1, 2, 3} # 集合并集 print('Example 42:') a = {1, 2, 3, 4, 5} b = {3, 4, 5, ...
import time # 插入排序 def insertion_sort(data): move_count = 0 # 统计移动次数 circle_count = 0 # 统计循环次数 for test n = len(data) for i in range(1, n): for j in range(i, 0, -1): circle_count += 1 # for test if data[j] < data[j-1]: data[j], data[j-1] = data[j-1],...
class Solution: def isPalindrome(self, s): """ 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 说明:本题中,我们将空字符串定义为有效的回文串 示例 1: 输入: "A man, a plan, a canal: Panama", 输出: true :type s: str :rtype: bool """ import re pat = re.compile(r'[\W_]') res ...
# def tower_builder(n_floors): # # 方法一 # # list_res = [] # # for i in range(1, 2*n_floors, 2): # # #temp = (i+1)//2 # # list_res.append((n_floors-(i+1)//2)*" " + i * "*"+ (n_floors-(i+1)//2)*" ") # # return list_res # # 方法二 # #return [(n_floors-(i+1)//2)*" " + i * "*"+ (n_floors-...
# # def quick_sort(arrys, left, right): # if left >= right: # return arrys # # key = arrys[left] # # 将左边第一位定位基准数,以此数将序列分为两部分 # low = left # high = right # while left != right: # # 从最右边开始查(一定要从最右边开始查),查找比基准值小的数 # while left < right and arrys[right]>=key: # righ...
class MinStack: def __init__(self): """ initialize your data structure here. """ self.head = -1 self.data = [] def push(self, x): """ :type x: int :rtype: void """ # if self.head == -1: self.data.append(x) self.hea...
def longestchildlist(arr): arr2 = arr[::-1] res = [] for i in range(1, len(arr)): b = [] for v in arr2[i-1:]: if len(b): if v < b[0]: b.insert(0, v) else: b.insert(0, v) if len(b) > len(res): res...
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not nums.count(target): nums.append(target) nums.sort() return nums.index(target) if __name__ == "__main__": lis ...
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if needle is not '': if needle in haystack: return haystack.index(needle) else: return -1 else...
class Solution: def lengthOfLastWord(self, s): """ 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 如果不存在最后一个单词,请返回 0 . 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 :type s: str :rtype: int """ res = s.strip().split(' ') if any(res): return len(res[-1]) ...
#comment added for git push practice dashboard = ['-'for i in range(9)] game_is_running = True current_player = 'X' winner = None def play_game(): global game_is_running global winner show_board() while game_is_running: handle_turn(current_player) ...
# Selection sort is proces of sorting an array. # In Selection sort, we take the smallest value in the array and swap it with the first element in the unsorted part. def selectionSort(list): for i in range(len(list)-1): minvalue = i for j in range(i+1,len(list)): if(list[minvalue] > li...
import os import random # Defining the suits and ranks of a given card suits = ["Spades", "Hearts", "Diamonds", "Clubs"] ranks = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"] player_hands = [] player_bids = [] player_chips = [] def create_deck(): # Create a full deck with 52 cards deck = [] ...
class user(object): def __init__(self,name,email,password): self.name = name self.email = email self.password = password self.friends_list = [] self.posts = [] def add_friend(self,email1,friends_list): self.email1 = email1 self.friends_list.append(self.email1) print (self.name +" had added "+self...
import numpy as np import matplotlib.pyplot as plt import ml.linear_regression as lire from ml.gradient_descent import gradient_descent data = np.loadtxt("ml_course_material/machine-learning-ex1/ex1/ex1data1.txt", delimiter=",") (m, feature_length_with_result) = data.shape x = data[:, 0].reshape((m, feature_length_...
import numpy as np import ml.utils as utils def feed_forward(X, Thetas): """ Feeds the inputs X through neural network represented by Theta matrices. :param X: inputs: m x n (m examples, n features) :param Thetas: Theta matrix for each layer :return: matrix of shape m x #neurons_in_output_layer ...
"""Calculate the equation inside the list in order of operation. The first and last item will always be a number. Numbers are separated by a + or * symbol. All items are in individual strings. Examples: >>> calculate(["6", "+", "8", "*", "12", "+", "47"]) 149 >>> calculate(["1", "+", "1", "+", "1"])...
def print_node_at_depth(root, depth): def wut_depth(root, depth, current_d): # base case if current_d == depth: print node else: current_d += 1 wut_depth(root.left, depth, current_d) wut_depth(root.right, depth, current_d)
def calc_change(n): penny = 1 nickle = 5 dime = 10 quarter = 25 coins = { quarter: 0, dime: 0, nickle: 0, penny: 0 } while n > 0: if n >= quarter: n -= 25 coins[quarter] += 1 elif n >= dime: ...
""" Write a function that reverses a string. Use as much memory as you want. """ def reverse_str(string): lst = list(string) current = len(lst) - 1 new_lst = [] while current > -1: new_lst.append(lst[current]) current -= 1 #print new_lst return "".join(new_lst) print r...
''' The classical introductory exercise. Just say "Hello, World!". "Hello, World!" is the traditional first program for beginning programming in a new language or environment. The objectives are simple: Write a function that returns the string "Hello, World!". Run the test suite and make sure that it succeeds. Submi...
# Written by Eric Martin for COMP9021 # # Prompts the user for an arity (a natural number) n and a word. # Call symbol a word consisting of nothing but alphabetic characters # and underscores. # Checks that the word is valid, in that it satisfies the following # inductive definition: # - a symbol, with spaces al...
# 1/1 count_web_words # 1/1 read_url # 1/1 string_to_words # 1.5/2 count_words # Bug as noted! You could remove the empty words here # 2/2 print_descending # 2/2 comments and style # # GRADE: 7.5/8 # Nice work! import urllib.request as web def get_input(): input_url = input("What url do you want to use?") re...
""" anagrams.py What anagrams can be found among 1000 common words in US English? To find out, debug the definition of the find_anagrams function below. In addition to fixing the code, add two comments as follows: # BUG: Show where you found the bug and explain how you found it. # FIX: Briefly explain in English how y...
import math def distance (x1, y1, x2, y2): """ this fuction finds the distance between two points Parameters: """ distance = math.sqrt(((x2 - x1)**2) + ((y2 - y1)**2)) return distance print(distance(0, 0, 4, 0)) def tri_perimeter(x1, y1, x2, y2, x3, y3): side1 = d...
import random def weather (): chance = random.random() if chance < 0.66: print("SNOW") elif chance < 0.99: print ("SUNNY DAY") else: print("RAINS CATS AND DOGS!") def loaded(): chance = random.random() if chance < 0.25: roll = 1 elif chance < 0.50: ...
VOWELS = "aeiuo" def piglatin(word): return word[1:] + word[0] + "ay" def main(): print(piglatin("python")) print(piglatin("Janet")) print(piglatin("string")) if __name__ == "__main__": main()
import re def get_matching_words(regex): words = ["aimlessness", "assassin", "baby", "beekeeper", "belladonna", "cannonball", "crybaby", "denver", "embraceable", "facetious", "flashbulb", "gaslight", "hobgoblin", "iconoclast", "issue", "kebab", "kilo", "laundered", "mattress", "millennia", "natural", "obsessive", "par...
def layered(x): (arr, multiplier) = x newarr = [] for index in arr: insert = [] one = index * multiplier while one>0: insert.append(1) one = one - 1 newarr.append(insert) print newarr return newarr x = layered(([2,4,5],3))
''' Assignment: Names Part I: Given the following list: ''' students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] ''' Copy Create a program ...
# #Multiples - Part I for odd in range(1,1000,2): print odd # #Multiples - Part II for multiple in range(5,1000001,5): print multiple #Sum List sum = 0 arr = [1,2,5,10,255,3] for i in arr: sum+=i print sum #Average List sum = 0 arr = [1,2,5,10,255,3] for i in arr: sum+=i print sum/len(arr)
import matplotlib.pyplot as plt import numpy as np x = [1,2,3,4,5,6,7] y_product1 = [100,200,230,120,500,210,400] y_product2 = [212,323,124,213,102,222,320] plt.plot(x,y_product1) plt.plot(x,y_product2) plt.xlabel("days of week") plt.ylabel("sales of the day") plt.legend(["y_product1","y_product2"]) p...
blocks = [ [ 'bamba is awesome', 'this is it', 'programming is awesome' ], [ "i'm a beast", ] ] for i, block in enumerate(blocks): for j, phrase in enumerate(block): if 'awesome' in phrase: block[j] = phrase.replace('awesome', 'unbelievable') ...
"""Reversed. OBS: não confunda com a função reverse() que estudamos nas listas reverse() é uma função das listas somente A relação é parecida com sort() e sorted() Sua função é inverter o iterável A função reversed() retorna um iterável chamado List Reverse Iterator Pode usar em list, tuple, set, dicioná...
import matplotlib.pyplot as plt # rename as plt x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y = [2, 3, 5, 3, 4, 7, 9, 7, 10, 8] # Definido título do gráfico plt.title("Título do meu gráfico") # define o título # Definindo nome aos eixos do gráfico: plt.xlabel("Eixo X") # eixo x plt.ylabel("Eixo Y") # eixo y plt.plot(x,...
# Dicas de padrão de código bem escrito do Pep8 """ [1] - CamelCase para nome de classes. class CalculadoraCientifica: pass # pass para não fazer nada mas não gerar erro por falta de código [2] - Utilize nomes em minusculo, separados por underline para funções ou variáveis def soma(a,b): return a+b [3] - ...
"""Dictionary Comprehension.""" """ Comprehension com uso em dicionários Pense no seguinte: tupla é (), lsita é [], set é {} Mas dicionário tem chave e valor: dicionario = {'a': 1, 'b': 2} Sintaxe: {chave:valor for valor in iterável} Em lista seria [valor for valor in iterável] """ # Exemplo 1: numeros =...
""" POO - Propriedades (Properties). Getters e setters em conjunto da classe usada na aual de abstração e encaps.. Essa refatorando a classe anterior utilizando propriedades (decorators)!! @property para atributos, como se fosse um método Mas o acesso ao atributo é sem os paranteses!! Também do @atributo.setter, fun...
""" Type hinting. É a ideia de dar a ideia do tipo de dado recebido no parametro e do tipo de retorno. Entra no Python 3.5 Já faço uso desde o início do curso. É importante entender a tipagem dinâmica Ajuda e muito aos desenvolvedores e a IDE para ter um controle e visão melhor do que está aconte...
""" Operador Walrus. O operador Walrus permite fazer a atribuição e retorno em uma única expressão Apenas para garantir maior patricidade, não há nada novo Sintaxe: variavel := expressão Obs: precisa estar utilizando Python3.8+ para tal (atual 3.8.2) Quando você deve ou não usar este oepraodr: Quando você ...
""" Teste de memória com Generators. """ from typing import List def fib_lista(max: int) -> List[int]: """Retorna a sequencia de fibonacci.""" nums = [] a, b = 0, 1 while (len(nums)) < max: # Eqnt quantidade de elem. em nums < max nums.append(b) # Insere o elemento b na lista nums ...
""" Forçando tipos de dados com decoradores. Vamos ter uma aplicação prática do mesmo Mas com o objetivo de forçar os tipos de dados com os decoradores """ from typing import List def forca_tipo(*tipos): def decorador(funcao): def converte(*args, **kwargs): novo_args = [] fo...
""" Ordered dict, do módulo Collections """ dicionario = {'a': 1, 'b': 2, 'c': 3} for chave, valor in dicionario.items(): print(f'chave {chave}; valor{valor}') # Aqui manteve a ordem, mas isso não é garantido, para isso se tem o Ordered from collections import OrderedDict dicionario = OrderedDict({'a': 1, 'b'...
"""Generators. O que seria o "tuple comprehension" é chamado de generator expression Por isso tal coisa não foi estuda no collections Sintaxe: Igual ao de list, mas ao invpes de [] usa () Ou seja, deixar tudo entre () indica estar usando generators A partir de conversão e uso, aqui o dado tbm é apagado d...
""" Escrevendo em arquivos CSV Temos a mesma ideia que na leitura, utilização de duas formas: writer() -> utiliza um escritor para csv writerow() -> escreve uma linha DictWriter -> Utiliza um dicionário para escrever A forma de abertura varia conforme o contexto, aqui foi usado w por exemplific """ ...
"""Decatorators com diferentes assinaturas. # Para situações de dois parametros quando se espera um, temos o uso de: Decorator pattern É a ideia de utilizar os *args e **kwargs nos parametros Permitindo essa flexibilidade Lembrando que args lançam uma tupla e kwargs um dicionário """ # Relembrando: d...
''' Tipo Booleano, lá do George Boole 2 constantes: True e False Obs: sempre como inicial maiúscula ''' var1 = True var2 = False # Padrão: print (var1) # Negação: print(not var1) # Or (operação binária): print (var1 or var2) # Se um é verdadeiro, retorna True. Só retorna falso se ambos False # And (operação bi...
""" Named Tuples, o módulo collections Recap tupla: tupla = 1, 2, 3 É uma ideia de "tupla nomeada", são tuplas diferenciadas, em que especificamos um nome para a mesma e também parâmetros Fica bastante próximo de uma ideia de struct de C e tal, porém modificado no acesso Pois você define nome e todos os tipos dentr...
# analisando o crescimento da população brasileiro - datasus # Utilizando o arquivo .csv salvo na pasta # o arquivo csv atual está separado os dados por ";" import matplotlib.pyplot as plt dados = open("populacao_brasileira.csv").readlines() x = [] # armazena os anos y = [] # armazena a população for i in r...
#!/usr/bin/python print "Content-Type: text/html\n" f=open("lit.txt") r= f.read() f.close() print "<!DOCTYPE html>" print '''<html><head><title>Storify</title><style> body {background-size:100%}</style></head><body background = "https://media2.giphy.com/media/nYmXj4wLAgd7W/giphy.gif">''' print '''<a href="lit.txt">lit<...
class Node ( object ): def __init__ (self , v, n): self.value = v self.next = n class LinkedList ( object ): def __init__ ( self ): self.firstLink = None def add (self , newElement ): self.firstLink = Node ( newElement , self.firstLink ) def test (self , testValue ): currentLink = self.firstLink while c...
import math x1 = int(input('Enter x1--->')) y1 = int(input('Enter y1--->')) x2 = int(input('Enter x2--->')) y2 = int(input('Enter y2--->')) d1 = (x2-x1) * (x2-x1); d2 = (y2-y1) * (y2-y1); res = math.sqrt(d1+d2) print('Distance between two points:', res);
#Escribir un programa que pida al usuario un número entero positivo y muestre por pantalla la #cuenta atrás desde ese número hasta cero separados por comas. numero= int(input("Introduzca un numero entero positivo: \n")) while numero<0 : print("ERROR. Numero negativo") numero= int(input("Introduzca un numero e...
# Escribir un programa que guarde en una variable el diccionario {'Euro':'€', 'Dollar':'$', 'Yen':'¥'}, # pregunte al usuario por una divisa y muestre su símbolo o un mensaje de aviso si la divisa no está en el diccionario. diccionario= {'Euro':'€', 'Dollar':'$', 'Yen':'¥'} divisa= input("Introduce una divisa: ") pri...
#Almacenar las matrices A(1 2 3) B(-1 0) # (4 5 6) ( 0 1) # ( 1 1) #en una lista y muestre por pantalla su producto. #Nota: Para representar matrices mediante listas usar listas anidadas, representando cada vector fila en una lista. # Las tuplas son como las li...
#Escribir un programa que almacene las asignaturas de un curso (por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista, #pregunte al usuario la nota que ha sacado en cada asignatura, y después las muestre por pantalla con el mensaje En <asignatura> has sacado <nota> #donde <asignatura> es cada una ...