text
stringlengths
37
1.41M
# Geetha Karthikesan ,2019 #python primes.py # num is any positive integer u need to check its prime or not num = int (input("Please enter a positive integer:")) # prime numbers are greater than 1 if num > 1: # check for factors in the range (2,num) for i in range(2,num): # checking if num is compl...
# import the necessary packages from __future__ import print_function from keras.models import load_model import numpy as np import cv2 # initialize the class labels for the Kaggle dogs vs cats dataset CLASSES = ["cat", "dog"] # load the network print("Loading network architecture and weights...") model = load_model...
ListaFilmes = ["baby driver", "star wars"] ListaJogos = ["Adastra", "password"] ListaLivros = ["O principe", "Sim"] ListaEsporte = ["futebol", "Tenis"] Lista = ListaFilmes + ListaJogos + ListaLivros + ListaEsporte print("Item da lista livro:", ListaLivros[0])
matrix = [[1,2],[1,3]] k = 2 all_lis=[] for i in matrix: for j in i: all_lis.append(j) print(sorted(all_lis)[k-1])
# Danny has a possible list of passwords of Manny's facebook account. All passwords length is odd. But Danny knows that Manny is a big fan of palindromes. So, his password and reverse of his password both should be in the list. # You have to print the length of Manny's password and it's middle character. # Note :...
# Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows: # Characters ('a' to 'i') are represented by ('1' to '9') respectively. # Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. # Return the string formed after mapping. # ...
import heapq class Order(object): def __init__(self,dic): self.__dict__.update(dic) def __lt__(self, other): if self.price!= other.price: if(self.side=='B'): return self.price>other.price else: return self.price<other.price else : ...
# Marvel characters, object oriented programming. # Class and Inheritance application # Marvel characters - Features application # written by Spyder IDE. """ @author: saaydmr """ #%% Base class class Marvel(): characters = [] age_avg = 0 def __init__(self, gender, age, power, name, surname, experience,...
""" Problem statement: Stock prices can be described as a Brownian motion and that mean future prices (states) are independent from the past prices (states). Brownian motion is a random process and therefore preditions of future sates are inherently impossible. Data: 5 years of Google stock prices, 01/2012 - 12/2016 ...
# -*- coding: utf-8 -*- """ Created on Mon Nov 6 20:29:15 2017 @author: Edward """ def is_even(n): if n < 0: return is_even(-n) if n < 2: return 1-n subs = [1 << i for i, bit in enumerate(bin(n)[-2:1:-1], 1) if is_even(int(bit)) is not True] return is_even(n - sum...
def reverse(x: int) -> int: if x < 0: num = -int(str(x)[1:][::-1]) else: num = int(str(x)[::-1]) return num if -2 ** 31 < num < 2 ** 31 - 1 else 0 if __name__ == '__main__': assert reverse(123) == 3215, '321'
my_name = ' Saurav Kanchan ' my_age = 18 #not a lie my_height = 74 #inches my_weight = 180#lbs my_eyes = 'Black' my_teeth = 'White' my_hair = "Brown" print "Let's talk about %s." % my_name #%s , %r and %d areknown as formatters. #they tell python to take the variable on the right and put it in to replace th...
# dictionary is a data stucture.(a complex way to say) # list is list = ["something"] # dictionary is dictionry = {"something" = "other"} # ######################### # # creat a mapping of state to abbrevation. states = { "Oregon": "OR", "Florida": "FL", "California": "CA", "New York" : "NY", "Michigan...
def add (a,b): print "Adding %d + %d" % (a, b) return a+b def subtract(a,b): print "SUBTACTING %d - %d"% (a, b) return a-b def divide(a, b): print "DIVIDING %d /%d"% (a,b) return a/b def multiply(a,b): print "MULTIPLYING %d* %d"%(a, b) return a*b print "Let's do s...
if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() average = sum(student_marks[query_name]) / len(student_marks[query_name]) prin...
#!/usr/bin/env python3 import sys import os import re # Search for the specific error in the log file def error_search(log_file): error = input("What is the error? ") # returned_errors will be used to list all the ERROR logs returned_errors = [] with open(log_file, mode='r',encoding='UTF-8') as file: for ...
import os import datetime def file_date(filename): # Create the file in the current directory os.mkdir(filename) timestamp = os.path.getmtime(filename) # Convert the timestamp into a readable format, then into a string new = datetime.datetime.fromtimestamp(timestamp) # Return just the date portion # Hin...
''' ToDo: Fase 1 - Base Classes ✔ - Basic Data Storage ✔ - Basic User Interface ✔ Fase 2 - Able to list all books ✔ - Able to view the information of a book ✔ - Adding books ✔ - Removing books ✔ Fase 3 - Account creation ✔ - Account login ✔ - Account permission checks ✔ - Restrict book editing to Librarian ✔ Fase 4...
""" Name: Akinlua, Olorunfemi Praise Date Created: April 04, 2020 About: Learn Python (Fuctions); Based of the Udemy Python Mega Course Version: 1.0 Python Version: 3.6 """ #Functions #Function is a peice of reuseable code that may or may not have arguments #that varies their results. They are basically smaller or mi...
#!/bin/usr/env python3 # -*- coding:utf-8 -*- #在一个list中,删掉偶数,只保留奇数,可以这么写: def is_odd(n): return n % 2 == 1 a1 = list(filter(is_odd,[1,2,3,4,5,6,7,8,9])) print('list仅保留奇数:',a1) def not_empty(s): return s and s.strip() a2 = list(filter(not_empty,['A','','B',None,'C',''])) print('去掉空字符串:',a2) #可见用filter()这个高阶函数...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- #位置参数 #我们先写一个计算x2的函数: def power(x): return x*x #对于power(x)函数,参数x就是一个位置参数。 #当我们调用power函数时,必须传入有且仅有的一个参数x: a_1 = power(5) print("5的平方=",a_1) #现在,如果我们要计算x3怎么办?可以再定义一个power3函数, # 但是如果要计算x4、x5……怎么办?我们不可能定义无限多个函数。 #你也许想到了,可以把power(x)修改为power(x, n),用来计算xn,说干就干: def power_1(x_...
#!/bin/usr/env python3 # -*- coding:utf-8 -*- #由于非字符串类型没有lower()方法,所以列表生成式会报错: #L = ['Hello', 'World', 18, 'Apple', None] # [s.lower() for s in L] #Traceback (most recent call last): # File "<stdin>", line 1, in <module> # File "<stdin>", line 1, in <listcomp> #AttributeError: 'int' object has no attribute 'lower' ...
#!/bin/usr/env python3 # -*- coding: utf-8 -*- #我们已经知道,可以直接作用于for循环的数据类型有以下几种: #一类是集合数据类型,如list、tuple、dict、set、str等; #一类是generator,包括生成器和带yield的generator function。 #这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。 #可以使用isinstance()判断一个对象是否是Iterable对象: from collections.abc import Iterable a = isinstance([],Iterable)#列表 b = isi...
# -*- coding: utf-8 -*- """ Created on Wed May 31 22:02:02 2017 @author: Administrator """ class Stack(object): def __init__(self, size = 8): self.stack = [] self.size = size self.top = -1 def set_size(self, size): if self.top >= size: raise Exceptio...
print("Hello World!") # Dogs are better than cats ''' ToDo Check different data types do some math do input and output Fnctons/Methods/Procedures function - a list of steps(algorithm) that defined to a word or phrase methods - OOP - object.methods or functions that obj...
neurons = [] val = float(raw_input()) while val != 0: neurons.append(val) val = float(raw_input()) #debug printing #print(neurons) numneurons = len(neurons) minlength = min(neurons) maxlength = max(neurons) avglength = float(sum(neurons)) / numneurons tot = 0.0 for n in neurons: tot = tot + (n-avglength)**2 stdd...
# write a program that receives an integer and # computes and outputs its absolute value val = int(raw_input()) # val = input() abs_val = val if abs_val < 0: abs_val = -abs_val # abs_val = -val # abs_val contains for sure a positive value print(str(abs_val))
USED = '+' NOTUSED = ' ' word1 = raw_input('') # h o u s e word2 = raw_input('') # s h o e s letter = [] # len1 = 0 for c in word1: letter.append(NOTUSED) len1 += 1 len2 = len(word2) if len1 == len2: isAnag = True i = 0 while i < len1 and isAnag == True: found = False j = 0 while j < len...
DNACOMPLEMENT = {'A' : 'T', 'C' : 'G', 'G' : 'C', 'T' : 'A', 'a' : 't', 'c' : 'g', 'g' : 'c', 't' : 'a'} # compl = DNACOMPLEMENT.get(ch) # GGGGaaaaaaaatttatatatat # CCCCttttttttaaatatatata # atatatataaattttttttCCCC # ata def computeReverseComplement(seq): revseq = "" size = len(seq) for i in range(size-...
# write a program that receives in input a strictly positive # integer (and it is surely so) which represents an amount of # time expressed in seconds. The program computes and outputs # this same amount expressed in hours, minutes and seconds. # 200 # 200s = 0h 3m 20s SEC_IN_MIN = 60 MIN_IN_HOUR = 60 time = int(...
import math x1 = int(input("Digite o primeiro número: ")) y1 = int(input("Digite o segundo numero: ")) x2 = int(input("Digite o terceiro numero: ")) y2 = int(input("Digite o quarto numero: ")) distancia = math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2)) if(distancia > 10): print(distancia) print("longe") else...
def main(): numero = int(input("Digite um numero inteiro: ")) mensagem = fizzbuzz(numero) print(mensagem) def fizzbuzz(a): div1 = a % 5 div2 = a % 3 if(div1 == 0 and div2 == 0): return("FizzBuzz") elif (div1 == 0): return("Buzz") elif(div2 == 0): retur...
"""Even iterate""" I = 2 for I = 1 to 10: print(I) I = I+2 print('Goodbye!')
def flip_case(phrase, to_swap): """Flip [to_swap] case each time it appears in phrase. >>> flip_case('Aaaahhh', 'a') 'aAAAhhh' >>> flip_case('Aaaahhh', 'A') 'aAAAhhh' >>> flip_case('Aaaahhh', 'h') 'AaaaHHH' """ flipped_string = "" for char in phrase: ...
a=3 #a=3을 입력하면 , 3이라는 정수형 객체가 메모리에 생성됨...a는 정수형 객체 3을 가르키는 변수 b=5 a,b = b,a print(b) from copy import copy #동일한 값을 가지면서 서로 다른 객체를 만드는 방법 a = [1, 2, 3] b = copy(a) print(a is b) a[1] = 10 print(a) print(b) #동일한 값을 가지면서 서로 같은 객체를 만드는 방법 c = [1, 2, 3] d = a print(c is d) c[1] = 10 ...
from particle_object import Particle import random """ The goal of this file is to get a list of random point inside the leaf shapes """ def get_initial(shape, num_particles): """ :param shape: the description of the leaf shape num_particles: number of random particles you want to generate :...
#TEAM MAKESMART #Maco Doussias, Pavlos Papadonikolakis, Jake McGhee #LAB11 #11-24-17 #Game Description: #An explorer has fallen down an hole in the ground and into a cave. He/She cannot climb back out. #Many people have died in the cave. The explorer must explore the cave to find objects to climb back out ...
import numpy as np print(np.char.add(['hello'], ['jsledd'])) print(np.char.multiply('Hello ', 3)) print(np.char.center('hello', 20, fillchar='*')) # 此函数返回所需宽度的数组,以便输入字符串位于中心,并使用fillchar在左侧和右侧进行填充 print(np.char.capitalize('hello world')) # 首字母大写 print(np.char.title('hello how are you?')) # 字符串的按元素标题转换版本,其中每个单词的首字母都大...
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), columns=['col1', 'col2', 'col3']) print(df.pipe(lambda x, y: x + y, 20)) # df.pipe(adder, 20) print(df.apply(np.mean, axis=1)) # 按行执行 print(df.apply(lambda x: x.max() - x.min())) # 默认按列执行 print(df['col1'].map(lambda x: x * 100)) print(d...
# -*- coding: utf-8 -*- """ Created on Wed Mar 13 23:21:46 2019 @author: S. V. Rajeenth """ n = int(input()) dict= {} for i in range (n): dict[i]=i*i print (dict)
''' Implementation fo adjancecy matrix representation of a graph Basic operations add_edge(i,j) O(1) remove_edge(i,j) O(1) has_edge(i,j) O(1) out_edges(i) O(|V|), |V|=num of vertices in_edges(i) O(|V|), |V|=num of vertices in_degree(i) O(|V|), |V|=num of vertices out_degree(i) O(|V|), |V|=num of ...
''' Set Implementation of Hash Table using Chaining Basic operations: get(x) O(1) add(x) O(1) remove(x) O(1) Note: - Hash Table: maps key to value for higher efficiency look up - Hash function: maps a key (big no. or string) to a smaller integer, which indicates index in the array - Colliso...
#!/usr/bin/env python3 # Library for reading csv files import csv # Library for reading command line parameters import sys #Library for (file-)system operations import os import os.path #Library to use sqlite3 import sqlite3 # ====================================================================== Control flow begi...
print('Enter name') name=input() print('Enter age') age=int(input()) if(name=='Alice'): print('Hi Alice') elif(age<12): print('Your are not Alice kiddo') elif(age>100): print('Your are not Alice grannie') elif(age>2000): print('You are a immortal vampire')
print("Gib einen Betrag und das was du bezahlt hast ein!") betrag = int(input("Betrag(in €): ")) bezahlt = int(input("Bezahlt(in ct): ")) zurueck = (bezahlt / 100) - betrag print("Das Rückgeld ist " + str(zurueck) + " €")
class Punkt(): def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y class MitName(): def __init__(self, name): self.name = name def __eq__(self, other): return self.name == other.name class P...
zahl1 = int(input("Gib hier die erste von zwei Zahlen ein deren Durchschnitt erechnet werden soll: ")) zahl2 = int(input("Und hier die zweite: ")) durchschnitt = (zahl1 + zahl2) / 2 print("Der Durchschnitt ist " + str(durchschnitt)) # Aufgabe b:aus mehreren Zahlen
__author__ = 'Mark Weinreuter' # 1. Rechteck gefüllt breite = 10 hoehe = 5 print("Rechteck gefüllt: %dx%d" % (breite, hoehe)) for i in range(0, hoehe): print("X" * breite) print() print("Rechteck hohl: %dx%d" % (breite, hoehe)) print("X" * breite) for i in range(0, hoehe-2): print("X" + " " * (breite - 2) +...
# Python Einführung 2: Variablen und Strings/Zeichenketten # Hinweis: Die verwendeten Befehle beziehen sich auf Python3. # Sie sind deshalb nicht zwangsweise mit Pyhton2 kompatibel! # Hinweis: Alle (hoffentlich alle) verwendeten Begriffe, können auch noch einmal # in der Datei 'uebersicht.py' nachgelesen werden. ...
# Liest einen Text von der Konsole ein name = input("Wie heißt du?: ") alter = input("Wie alt bist du?: ") # Alter als Text einlesen alter = int(alter) # Text in eine Zahl konvertieren # Gibt den eingelesenen Namen auf der Konsole aus print("Hallo", name) print("Du bist also", alter, "Jahre alt!")
# -*- coding: utf-8 -*- ''' A partir de este ejercicio cambiamos las rutas absolutas por relativas y se utiliza la codificación UTF-8 ''' carpeta_nombre="Documentos\\" archivo_nombre="P_IFT_200416_162_Acc.txt" palabra1="ACUERDO" palabra2="RESOLUCIÓN" with open(carpeta_nombre+archivo_nombre,"r",encoding="utf8") as a...
# -*- coding: utf-8 -*- ''' El ejercicio consiste en segmentar un texto en oraciones. Se entiende por oración todo lo que hay entre una mayúscula y un punto. Para garantizar esta segmentación se recorre una lista con todas las mayúsculas. ''' import re carpeta_nombre="Documentos\\" archivo_nombre="P_IFT_290216_73_Ac...
# Permutation # - an arrangement of its members into a sequence or linear order, or if the set is already ordered, a rearrangement of its elements. (Order matters) # nPr = n!/(n-r)! import itertools data = [1,2] for x in itertools.permutation(data,2): print(list(x)) # Combination # - Same concept as permutation b...
# bisect : Provides support for maintaining a list in sorted order without having to sort the list after each insertion (Binary search) # -Similar to upper_bound and lower_bound from c++ # a) bisect_left(a,x): Maintaining a list in sorted order, find the index for the insertion point for x in a to most left side. # b) ...
def rotate_a_matrix_by_90_degree(a): row_length = len(a) column_length = len(a[0]) res = [[0]*row_length for _ in range(column_length)] for r in range(row_length): for c in range(column_length): res[c][row_length-1-r] = a[r][c] return res #ex a = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ] b = ...
# Link : https://leetcode.com/problems/single-number/ # Problem: # Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. # Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory? class Solution: def singl...
from operator import xor def findXOR(n): mod = n % 4 if (mod == 0): return n elif (mod == 1): return 1 elif (mod == 2): return n + 1 elif (mod == 3): return 0 def findXORFun(l, r): res=(xor(findXOR(l - 1) , findXOR(r))) return res fo...
for _ in range(int(input())): a = input() b = input() if len(a)==len(b): max = 0 min = 0 for i in range(len(a)): if a[i]!=b[i] and a[i]!='?' and b[i]!='?': min+=1 if a[i]!=b[i] or a[i]=='?' or b[i]=='?': max+=1 pr...
from board import board from boats import Boat import copy class Player: def __init__(self): """ Initialize arguments Args: None Returns: None """ # this player's ships self.shipList = [] self.shipCoordinateList = [] # this player's board self.myBoard = board(8, 8) # opponent's board self....
#A program that will be responsible for capturing employee payment data #23 Feb 2015 from WagedEmployee import WagedEmployee from SalariedEmployee import SalariedEmployee from Employee import Employee from Person import Person def main(): #this is the main pr...
class Student: def __init__(self, n='unknown', sn='unknown'): self.name = n self.student_number = sn self.courses = [] def __str__(self): s = self.name + ',' + self.student_number for c in self.courses: s += '-' + str(c) return s def...
#A program that solves quadratic equation #Mholi Mncube #created 1 May 2014 modified 7 May 2014 def quad_solve(): import math a=int(input("Enter the value of a: ")) b=int(input("Enter the value of b: ")) c=int(input("Enter the value of c: ")) d=b**2-4*a*c if d>0: print("The first root is...
def palindrome(s): #definition of the program s.lower() #cast input string into lower if len(s)==0: # base case return s else: return palindrome(s[1:]) +s[0] #this part reverses the string def main():#main function x=input('Enter a sente...
def enter_rainfall(): months=['January','February','March','April','May','June','July','August','September','October','November','December'] y=input('Enter <city_name>_<year>.dat in this format exactly: ') #this f=open(y,'w') for i in months: print(i) x=input('Enter rainfall for twelve ...
#tic tac toe def OXO(): OXO=[['1','2','3'],['4','5','6'],['7','8','9']] #this is the 2d list print(OXO[0][0],OXO[0][1],OXO[0][2],sep='|') #basically this is the grid formmated as asked in the question print("------") print(OXO[1][0],OXO[1][1],OXO[1][2],sep='|') ...
""" User class which is responsible for both the user properties and user database management """ class User: def __init__(self, name: str): self.name = name def get_name(self): pass def save(self, user: 'User') -> 'User': pass """ Split User class into User and UserDB """ c...
a = int(input("Введите число 1: ")) b = int(input("Введите число 2: ")) c = int(input("Введите число 3: ")) if a * b == c: print(a, "умножить на", b, "равно", c) elif a * b != c: print(a, "умножить на", b, "не равно", c) if a / b == c: print(a, "разделить на", b, "равно", c) elif a / b != c: print(a, "...
word = input("Введите слово: ") word = word.lower() l = len(word) code = word a = 0 print(word) for a in range(l - 1): for i,letter in enumerate(word): if i == l - 1: code += code[0] elif i < l: code += code[i + 1] else: break code = code[-l : ] a...
a = input("Please enter a number: ") b = input("Please enter another number: ") a = int(a) b = int(b) c = a + b print("The sum of the numbers entered is:", c)
# Pythono3 code to rename multiple # files in a directory or folder # importing os module import os # Function to rename multiple files def main(): i = 0 file1 = open("list.txt","w") L = ["This is Delhi \n","This is Paris \n","This is London \n"] # \n is placed to indicate EOL (End of Lin...
#Replaces a letter in a word word = input("Word: ") letter = input("Letter to remove: ") final = word.replace(letter,"") print(final)
import calendar from datetime import datetime from decimal import Decimal from django.utils.datastructures import SortedDict def _create_datetime_object(year, month): # year, month, day, hour, minute, second return datetime(year, month, 1, 0, 0, 0) def _get_months_days(year): """ Returns a list of the...
# -*- coding: utf-8 -*- """ Created on Mon Dec 10 09:50:17 2018 @author: mluci """ #--------Module 2: Lesson 5 --------- #----"Team Class Work"---- ###Pizza Game### class PizzaShop(): def welcome(): message="Welcome to our pizza shop" print(message) welcome() class CustomerInfo(PizzaShop...
# -*- coding: utf-8 -*- """ Created on Wed Jan 9 09:10:47 2019 @author: mluci """ ####Chapter 14: Databases#### import sqlite3 #Import and connect a database# conn = sqlite3.connect('ch14.db') #Connect cursor# c=conn.cursor() #Create table# def create_table(): c.execute('CREATE TABLE IF NOT EXISTS stuffToBuil...
# -*- coding: utf-8 -*- """ Created on Fri Dec 21 13:44:22 2018 @author: mluci """ ####07/03: Creating your own moving figure#### from Shapes import * from pylab import random as r class MovingShape: def __init__(self, frame, shape, diameter): self.shape = shape self.diameter = diameter s...
# -*- coding: utf-8 -*- #--------Module 2: Lesson 3--------- #----"Functions & Importing Modules"---- # TIP: when importing for another file, do not have script in it as it will run script first ##Instructions to Import## #-When you want a specific function: from ch03_functionIntro import add_two_numbers #-When you...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ #--------Module 2: Lesson 2--------- #--"Operations, Strings and Variables---- ###Task 1 : Simple operations with Python### 8*9 6/2 5/2 5.0/2 5%2 2*(10+3) 2**4 ###Task 2: Variabe practice### age=5 age="almost three" age=29.5 age='I reall...
import random import math def fibo(n): if (n == 1) or (n == 2): return 1 return fibo(n - 1) + fibo(n - 2) print('Δώστε έναν αριθμός του Fibonachi') userNumber = int(input()) fiboNumber = fibo(abs(userNumber)) if (userNumber < 0) and (userNumber % 2 == 0): fiboNumber = fiboNumber * (-1) result = False finalResul...
gas_station = [ (0, 15), (12, 15), (14, 15), (20, 15), (25, 15), (30, 15), (40, 15), (45, 15), ] gas_station.sort(reverse=True) # n*log(n) at, max_range = 0, 0 stopped_at = [] destination = 60 while max_range < destination and gas_station: furthest_gas_station = None while gas_station and gas_station[-1...
tasks = [ # (label, time_needed, deadline), ('A', 3, 6), ('B', 1, 8), ('C', 5, 5), ('D', 3, 4), ('E', 5, 9), ('F', 2, 4), ('G', 2, 2), ('H', 4, 7), ] tasks.sort(key=lambda x : x[2], reverse=True) lateness = 0 at = 0 while tasks: label, time_needed, deadline = tasks.pop() at = at + time_needed if at > d...
from collections import defaultdict peso = {1:4, 2:2, 3:1, 4:3} valor = {1:500, 2:400, 3:300, 4:450} cap = 5 # capacidade máxima da mochila objs = 4 # qnt de objetos table = defaultdict(lambda:defaultdict(lambda:0)) # cm: capacidade da mochila for cm in range(1, cap+1): # para cada objeto for obj in range(1, objs...
# Use the file name file2.txt as the file name fname = input("Enter file name: ") fh = open(fname) count = 0 a = 0; for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue count += 1 x = float(line[19:].lstrip()) a += x avg = a/count print("Average spam confidence:", avg)
# -*- coding: utf-8 -*- import asyncio import time def now(): return time.time() # 1.定义协程函数 """ async def task0(): await asyncio.sleep(1) print("task0 done") async def task1(): await task0() await asyncio.sleep(1) print("task1 done") async def task2(): await task1() await asyncio.sl...
class Car: # Initialize the required arguments def __init__(self, modelYear, carMake): self.__modelYear = modelYear self.__carMake = carMake self.__carSpeed = 0 # Run the car acceleration def accelerate(self): self.__carSpeed += 5 # Decelerates the car def ...
def get_income(hot_dog): income = (6 * hot_dog) - 3000 return income print(get_income(400)) print(get_income(400)) def foo(n): num = (6 * n) - 4 return num print(foo(4)) print(foo(5)) print(foo(6)) print(foo(7)) def coo(a): num = (1 / (3 ** a - 1)) return num print(coo(1)) print(coo(2)) print(coo(3)) pri...
# This solution is how I approached the problem: # - First I iterate through the input list using index i # - For every element, I iterate through the remaining part of the list and see if there are subsequent elements that would add with element at index i to be k # - If there is, return True. def solution1(number_lis...
ganha=float(input("Quanto você ganha por hora? ")) trabalhada=int(input("Quantas horas você trabalha por mês? ")) salario=ganha*trabalhada print("Seu salário bruto foi: ", salario) inss=(salario*0.08) print("INSS: ", inss) sindicato=(salario*0.05) print("Sindicato: ", sindicato) ir=(salario*0.11) print("Impo...
vendedor=[0,0,0,0,0,0,0,0,0] cont=0 resposta="s" while resposta=='s': salario=float(input("Informe seu salario R$: " )) if 200 < salario <299: vendedor[0]=vendedor[0]+1 elif 300 < salario > 399: vendedor[1]=vendedor[1]+1 elif 400 < salario > 499: vendedor[2]=vendedor[2]+1...
#!/usr/bin/env python3 # HW06_ch09_ex05.py # (1) # Write a function called is_abecedarian that returns True if the letters in a # word appear in alphabetical order (double letters are ok). # - write is_abecedarian # (2) # How many abecedarian words are there? # - write additional function(s) to assist you # - nu...
pi = 3.14 r = 1.1 area = pi * r * r print("area of circle:%2f"%area)
lit2num = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1} num2lit = { y: x for x, y in lit2num.items()} def decode(roman): """complete the solution by transforming the roman numeral into an integer""" nums = [literals[x] for x in roman] result = 0 print nums for i, n in enumerate(nums): ...
""" Library of EV3 robot functions that are useful in many different applications. For example things like arm_up, arm_down, driving around, or doing things with the Pixy camera. Add commands as needed to support the features you'd like to implement. For organizational purposes try to only write methods into ...
''' Faça um programa que recebe um número n que corresponde a quantidade de valores inteiros que serão lidos e armazenados em uma lista. Como saída, o programa imprime os n valores lidos na ordem decrescente dos valores. Entrada: Saida: 3 [5, 4, 2] 2 5 4 ''' lista_Numeros = [] quantidade = int(i...
import common def jump(n): if n%2==0: return n/2 else: return 3*n +1 @common.cached def countJumps(n): if n is 1: return 1 return 1 + countJumps(jump(n)) max_jumps = 1 n = 1 for i in range(2, 10**6): jumps = countJumps(i) if jumps>max_jumps: max_jumps= jumps n = i print n
from common import sieve N = 20 lst = range(1, N+1) primes = sieve(N) lcm = 1 for prime in primes: while(True): found_a_multiple = False for i, n in enumerate(lst): if n%prime == 0: lst[i] /= prime found_a_multiple = True if found_a_multiple: lcm *= prime else: break print lcm
def run(): def dividir_lista(lista, divisor): try: return [i / divisor for i in lista] except ZeroDivisionError as e: print(f'Error: {e}') lista = range(1, 10) divisor = 2 print(dividir_lista(lista, divisor)) # Excepciones comunes: # ImportError : una ...
import random class Universe(object): """Class representing a Game of Life universe.""" def __init__(self, cells): self.cells = frozenset(cells) @classmethod def randomized(cls, width, height): """Returns a randomized Game of Life universe of the given dimensions""" seed = [(x...
def mortal_fibonacci(n,m): if n > 2: return(n) elif 2 <= n <= m: return(mortal_fibonacci(n-1,m) + mortal_fibonacci(n-2,m)) elif n > m: return(mortal_fibonacci(n-1,m) + mortal_fibonacci(n-2,m)-mortal_fibonacci(n-3,m)) print(mortal_fibonacci(6,3))
#"as" can be used as alias to prevent naming collision from pkg_resources import EGG_DIST import module as m #imports all functions from module.py from module import favorite_book as fb #imports one function from module.py #from module import * <-- "*" imports all functions in a module #using a module using alias m.d...
from random import randint value = randint(1, 10) tries = 0 guess = input('Guess a number between 1 to 10: ') guess = int(guess) while guess != value: if guess < value: print('Your guess is too low') elif guess > value: print('Your guess is too high') tries += 1 guess = input('Try again: ') guess = ...