text
stringlengths
37
1.41M
import re list_tens_2 = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] list_tens = ['', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] list_ones = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', '...
import math import os masses = open('./input.txt','r').readlines() masses = [ int(m) for m in masses] def compute_fuel(mass): assert type(mass)==int return math.floor(mass/3)-2 def compute_extra_fuel(mass): assert type(mass)==int extra_fuel = compute_fuel(mass) actual_fuel = 0 while extra_fue...
print ("Ternary Operator") print (""" Ternary Operator atau operator rangkap tiga ini adalah kondisional yang ditulis dengan lebih hemat. Tetapi struktur yang dapat dibuat hanya if dan else saja. Operator ini ditulis didalam variabel. rumus : var1 = 'statement1' if 'kondisi' else 'statement2' """) total_belanja_A...
print ("If Statement") print (""" Dalam algoritma kita mengenal pilihan. Untuk mewujudkan pilihan atau bisa juga kondisional kita akan menggunakan if. Cara kerjanya, kita harus tetapkan dulu suatu kondisi A yang akan melaksanakan perintah A, dan kalau tidak memenuhi kondisi A, maka akan melakukan perintah yang la...
print("Elif Statement") print(""" Elif statement memungkinkan kita membuat kondisional lebih dari 1, sebelumnya kita tau if dan else. Dengan adanya elif, kita dapat membuat banyak kondisi dengan banyak reaksinya. rumus penggunaan : if 'kondisi A': 'reaksi A' elif 'kondisi B': 'reaksi B' elif 'kondisi C': ...
print("____Taş,kağıt,makas oyununa hoşgeldiniz____") player_1=input("1.oyuncu Lütfen adınızı giriniz:" ) player_2=input("2.oyuncu Lütfen adınızı giriniz:" ) player_1skor=0 player_2skor=0 tur=1 while tur<11 : player_1_answer = input("%s,Taş(T),Kağıt(K),Makas(M) hangisini seçmek istersiniz?" % player_1) ...
''' Created on Dec 15, 2010 @author: Michael Kwan ''' import numpy as np from matplotlib import pyplot def closest_feature(map, x): '''Finds the closest feature in a map based on distance.''' ind = 0 mind = np.inf for i in xrange(len(map)): d = np.sqrt(np.power(map[i, 0] - x[0], 2) + np.power(map[i, 1]...
""" This library act as interactive bridge between user and code. It contains higher level functions which are used to train models * learn - returns trained model to generate new images """ import pickle from gimmick import mapping from gimmick.image_op import functions as image_functions from sklearn.model_sel...
calories = [int(x) for x in input().split()] string = [str(x) for x in input()] result = 0 for i in range(len(calories)): result += calories[i]*string.count(str(i+1)) print(result)
pn = 0 ss = "" pw = 1 anton = 0 danik = 0 print("Enter no. of playing") pn = int(input()) while pw <= pn : print(f"Enter {pw} of playing") ss = input() if ss == "A": anton+=1 elif ss == "D": danik+=1 pw+=1 if anton > danik: print("Anton Won") elif anton < danik: print("D...
# When the attacker's die value is larger: Attacker wins (1 defender unit dies) # When the 2 dice value is tie: Defender wins (1 attacker unit dies) # When the defender's die value is larger: Defender wins (1 attacker unit dies) # Attacker: Lost x units # Defender: Lost x units import random # print(random.randrange(1...
from turtle import Turtle class Scoreboard(Turtle): player = 0 computer = 0 def __init__(self): super().__init__() self.shape("circle") self.hideturtle() self.pencolor("cyan") self.penup() self.goto(0, 360) self.write(f"Score : {self.computer} | Score : {self.player}", align="center", font=("Ar...
from turtle import Turtle class Player(Turtle): def __init__(self): super().__init__() self.shape("turtle") self.pensize(3) self.pencolor("white") self.fillcolor("white") self.penup() def move(self, dirc): if dirc == "w": self.forward(2.5) else: self.back(2.5)
fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue if x == "cherry": break print(x) else: print("We have reached the end.") for x in range(6): print(x) else: print("Finally finished!")
from turtle import Turtle class Plate(Turtle): def __init__(self, side): super().__init__() self.shape("square") self.pensize(5) self.shapesize(1,5,1) self.left(90) self.pencolor("white") self.fillcolor("white") self.penup() self.goto(side * 360, 0) def move_up(self): self.forward(5) def move...
import random import math # Limits lower = int(input("Enter Lower bound:- ")) upper = int(input("Enter Upper bound:- ")) # Prep generated = random.randint(lower, upper) expected = math.ceil(math.log(upper - lower + 1, 2)) guesses = 0 guess = lower - 1 # Game while generated != guess: guess = int(input("Guess a numb...
#This exercise is to become more familiar with variables # and printing in python my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' #Insert a string variable into a string print "Let's talk about %s." % my_name #Ins...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] 前序遍历 :type inorder: List[int...
# -*- coding:utf-8 -*- class Solution: def maxInWindows(self, num, size): # write code here start = 0 end = start + size max_list = [] if len(num) < size or size==0: return [] while(end<=len(num)): max_list.append(max(num[start:end])) ...
# -*- coding: utf-8 -*- """ Created on Thu Feb 14 12:54:15 2019 @author: Killer1 """ import pandas as pd import matplotlib.pyplot as plt import numpy as np datos = pd.read_csv("student.csv") """ print(datos.dtypes) print(datos.info()) print(datos.describe()) print(datos.head()) """ df1=datos.loc[(d...
from cs50 import get_int # Our main funcion def main(): # continue forever while True: height = get_int("Height: ") # does the input match our range if height <= 8 and height > 0: # draw it if it does mario(height) # end the loop break ...
#!/usr/bin/env python """ Implementation of a PID controller. Assignment 4, in3140 """ import rospy import math class PID(object): def __init__(self): # Proportional constant self.p = 0.0 # Integral constant self.i = 0.0 # Integral accumulation variable self.integ...
#!/usr/bin/python3.6 # Exercise 30: Else and If people = 30 cars = 40 trucks = 15 if cars > people: print("We should take the cars.") elif cars < people: print("We should not take the cars.") else: print("We can't decide.") if trucks > cars: print("That's too many trucks.") elif trucks < cars: print("Maybe we ...
#Functions holding the answers def founder_name(): name = "Fred Swaniker" return name.lower() def year_founded(): return 2015 def campus(): campuses = "Rwanda and Mauritius" return campuses.lower() def number_of_campus(): return 2 def dean_name(): dean = "Gaidi Faraj" return dean....
#Write your code here class Patient: def __init__(self,name,age,weight,height): self.name = name self.age = age self.weight = weight self.height = height def print_details(self): print("Name:",self.name) print("Age:",self.age) print("Weight",self....
#Check if all alphabets are present def checkletters(): for alphabet in alphabets: if alphabet not in strupper: return 'The input string does not contains all alphabets' return 'The input string contains all alphabets' #Take input str= input('Please enter a string of your choice') #convert to upper case s...
from fastNLP import Vocabulary from fastNLP import DataSet # 问题:fastNLP虽然已经提供了split函数,可以将数据集划分成训练集和测试机,但一般网上用作训练的标准集都已经提前划分好了训练集和测试机, # 而使用split将数据集进行随机划分还引来了一个问题: # 因为每次都是随机划分,导致每次的字典都不一样,保存好模型下次再载入进行测试时,因为字典不同导致结果差异非常大。 # # 解决方法:在Vocabulary增加一个字典保存函数和一个字典读取函数,而不是每次都生成一个新字典,同时减少下次运行的成本,第一次使用save_vocab() # 生成字典后...
class Instance(object): """An Instance is an example of data. Example:: ins = Instance(field_1=[1, 1, 1], field_2=[2, 2, 2]) ins["field_1"] >>[1, 1, 1] ins.add_field("field_3", [3, 3, 3]) :param fields: a dict of (str: list). """ def __init_...
# the list "students" is already defined # students = [["Will", "B"], ["Kate", "B"], ["Max", "A"], ["Elsa", "C"], ["Alex", "B"], ["Chris", "A"]] top_students = [student[0] for student in students if student[1] == "A"] # # top_students = [] # for student in students: # if student[1] == "A": # top_students.ap...
# solution uploaded to # https://repl.it/@MikaMusic/NoxiousAdmiredBlogs#mean_var_std.py import numpy as np # list = [0, 1, 2, 3, 4, 5, 6, 7, 8] def calculate(list): '''this function will convert a list to a 3-by-3 matrix (fixed-size) and return statistics mean, var and std vor each column, line and the flat...
import timeit import sympy import numpy from part1_output import Output from equations_util import create_dataframe_part2 import timeit import equations_util from part1_output import Output def _eliminate(system: sympy.Matrix, i, j): """ Performs forward eliminates on a row inside a system of linear equatio...
# @Author: Akash Raj # @Date: 2020-01-07 12:37:55 # @Last Modified by: Akash Raj # @Last Modified time: 2020-01-07 12:38:33 # # https://www.interviewbit.com/problems/power-of-two-integers/ # # Given a positive integer which fits in a 32 bit signed integer, find if it can be expressed as A^P where P > 1 and A...
import test # this stack implementation assumes that the end of the list # will hold the top element of the stack. as the stack grows(push) # new items will be added on the end of the list. pop operations # will manipulate that same end class Stack(): # 0(1) append and pop # will perform in constant time no m...
def ana_of_pal(str): """ is the word an anagram of a palindrome? """ seen = {} # count each letter for letter in word: cound = seen.get(letter, 0) seen[letter] = count + 1 # it's a palindrome if the number of odd counts is 0 or 1 seen_an_odd = False for count in seen.val...
""" write a function fib() that takes an integer n and returns the nth fib number""" # o(n2) # each call to fib makes 2 more calls # draw it out - forms a binary tree # exponential time cost # recurrence tree gets twice as big each time u add 1 to n def fib(n): if n in [1, 0]: return n else: re...
# 0(n2) # stop if the lst is sorted def bubble_sort(lst): exchanges = True passnum = len(lst) - 1 while passnum > 0 and exchanges: exchanges = False for i in range(passnum): if lst[i] > lst[i+1]: exchanges = True lst[i], lst[i+1] = lst[i+1], lst[i...
"""You're given a list that contains the prices of a stock during one trading day, at 1 minute intervals. The list is chronologically ordered. You want to buy and sell the stock the same day, and maximize your profit. Write a method that takes the list and returns the time to buy and time to sell in order to maximiz...
class Item(): """The Base Class for all the loot and magical nonsense""" def __init__(self, name, description, value): self.name = name self.description = description self.value = value def __str__(self): return "{}\n=====\n{}\nValue: {}\n".format(self.name, self.description...
from decimal import * import platform import os import struct def get_integer_input(prompt): while True: try: res = int(input(prompt + ': \n')) break except (ValueError, NameError): print("Por favor, digite um número inteiro, de acordo com o menu exibido.") ...
from decimal import * # Decimal precision. getcontext().prec = 15 #----------------------------------------------------------- # Tool to convert GPS coordinates. # Degrees-minutes-seconds to decimal degree, vice-versa. #----------------------------------------------------------- def dms_to_deci_deg(dms_coord): ...
class Solution: def toLowerCase(self, s: str) -> str: return s.lower() # Solved using ascii code ''' approach: - check every character of string is Uppercase or not - if character is upper case then convert it to lowercase - else do nothing ''' class Solution: def toLowerCase(self, s: str) -> str: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Student(object): def __init__(self,name): self.name = name def __str__(self): return 'student object (name = %s)' % self.name __repr__ = __str__ print (Student('Michael')) class Fib(object): def __init__(self): self.a, self.b...
# Functions for running an encryption or decryption algorithm ENCRYPT = 'e' DECRYPT = 'd' # Write your functions after this comment. Do not change the statements above # this comment. Do not use import, open, input or print statements in the # code that you submit. Do not use break or continue statements. def c...
a=[1,2,3,[4,[5,6,[7]],8],[9]] b=[] def fun(a): for i in a: if type(i)==list: fun(i) else: b.append(i) print(a) fun(a) print(b)
import random from node import Node ####################################################################################################### ####################################################################################################### class Stack: def __init__(self, limit=1000): # only as an exercise, a ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 5 12:43:39 2019 @author: danielacamacho """ from graphics import * initial_instructions= 'Click on the item where you would like to begin! Here’s a hint: Jed would probably be the best place to start because Jed knows all. \nBe sure to keep track...
#!/usr/bin/env python #======================================================================# # Logic-2 # # Medium boolean logic puzzles -- if else or not. # #======================================================================# # m...
#!/usr/bin/env python #======================================================================# # List-1 # # Basic python list problems -- no loops. Use a[0], a[1], ... to # # access elements in a list, len(a) is the length. # #====...
from nltk.corpus import stopwords from nltk.tokenize import word_tokenize stopwords = list(stopwords.words('english')) numbers = list(range(0, 100)) #numbers that is identifiers of pages forumSpecificWords = ['>', '<', '?', '[', ']', '*'] + numbers #special signs stopwords += forumSpecificWords print('All t...
import turtle t = turtle.Turtle() t.color("cyan") for side in range(19): t.forward(side *10) t.right(120)
def word_triangle(word): length = len(word) for n in range(length): print(word[:length-n]) word_triangle("Pineapple")
# Example of if/else statement import turtle oz = turtle.Turtle() oz.width(5) for side in range(4): if side == 1: oz.color("white") else: oz.color("red") jack.forward(100) jack.right(90)
# Strings are ordered sequence of characters # Strings: s = 'Hello world' # String methods: Upper(), Lower(), Split() # v1 print('The result was {}'.format(3.14)) # v2 {value:width.precision f} print('The result was {r:1.3f}'.format(r=3.14)) # Lists are ordered sequence of objects (mutable) # Lists: l = ['STRING', 100...
# File name: creditCardValidator.py # Description: Script for credit card validation # Author: Juris Tihomirovs # Date: 28-05-2021 def check_luhn(number): num_list = [] # Create digit list - iterate through string and add items to list for num in number: num_list.append(int(num)) # From end ...
# Goal: Get title of every book with a 2 star rating import bs4 import requests base_url = 'http://books.toscrape.com/catalogue/page-{}.html' res = requests.get(base_url.format(1)) soup = bs4.BeautifulSoup(res.text, 'lxml') products = soup.select('.product_pod') example = products[0] # We can check if something is 2 ...
import datetime mytime = datetime.time(2, 20, 1, 20) print(mytime) print(mytime.hour) print(mytime.minute) print(mytime.second) print(mytime.microsecond) today = datetime.date.today() print(today) print(today.year) print(today.month) print(today.day) print(today.ctime()) mydatetime = datetime.datetime(2021, 10, 3,...
# File name: collatzConjecture.py # Description: Start with a number n > 1. Find the number of steps it takes to reach # 1 using the following process: If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. # Author: Juris Tihomirovs # Date: 28-05-2021 def get_collatz(): user_input = 0 while...
''' Created on May 28, 2013 @author: Tsss-Pc1 ''' #Program to Find Factorial of a Number #5 = 5*4*3*2*1 a = input() a=int(a) b=1 for i in range(a): i=i+1 b=b*i; #i=i+1 print(b)
''' Created on May 28, 2013 @author: Tsss-Pc1 ''' #Program to Check Vowel or Consonant c=input() if c=='a' or c=='e' or c=='i' or c=='o' or c=='u': print(c," is vowel") else: print(c," is consonant")
def operation(str1, str2, set1): str1 = str1+str2[0] str2 = str2[1:] sign = ['+','-',''] for item in sign: str3 = str1+item str4 = str3+str2 if str4[-1] == item: break add = eval(str4) if add == 100: ...
""" Challenge Given a list of integers, can you count and output the number of times each value appears? """ n = int(input().strip()) arr = list(map(int, input().strip().split())) max_value = max(arr) buckets = [0]*(max_value+1) #create an array that can include number from 0 to max_value. for i in range(n): b...
#Ste= p 1 #{}Debug the following program so that it properly takes a users order and outputs the price of the order. #Step 2 #Edit the existing code and have it print out the items you are ordering as follows... #Example # "Coffee x 0" # "Cake x 2" # "Tea x 3" #Step 3 #Have the items you are ordering also output thei...
def find_it(seq): result = [number for number in seq if seq.count(number) % 2 != 0] return result[0] print(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]))
def count_pairings(n, taken, are_friends): first_free = None for i in range(n): if not taken[i]: first_free = i break if first_free is None: return 1 ret = 0 for pair_with in range(first_free+1, n): if not taken[pair_with] and are_friends[first_f...
# -*- coding: utf-8 -*- """ Created on Thu Jun 6 18:53:05 2019 @author: satbi """ def Sum_rec(n): if n<0: return n+1 else: return n+Sum_rec(n-1) n=int(input("Enter a number to add till 0: ")) print(Sum_rec(n))
def check_if_self_dividing(number): try: digits = list(map(int, list(str(number)))) for digit in digits: if number % digit != 0: return False return True except: # some zeros probably or invalid input return False def get_self_dividing_numbers(left,...
def sign_func(nums): ans = 1 for num in nums: ans *= num if ans == 0: return 0 elif ans > 0: return 1 else: return -1
def computepay(h, r): pay = h * r if(h > 40): pay += (h - 40) * (r * .5) return pay try: hours = float(input("Enter in hours: ")) except: print("Error, you get no hours!") hours = 0 try: rate = float(input("Enter in rate: ")) except: print("Error, you now work for free") ra...
# -*- coding: cp1252 -*- ## ================= ## MorseCode.py ## ================= ## 2012.09.07 ## Justin Whitehouse ## # -*- coding: cp1252 -*- ## ***************** ## Morse Code = INTERNATIONAL Morse Code ## ***************** ## ----------------- ## ## Program to convert text into morse code. ##...
class marksheet: def __init__(self): self.Snumber=0 self.Sname="" self.english=23 self.cs=34 self.maths=33 self.physics=16 self.chemistry=45 def calc(self): self.t=self.chemistry+self.physics+self.cs+self.maths+self.english self.p=float((se...
class marksheet: def __init__(self): self.Snumber=0 self.Sname="" self.english=23 self.cs=34 self.maths=33 self.physics=16 self.chemistry=45 def calc(self): self.t=self.chemistry+self.physics+self.cs+self.maths+self.english self.p=float((se...
def encrypt(x): y=len(x) a=0 b=1 q=j=r=" " while a<y: q=q+x[a] a=a+2, while b<=y: r=r+x[b] b=b+2 j=q+r print q+r return j def decrypt(x): y=len(x) if y%2==0: a=y/2 b=y/2 else: a=((y-1)/2)+1 b=((y-1)/2) ...
# SET 2: # This program explores how Linear Regression for classification works, # using an input set of X = [-1, 1] x [-1, 1]. import math from random import random import numpy as np def getSign(x): if x > 0: return 1 elif x < 0: return -1 else: return 0 def getOutput(x, y, m, b): if y > m*x+b: return...
# SET 1: # This program explores how the Perceptron Learning Algorithm works. import math from random import random def getSign(x): if x > 0: return 1 elif x < 0: return -1 else: return 0 def getOutput(x, y, m, b): if y > m*x+b: return 1 else: return -1 def getF(x1, y1, x2, y2): m = (y1 - y2) / (x1 ...
# Author: Victor Ding # -*- coding: utf-8 -*- # 用线程实现 import threading import time def sayhi(name, age, interval): time.sleep(1) print("My name is {},I am {} years old".format(name, age)) start_time = time.time() print("Thread {} started at {}".format(threading.current_thread().getName(), time.cti...
# Author: Victor Ding list1 = [1,2,3,4,5,6,8,7,9,10,11,12,13,14,15] print(list1[::-1]) # reverse the list # 若 step < 0, 则表示从右向左进行切片。 此时,start必须大于end才有结果,否则为空。列如: s[5: 0: -1]的结果是'fedcb' # 那么,s[::-1]表示从右往左,以步长为1进行切片; s[::2] 表示从左往右以步长为2进行切片 print(list1[::-2]) print(list(reversed(list1))) print(sorted(list1)) print(...
# Author: Victor Ding # with open("file.txt","r") as fh: # for line in fh: # print(line.strip()) # fh.close() # with open("file.txt","r") as fh: # for line in fh.readlines(): # print(line.strip()) # fh.close() # with open("file.txt","r+") as fh: # fh.write("TITLE\n") # l = fh....
# Author: Victor Ding names = ['vmware','sonicwall','red hat','cisco','juniper','palo alto','arista'] names.append('fortinet') # insert at the end names[2] = 'citrix' # replace specific element names.insert(2,'extreme') # How to delete elments names.remove('arista') print(names) names.__delitem__(names.index('juni...
# Author: Victor Ding #Python 多态 class Animal(): @staticmethod def act(obj): obj.action() class Bird(Animal): def __init__(self,type): self.type = type def action(self): print("{} 在飞翔".format(self.type)) class Fish(Animal): def __init__(self,type): self.type = ty...
# Author: Victor Ding # -*- coding: utf-8 -*- import threading,multiprocessing import time def ttt(t): print("This is Thread {}".format(t)) time.sleep(5) def sayhi(): tlist = [threading.Thread(target=ttt,args=("name%s"%(str(i)),),) for i in range(3)] for i in tlist: i.start() for i in th...
# Author: Victor Ding # -*- coding: utf-8 -*- class people(): def __init__(self, name, age): self.name = name self.age = age def talk(self): print("{} is talking about his age,which is {}".format(self.name, self.age)) def eat(self): print("{} is eating breakfast".format(self.nam...
# Author: Victor Ding # -*- coding: utf-8 -*- import threading import time import random # At start-up, a Thread does some basic initialization and then calls its run() method, # which calls the target function passed to the constructor. To create a subclass of Thread, override run() to do whatever is necessary. c...
n = int(input('Digite um número ')) a = n - 1 s = n + 1 print('Analisando seu valor {}, seu antecessor {}, e o sucessor é {}'.format(n, a, s))
# NewPogi.py # Python2 # Andresito de Guzman apptitle = "\n\nAkala mo may itsura ka?" appcreate = "April 2016" appseparate = "========================" appbreak = "\n" print apptitle print appcreate print appseparate print appbreak # Ask name print "Computer: Oi ikaw, oo ikaw nga! Ano pangalan mo?" pangalan = raw_i...
# utility functions # Use this file for all functions you create and might want to reuse later. # Import them in the `main.py` script def mean_ano(x, lat_min, lat_max, lon_min, lon_max, year): """ Calculates the mean anomaly from the monthly anomaly values. The single monthly anomalies were calculate...
#se importa asi: from { file name } import {class name} from Calculator import Calculator firstNumber = int(input('enter the first number: ')) secondNumber = int(input('enter the second number: ')) operator = input('enter the operator: ') c = Calculator() result = 0 if operator== '*': result = c.__multiply__(firs...
''' Author: Fernando Luiz Neme Chibli Date: 2019/04/29 This code will find the least number that has 99% or more of bouncy numbers in its collection. For performance purpouses, this verification will start at 21780. ''' from BouncyTools import BouncyList, LeastBouncyFinder from sys import argv usage_exemple='\nUsage:...
""" Evaluate the value of a polynomial using the Horner's method. """ class Polynomial: def __init__(self, coefficients: list): self._coefficients = coefficients def evaluate_at(self, x: float) -> float: result = self._coefficients[0] for coefficient in self._coefficients[1:]: ...
# to run this file, run 'python ls1.2.py demo2.txt' in the console import random import sys # write f = open("c1/demo2.txt", "w") i = 0 while i < 50: f.write("%3d \n" % random.randint(0, 100)) i += 1 f.close() # read and calculate if len(sys.argv) != 2: # sys.argv returns a list ["ls1.2.py", "demo2.txt"]...
from sys import stdin, stdout # The anormaly unexplained #stdout.write("Enter your name :") #name = stdin.readline() #print("") #print("You just typed: ", name) # alternatively name = input("Enter your name: ") stdout.write("You just typed: %s" % name) print("")
# Tuples are immutable # The benefit of immutability is that we can use them as keys in dictionaries, # and in other locations where an object requires an hash value. # Behavior cannot be stored in a tuple # create a tuple stock = "FB", 75.00, 75.03, 74.90 # or stock2 = ("FB", 75.00, 75.03, 74.90) print(stock == st...
# ABCs define a set of methods and properties that # a class must implement in order to be considered a duck-type # instance of that class ########## Use an abstract base class # most ABCs live in the collections module from collections import Container def main(): print(Container.__abstractmethods__) # get __...
def divide(a, b): q = a // b # // returns the quotient r = a - q * b return (q, r) def te(): print("say teeee") print(divide(5,3))
# sets are unordered # in python, set can hold any hashable objects # so lists and dictionaries are out song_library =[('a', "James"), ('b', "Eric"), ('c', "John"), ('d', "Eric")] artists = set() for song, artist in song_library: artists.add(artist) artists # There is no built-in syntax for empty set # but w...
# What is stack? (https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29) # What is the first argument of each method? # What is the difference between instance method and static method? items = [37, 42] # set up an object items.append(73) # edit the object print(dir(items)) # dir lists all methods available...
import math ## class MyFirstClass: pass a = MyFirstClass() b = MyFirstClass() ## class Point: pass p1 = Point() p2 = Point() p1.x = 5 p1.y = 4 p2.x = 3 p2.y = 6 ## class Point: def reset(self): self.x = 0 self.y = 0 p = Point() p.reset() # which is equivalent to: Point.reset(p) # ...
""" Consider a list (list = []). You can perform the following commands: insert i e: Insert integer at position. print: Print the list. remove e: Delete the first occurrence of integer. append e: Insert integer at the end of the list. sort: Sort the list. pop: Pop the last element from the list. revers...
a = int(input("Enter a \n")) b = int(input("Enter b \n")) #if a>b: print("A is greater than B") print("B is greater than A") if b>a else print("A is greater than B")
# # 1. print string within str # for val in "String": # if val == "i": # break # print(val) # print("The end") # # 2. print 1 to 4 # i = 0 # while i < 6: # x = i + 1 # print(x) # i = x # if i == 4: # break # print("the end") # # 3. print string without i # for val in "string": # ...
print("-" * 20) print(" IGEL DISTRIBUIDORA") print("-" * 20) #5 reais serão do custo fixo do ML #45% é a margem de lucro ideal #11% é a tributação por venda #18% é a tarifa do ML #15% é o custo fixo da IGEL, cálculo feito com base no ticket médio e total de vendas por mês #Cálculo Markup: #Markup = 100/100 - (Des...