text
stringlengths
37
1.41M
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/submissions/ # # time: O(n^n) - generates a recursive tree for every entry # space: O(n) - only stores indexes and profit, but stores an index set for every root node class Solution: def maxProfit(self, prices: List[int]) -> int: return se...
#!/ usr/bin/env python #coding: utf-8 """ Author: Arnaud Ferré Contact: arnaud.ferre@u-psud.fr Date: 09/02/2017 Description: - A clean example of a Python script architecture for functions definition - Used to test commit command Licence: DSSL """ # Importations import math # Autres syntaxes/utilisations possibles :...
#! /usr/bin/python def maxsub(a): ''' This returns the sum of the maximum continuous subsequence. ''' if len(a) == 1: return a[0] left = a[:len(a)/2] right = a[len(a)/2:] return max( max(maxsub(left), sum(left)+lborder(right)), # Left max(maxsub(right), sum(right)+rborder(left)), # Right rborder(left) ...
a={1,2,3,4,5} b={4,5,6,7,8} print("the set value of a ",a) print("the set value of b ",b) a.difference_update(b) print("remove the intersection of 2nd set from set from the 1st set ",a)
#merged list of tuples from two lists l1=list(range(5)) l2=list(range(5,10)) t1=list(zip(l1,l2)) print(t1) #merge list and range to create list of tuples l=range(1,8) l1=["a","b","c","d","e"] print(list(zip(l,l1))) #sorting the list l=list(range(10,0,-1)) print(sorted(l)) #filter odd numbers l1=range...
#multiply two arguments z=lambda x,y:x*y print(z(2,5)) #fibonacci series def fib(n): r=[0,1] any(map(lambda _:r.append(r[-1]+r[-2]),range(2,n))) print(r) n=int(input("Enter number")) fib(n) #multiply a number to the list l=list(range(10)) l=list(map(lambda n:n*3,l)) print(l) #divisible b...
""" 2. Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. """ numero = int(input('Informe um número\n')) if numero >= 0: print('O número informado é positivo') else: print('O número informado é negativo\n')
""" 9. Faça um Programa que leia três números e mostre-os em ordem decrescente. """ numeros = set() while True: try: numero = int(input(f'Informe o {len(numeros)+1}º número\n')) numeros.add(numero) if len(numeros) == 3: break pass except ValueError: pass prin...
""" 26. Um posto está vendendo combustíveis com a seguinte tabela de descontos: Álcool: até 20 litros, desconto de 3% por litro acima de 20 litros, desconto de 5% por litro Gasolina: até 20 litros, desconto de 4% por litro acima de 20 litros, desconto de 6% por litro Escreva um algoritmo ...
""" 5. Faça um Programa que converta metros para centímetros """ metros = float(input('Informe a quantidade de metros\n')) print(f'{metros} metros equivale a {int(100*metros)} centimetros\n')
""" 25. Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são: "Telefonou para a vítima?" "Esteve no local do crime?" "Mora perto da vítima?" "Devia para a vítima?" "Já trabalhou com a vítima?" O programa deve no final emitir uma classificação sobre a participa...
"""Python Decorator Templated""" from functools import wraps, partial __all__ = [ 'base_decorator_func', 'base_decorator_func_with_args', 'BaseDecorator', ] def base_decorator_func(func): """Decorator function: This decorator overrides original 'function' and returns the wrapper function. ...
class Queue(object): def __init__(self): self.queue = [] def enqueue(self, val): self.queue.insert(0, val) def dequeue(self): if not self.is_empty(): self.queue.pop() else: print("underflow") def is_empty(self): return False if self.queue else True def travel(self): print(self.queue[-1::-1]...
import doctest class Square(object): """A square object""" def __init__(self, value): #requires value upon initialization self.up = None # default self.down = None # default self.left = None # default self.right = None # default self.value = value # taken in above ...
#RUSHIKESH BANDIWADEKAR, SE-IT, A-37 #Program to traverse through given dictionaries using for loop #Taking how many data/values user want to enter/add in dictionary n = int(input("Enter how many number of datas you want to add in dictionary : ")) #Creating empty dictionary d = {} #We take rolll number and name as k...
# coding: cp949 #money = 2000 money =int(input("󸶸 ֽϱ? ")) # input ޴° string ó #card = 1 <- ī θ ǴϹǷ ޸ #card = True card = input("ī带 ϰֽϱ? (y/n) :") if card == 'y': card = True else: card = False if money >= 3000: print("Űó ý м мմϴ."); print("м Ϸᰡ Ǿϴ."); print("ýø Ÿ ") elif card == T...
import os import time import random # --- NL = '\n' # --- GAMES_TO_PLAY = 10 SLEEP_TIME = 0.1 # --- players = [ { 'Name': 'Bob', 'Symbol': 'X', 'Wins': 0 }, { 'Name': 'Alice', 'Symbol': 'O', 'Wins': 0 } ] # Board stored as 3D char array board = [[' ' for i in range(3)] for j in ra...
#Nicolas Tracewell #ntracewe@ucsc.edu #programming assignment 3 #The program chooses a random number between 1 and 10 and gives the user three guesses to get it right, giving hints with each guess. import random x = random.randint(1,10) print("I'm thinking of an integer in the range 1 to 10. You have three guesses....
""" Takes an input label file and converts the labels currently as days (ints) into years (floats) """ input_file = open("/home/albert/Desktop/pic5_dataset/age/pic5_age_train.days.txt", "r") output_file = open("/home/albert/Desktop/pic5_dataset/age/pic5_age_train.years.txt", "w") lines = input_file.readlines() for...
import os import csv # Path to collect data budget_csv = os.path.join('budget_data.csv') # Read in the CSV file with open(budget_csv, 'r') as csvfile: # Split the data on commas csvreader = csv.reader(csvfile, delimiter=',') months = [] header = next(csvreader) net_pl = [] change_pl =...
import src.ETL.Person as p class Drink: def __init__(self, drink_type, drink_name, details, price, id=None): self.id = id self.drink_type = drink_type self.drink_name = drink_name self.details = details self.price = price def get_info(self): return f"#{self.id...
import matplotlib.pyplot as plt x1 = [1,2,3,4,5] y1 = [1,2,4,8,16] colors = ['green', 'red', 'blue', 'orange', 'lightgreen'] plt.bar(x1, y1, edgecolor='black', color = colors, linewidth = 3) plt.title("title") plt.xlabel("horizontal title") plt.ylabel("vertical title") plt.show()
#5-1 condition test car = 'subaru' print("is the car a 'subaru'? i predict true.") print (car == 'subaru') car = 'audi' print("\nis this car an 'audi'? i predict false") print (car != 'audi') name = 'peterson' print("\nis this persons name and 'peterson'? i predict true") print (car == 'peterson') car = 'peterson' ...
#5-8 hello admin names = ['admin', 'elgin', 'dylan', 'logan', 'keenan'] for name in names: if name == 'admin': print(f'hello {names[0]}, would you like to see a status report') if name == 'elgin': print(f'hello {names[1]}, thank you for logging in again') if name == 'dylan': print(f'hello {names[2]}, thank yo...
# Part I: Members, Students and Instructors # You're starting your own web development school called Codebar! Everybody at Codebar -- whether they are attending workshops or teaching them -- is a Member. class Member: def __init__(self, full_name): self.full_name = full_name def hello(self): pri...
from itertools import chain, combinations def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return list(chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))) def subsequentset(iterable): sset = [] s = list(iterable) ...
# Three-Dimensional Object # # This is a container class for three-dimensional objects. # # Last Modified 2013.01.13 22:24 # import ThreeVector class ThreeDimensionalObject: def __init__(self, X1 = 0, X2 = 0, Y1 = 0, Y2 = 0, Z1 = 0, Z2 = 0): self.X1 = X1 self.X2 = X2 self.Y1 = Y1 self.Y2 = Y2 se...
valor_lado = int(input('Por favor ingrese el valor del lado: \t')) area = valor_lado * valor_lado perimetro = valor_lado + valor_lado + valor_lado + valor_lado print(f'El area es: {area}') print(f'el area del perimetro es: {perimetro}')
def line_break(x): print(str(x) + '---------' + str(x) + '---------' + str(x) + '---------' + str(x) + '---------') lb = line_break ''' ~appendix * this is the first note on building a python flask application * ~lb(0): flask is fun: what is going on here? ~lb(1): starting the flask app ~lb(2): updatin...
from typing import List class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: res = sorted(nums1 + nums2) mid = (len(res) - 1) // 2 print(res[mid]) return res[mid] if len(res) % 2 != 0 else (res[mid] + res[mid + 1])/2 print(Solution().find...
variable_creator = dict() for x in range(5): x = input("enter in your variable name:") y = input("enter its value:") variable_creator[x] = y x = "" y = "" print(variable_creator) n = input("which one do you want to access") print(variable_creator[n])
x=12 y=5 z=123 print(max(x,y)) print(min(z,y)) print(abs(-12)) print(pow(21,21)) print(round(3123.3223)) from math import * print(floor(3.678) , floor(3.2134) , floor(4)) print(ceil(3.6454) , ceil(3.4122) , ceil(3)) print(sqrt(25)) print(1)
# A string is an immutable, ordered, and it is represented by text # A string can be written in all these different ways and all have their own advantages # like the single quote one is easy # double quote help if you want to throw in a single quote # triple quote are used for multiple lines # var1 = 'Hello Wor...
import student # main functions section def addNewStudent(): def setStudentNo(): studentNo_ = input("3 reqemden ibaret telebe nomresini daxil edin: ").strip() if studentNo_.isdigit() and len(studentNo_) == 3: for s in student.userList: if s.studentNo == studentNo_: ...
N = input() if N < 60: print "Bad" elif N < 90: print "Good" elif N < 100: print "Great" else: print "Perfect"
# Get inputs from user print("Hi! I need a couple of inputs from you to make your experience jovial. So let's start then by hitting ENTER :)") name1 = input("Name: ") nickname = input("Nick Name: ") adjective1 = input("Adjective: ") verb1 = input("Verb: ") verb2 = input("Verb: ") famous_character1 = input("Famous Cha...
import math import random # string functions string = 'Monty Python' length = len(string) print("String = ",string,"\tlength = ",length) rep = string.replace('n','N') print(rep) upper = string.upper() lower = string.lower() print(upper) print(lower) # data functions character = 'A' ordchar = ord(chara...
import collections def TupleAssign(): (x,y,z) = ("python", "is", "Number 1") return x,y,z def TupleMinMax(tup): mn = min(tup) mx = max(tup) return mn,mx def TupleIndex(tup,val): y = tup.index(val) return y def TupleLen(tup): y = len(tup) return y ...
# Copyright (c) 2020. Adam Arthur Faizal from sys import copyright print("====== IMPLEMENTASI FUNGSI RANGE ======\n") print("--- Bagian 1 --- (Menampilkan rentang nilai)") # Menampilkan rentang nilai awal = int(input("Masukkan nilai awal : ")) akhir = int(input("Masukkan nilai akhir : ")) pembaruan = int(input("Mas...
# Copyright (c) 2020. Adam Arthur Faizal from sys import copyright print("====== WHILE LOOP ======\n") angka = 0 while angka < 10: print("Nilai angka adalah :", angka) angka += 1 print("Di luar while") angka2 = 0 start = True while start: print("Nilai angka2 adalah :", angka2) angka2 += 1 if angk...
# Courses # Login/Signup # Palindrome or not? # Palindrome wo strings ya numbers hote hai jo ulta seedhe same hote hai. # Jaise, NITIN. Nitin ko aap left se padho ya right se, nitin hi hai. Aise hi MOM bhi ek # palindrome hai. Code likho jo check kare ki kya list palindrome hai ya nahi. Aur print karo # “Haan! pali...
# duplicates # Duplicates # iss lists mei se duplicates nikal kar, kisi aur list mei daal kar print karne hai. a= [19, 17, 12, 17, 17, 18, 10, 17, 14, 12, 19, 17, 12, 13, 11] i=0 b=[] # count=0 while i<len(a): l=a[i] if l not in b: b.append(l) # count=count+1 i=i+1 print(b)
# Courses # Login/Signup # aao-jodein # Aao Jodein # Ek code likho jo kissi bhi list ke liye uss list ke do sum ka output karta hai, ki uss # list mei odd numbers ka sum aur even numbers ka sum kitna hai. elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43] a=[] sum1=0 i=0 sum=0 s=[] while i<len(elements): n...
# Author: Omar Shehab # Email: shehab1@umbc.edu # Date: May 4, 2017 # This program uses the Forest API from the Rigetti Quantum Computing # to solve a few challenge problems as a part of the interviewing process. # The author has tried to use as few quantum gates as he can. # This program is written for Goal 4. # Go...
# Author: Omar Shehab # Email: shehab1@umbc.edu # Date: May 4, 2017 # This program uses the Forest API from the Rigetti Quantum Computing # to solve a few challenge problems as a part of the interviewing process. # The author has tried to use as few quantum gates as he can. # This program is written for Goal 3. # Go...
# On importe une librairie pour choisir un nombre aleatoire : import random # On cree une variable nombre_cacher # On y stock un nombre aleatoire en entre 0 et 100 # on fait appel a la fonction randint qui se trouve dans random nombre_cacher = random.randint(0, 100) print("Tape un nombre entre 0 et 100") entree_jou...
import itertools from functools import reduce from typing import Set, List, Mapping from utils import NumType def get_primes_divisors(num: int) -> List[int]: prime_divisors = list() inner_num = num while inner_num % 2 == 0: prime_divisors.append(2) inner_num = int(inner_num / 2) for ...
todolist = [] while True: print("Welcome to my To-Do List\n") print("1)Add an item\n2)Mark an item as done\n3)View the list\n4)quit") choice = int(input("enter your choice\n")) if choice == 1: data = input("what do you want to add?") todolist.append(data) elif choice == 2: ...
from xmltodict import parse import json def create_file_name(filename): """ change name from xml to json name """ sep = filename.split('.') name = './' + './' + '/' + sep[0] + '.json' return name, sep filename = input('file name(INPUT WITH .xml): ') file = open(filename).read() diction = pa...
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': gmail_regex = re.compile("^[a-z\.]+@gmail.com$") gmail_accounts = dict() N = int(input().strip()) for _ in range(N): firstName, email = input().strip().split(' ') if gmail_regex.match(e...
############################################################ # Code for reading a textfile and calculating mean values # # Useful when calcualte the mean cross-section # ############################################################ # --data file f1name='xsec.dat' # --read file f = open(f1name,'r') lines = f.r...
from random import randint i = 0 num = randint(0, 20) for i in range(3): print(i) i += 1 answer = input("Pick a number") if (int(answer) == num): print("Congrats!") break elif (int(answer) > num): print("Guess lower.") elif (int(answer) < num): prin...
class Class1: def __init__(self, obj): self.obj = obj def print(self): print(self.obj.x) class Class2: def __init__(self): self.x = 5 g = Class2() h = Class1(g) h.print()
from constants import * from vector import Vector def draw_text(screen, text, color, x, y): ''' Draws a text on the desired position ''' # Puts the text into a surface text_surface = FONT.render(text, True, color) # Creates a rect object at the desired position text_rect = text_surface.g...
print(""" ************************************** ** Welcome to the Snakes Cafe! ** ** Please see our menu below. ** ** ** To quit at any time, type "quit" ** ************************************** Appetizers ---------- Wings Cookies Spring Rolls Entrees ------- Salmon Steak Meat Tornado A Literal Garden D...
import sys import random #GLOBAL VARIABLES arr_init = [] arr = [] current_line = -1 def draw(rows): width = rows*2 + 1 print('*'*width) for i in range(rows): if arr[i] < arr_init[i]: k = arr_init[i] - arr[i] else: k = 0 print('*' +' '*(rows-i...
'''this piece of code shows the basic idea of polymorphism: you can see that we pass objects of different classes(duck and human) at run-time to the same function, and it performs different behaviors based on the object type. This is called polymorphism(multi-behavior)''' class duck: def talk(self): print...
import pygame class Shape: def __init__(self, x, y, xSpeed, ySpeed, color): self.x = x self.y = y self.xSpeed = xSpeed self.ySpeed = ySpeed self.color = color def move(self): self.x = self.x + self.xSpeed self.y = self.y + self.ySpeed def show(self,...
from collections import defaultdict SPACE = ' ' def findRoot(employers): #finding node with no in-edges i.e not present in RHS root = list(employers.keys())[0] for key, values in employers.items(): for child in values: if child == root: root = key return root de...
# First we'll import the os module # This will allow us to create file paths across operating systems import os # Module for reading CSV files import csv # path for budget data csvpath = os.path.join('Resources', 'budget_data.csv') # Variables that will be needed for the summary runningprofit = 0 currentprofit = 0 i...
class Node: def __init__(self, data = '', prev = None, next = None): self.data = data self.prev = prev self.next = next class DLL(Node): def __init__(self): self.head = None self.tail = None self.current = None self.size = 0 def __str__(self): ...
import random class Pizza_slice(object): def __init__(self): self.__topings = self.add_topings() self.__ID = '' def add_topings(self): topping_list = ['Pepperoni', 'Mushrooms', 'Onions', 'Sausage', 'Bacon', 'Extra cheese', 'Black olives', 'Green peppers'] Out_put_list = [] ...
from tkinter import * from tkinter.colorchooser import * from tkinter.simpledialog import * ## 함수 선언 부분 ## def mouseClick(event): global x1, y1, x2, y2 x1 = event.x y1 = event.y def mouseDrop(event): global x1, y1, x2, y2, penWidth, penColor, penStyle x2 = event.x y2 = event.y if penStyl...
import csv from tkinter.filedialog import * ## 우리회사 평균 연봉은? filename = askopenfilename( parent=None, filetypes=(("CSV 파일", "*.csv"), ("모든 파일", "*.*"))) csvList = [] with open(filename) as rfp: reader = csv.reader(rfp) headerList = next(reader) sum = 0 count = 0 for cList in reader: cs...
'''To Do: This will be an exe, just run it to get gui and work from there. ''' import tkinter as tk from tkinter import messagebox import generator as gen #####Functions that will be used def get_evaluation(): """ get evaluation from entry fields """ dim = int(enter_dim.get()) ...
import random def generate_cipher(): return random.sample(range(10), 4) def get_bulls_and_cows(cipher, guess): assert len(cipher) == len(guess), 'the arguments must be the same length' bulls = 0 cows = 0 for i in range(len(cipher)): if guess[i] == cipher[i]: bulls += 1 ...
""" 2 A Python implementation of GPS related time conversions. 3 4 Copyright 2002 by Bud P. Bruegger, Sistema, Italy 5 mailto:bud@sistema.it 6 http://www.sistema.it 7 8 Modifications for GPS seconds by Duncan Brown 9 10 PyUTCFromGpsSeconds added by Ben Johnson 11 12 This pro...
#sorting numpy array import numpy as np; #single dim array sd=np.array([100,20,45,90,44,10,25]); print(np.sort(sd)); #sorting in ascending order print(np.sort(sd)[::-1]);#sorting and slicing in reverse direction (desc order) print("__________________________________________________________"); md=np.array([[20,...
#asarray function is like array #it can create an ndarray from list,tuple etc import numpy as np; list=[10,20,30]; tuple=(40,50,60,70); npa1=np.asarray(list); npa2=np.asarray(tuple); npa3=np.asarray(tuple,dtype=float); print(npa1); print(npa2); print(npa3);
from array import array tab = array('i', [1, 3, 5, 7, 9]) for i in range (0,len(tab)): print(tab[i]) def somme(tab): somme = 0 for i in range (0,len(tab)): somme += tab[i] return somme print("somme : ", somme(tab))
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import numpy as np arr1 = np.array([1, 2, 3]) # 共享一块内存 arr2 = arr1 arr2[0] = 5 print(arr1) print(arr2) # [5 2 3] # [5 2 3] # 深拷贝 arr3 = arr1.copy() arr3[0] = 6 print(arr1) print(arr3) # [5 2 3] # [6 2 3]
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 生成随机数的方式 import numpy as np # 生成3行2列从0到1的随机数 sample = np.random.random((3, 2)) print(sample) # [[0.94800964 0.91867228] # [0.3680591 0.14434706] # [0.33398542 0.50719141]] # 生成3行2列符合标准正态分布的随机数 sample2 = np.random.normal(size=(3, 2)) print(sample2) # [[ 0.22708609 -...
#Ex 4.1 #a def print_list(elements): print(elements) #b def print_reverse(elements): print(list(reversed(elements))) #c def len_function(elements): count = 0 for index in elements: count += 1 return count #Ex 4.2 def set_first_elem_to_zero(l): l[0] = 0 return l #Ex 4.4 def set_in...
texto = "oi, eu sou a Urias" print(len(texto)) print(texto.upper()) print(texto.lower()) print(texto.capitalize()) print(texto.title())
#O programa pede para o usuário dois numeros e realiza a soma deles numero1 = int(input("Informe um valor:")) numero2 = int(input("Informe outro valor:")) resultado = numero1 + numero2 print("O resultado da soma é:", resultado)
entrada = "Pabllo;Urias;McTha;Dudinha" #Estrutura for for nome in entrada.split(";"): print(nome.upper())
#Fatiamento de string palavra = "Victoria Medej" #Para mostrar apenas uma letra da palavra (Ver a posição da letra) letra = palavra[3] print(letra) #Para mostrar um conjuto de letras de uma string letras = palavra[0:5] print(letras) #Para mostrar da posição escolhida até o final letras = palavra[5:] print(letras) #...
#Programa valor = 0 contador = 0 while contador < 7: valor = valor + (valor / 2) + 4 if valor % 2 == 0: print (valor) else: print (valor//2) contador = contador + 1 #Resposta 4 10 9 16 26 41 64
print("Olá mundo!") #Isso é um comentário e não sera executado #A função input() sempre retorna uma string/texto nome = input("Digite o seu nome: ") print("Olá", nome)
valor_total = float(input("Informe o valor do produto: ")) quantidade_parcelas = int(input("Informe a quantidade de parcelas: ")) if quantidade_parcelas == 1: valor_final = valor_total * 0.9 elif quantidade_parcelas == 2: valor_final = valor_total elif quantidade_parcelas == 3: valor_final = valor_total * 1.05...
#Estrutura de repetição numero_secreto = 13 acertou = False while acertou == False: chute = int(input("Informe seu chute: ")) if chute > numero_secreto: print("O número é menor") elif chute < numero_secreto: print("O número é maior") else: acertou = True print("Acertou!") print("Obrigada por...
numero1 = int (input ("informe um numero: ")) numero2 = int (input ("informe outro numero: ")) soma = numero1+numero2 print ("o resultado é: ", soma)
import tkinter import random window = tkinter.Tk() def Random_Number(): My_Random = random.randint(1,20) dice_thrown.configure(text = "Rolled: " + str(My_Random)) MyTitle = tkinter.Label(window, text = "DnD Dice Roller", font = "Arial 16") MyTitle.pack() MyButton = tkinter.Button(window, text = "Roll", comm...
# -*- coding: utf-8 -*- """ Created on Tue Jan 22 16:47:12 2019 @author: harsh """ #Program to reverse the string o(n) def reverseString(s1): print(len(s1)) reverse="" for i in range(0,len(s1)): reverse=s1[i]+reverse print(reverse) reverseString('Harsa') #Duplicates alphabe...
# -*- coding: utf-8 -*- """ Created on Wed Sep 15 11:33:03 2021 @author: karth """ # Create class "Patient" class Patient: # Constructor def __init__(self, name, bloodgrp, address, branch): self.name = name self.bloodgrp = bloodgrp self.address = address self.branch = branch # Functio...
def minCutsPalindrome(string): n = len(string) # dp for palindrome. pal[i][j] is true if string[i] to string[j] is a palindrome pal = [[False]*n for i in range(n)] for i in range(n): pal[i][i] = True # dp for mincuts. cuts[i][j] stores minimum cuts needed for string[i] to string[j] ...
my_list=[5,10,15] print(list(map(lambda i: i*i, my_list))) #square bitches lingo=[(0,2),(4,3),(10,-1)] # sorting a tuple or dictorinary!!! lingo.sort(key=lambda x: x[1]) print(lingo)
class Pets(): animals = [] def __init__(self, animals): self.animals = animals def walk(self): for animal in self.animals: print(animal.walk()) class Cat(): is_lazy = True def __init__(self, name, age): self.name = name self.age = age def walk(self...
# dummy import example # import statement does not require .py extension # a folder containing modules is called a package # the files in the folder are called modules # imported as module import utility # imported as package.module import ex_folder.multiply # another way to write this is # import * will import all...
# range() # return an object that produces a sequence # of intergers from start to stop for number in range(0, 10): print(number) for _ in range(10, 0, -1): print(list(range(10)))
# walrus operator # := # assigns values to variables as part # of a larger expression a = 'hello' if (len(a) > 4): print(f'too long {len(a)} elements') # using the walrus operator if ((n := len(a)) > 4): print(f'too long {n} elements') while ((n := len(a)) > 1): print(n) a = a[:-1] print(a)
# built in functions print(len('012345678')) # -> 9 greet = "hello" print(greet[0:len(greet)]) # methods # methods that can be used only on strings # .format() # this is a method quote = 'to be or not to be' print(quote.upper()) print(quote.capitalize()) print(quote.find('be')) # -> 3 finds index print(quote.repla...
# error handling # errors in python # an error that crashes a program is called an exception # SyntaxError denotes a non standard python syntax error # NameError denotes a name or variable that is undefined # IndexError indicates an index is nonexistant # KeyError indicates a key in a dictionary that does not exist #...
# dictionary # dict # dictionary = { # 'KEY': VALUE, # 'KEY': VALUE # } # dictionary keys may be expressed as int str bool # they must be immutable # keys must be unique # if keys are not unique, the latter value will override dictionary = { 'a': 1, 'b': 2, 'c': 3 } print(dictionary['b']) # prints...
n = int(input()) string = input() o_number = 0 zeros = 0 ones = 0 ans = "" for char in string: if char == 'o': o_number += 1 elif char == 'z': zeros += 1 ones = o_number - zeros while ones > 0 or zeros > 0: if ones: ans += "1 " ones -= 1 elif zeros: ans += "0 ...
n = int(input()) ans = "" for current in range(1, n+1): if current % 2 == 1: ans += "I hate " else: ans += "I love " if current == n: ans += "it" else: ans += "that " print(ans)
#!/usr/bin/python # # 12tweet - tiny little robots that live in the twittersphere # Created by Jeff Verkoeyen @featherless # # The brains of a basic twitter bot. Does little more than print # all tweets for the given twitter user. # import twitterbot import random class Bot(twitterbot.StandardBot): '''A generic t...
Exercise 1 print("Hello, World!") Exercise 2 mystring = "hello" myfloat = 10.0 myint = 20 if mystring == "hello": print("String: %s" % mystring) if isinstance(myfloat, float) and myfloat == 10.0: print("Float: %f" % myfloat) if isinstance(myint, int) and myint == 20: print("Integer: %d" % myint) Exerci...
""" Module to manage AFW (Alternating Finite automaton on Words). Formally a AFW (Alternating Finite automaton on Words) is a tuple :math:`(Σ, S, s0, ρ, F )`, where: • Σ is a finite nonempty alphabet; • S is a finite nonempty set of states; • :math:`s0 ∈ S` is the initial state (notice that, as in dfas, we have...
""" Module to manage NFA (Nondeterministic Finite Automata). Formally a NFA, Nondeterministic Finite Automaton, is a tuple :math:`(Σ, S, S^0 , ρ, F )`, where • Σ is a finite nonempty alphabet; • S is a finite nonempty set of states; • :math:`S^0` is the nonempty set of initial states; • F is the set of accepting ...