text
stringlengths
37
1.41M
# Official Name: Janet Lee # Lab section: M3 # email: jlee67@syr.edu # Assignment: Assignment 3, problem 1. # Date: September 14, 2019 # Compute the time lapse of seeing to hearing a lightning strike def main(): #Ask user how many lines l= eval(input("How many lines do you want in your table? ")) ...
#Janet Lee #Lab M3 #processCookies.py #Obtain information from the file cookieSales.txt. #Print how many kids there are and their names. #Print the total number of Samoas sold. #From a line already read from a file, place the different # pieces of data in well named variables of a good type. def getCookieD...
#Janet Lee #LabM3 #Snowman.py #Introduction to functions with no parameters #and no return values # What does this do? def snowball(): s='*' print("{0:>11}".format("****")) print("{0:>7}{0:>6}".format("**")) print("{0:>5}{0:>9}".format(s)) print("{0:>4}{0:>11}".format(s)) print("{0...
import random print "Rock Paper Scissors\n G A M E"; victorias = 0; derrotas = 0; var = 1; array = ["nada","piedra","papel","tijeras"]; while var == 1: print ""; print tirada = int(raw_input("\nIntroduce your movement: \n 1-Rock\n 2-Paper\n 3-Scissors")); maquina = random.randint(1,3); ...
#!/usr/bin/python3 import sys import copy import math import random class Board: def __init__(self, board_size, goal): ''' initialize a board''' self.board_size = board_size self.goal = goal self.fitness = 0 # put first items in bord self.queens = list(range(self....
######################################################################## # #100DaysofCode By Jonathan Rhau # # # # Day 4 - Rock Paper Scissors # # ...
######################################################################## # #100DaysofCode By Jonathan Rhau # # # # Day 22 - Ping Pong Game # # ...
######################################################################## # #100DaysofCode By Jonathan Rhau # # # # Day 16 - Coffee Machine (OOP) # # ...
######################################################################## # #100DaysofCode By Jonathan Rhau # # # # Day 8 - Caesar Cipher # # ...
# -*- coding: utf-8 -*- """ Created on Fri Feb 15 13:55:05 2019 @author: Vanathi """ # Load the PANDAS library import pandas import matplotlib.pyplot as plt import numpy as np import itertools from itertools import combinations #Suppose a market basket can possibly contain these seven items: A, B, C, D, ...
#Training a NN to classify IMDB reviews as positive or negative in Keras #Works by taking in data on the most used 10000 words, seeing what words are present in a given review, #and then training a model to classify reviews as positive or negative based on reviews in a training set. #Import IMDB dataset, already pres...
import numpy as np from sklearn.cluster import KMeans import networkx as nx import seaborn as sns sns.set() class Spectral: """ Performs spectral clustering from scratch. In spectral clustering, the affinity, and not the absolute location (i.e. k-means), determines what points fall under which cluster. ...
class Person: def __init__(self, name): self.name = name def __str__(self): return f'{self.__class__.__name__} class, Obj name: {self.name}' person = Person("Arijona") print(person.__str__())
# This program showed that how to use __init__() method in class class Homosapien: def __init__(self, name, age, no_of_hand, no_of_leg, specification): self.name = name self.age = age self.no_of_hand = no_of_hand self.no_of_leg = no_of_leg self.specification = specificati...
def decToHex(): numero_decimal = int(input("escolha um numero decimal: ")) hexadecimal = "" while numero_decimal != 0: restante = mudaDigito(numero_decimal % 16) hexadecimal = str(restante) + hexadecimal numero_decimal = int(numero_decimal / 16) return print(hexadecimal) ...
# Press Shift+F10 to execute it or replace it with your code. # Vigenere cipher import string from typing import List, Any, Union input = "The Avengers could be considered as a Lee and Kirby's renovation of a previous superhero team, All-Winners Squad, who appeared in comic books series published by Marvel Comics...
glossary = { 'string': 'a sequence of characters', 'variable': 'a value that can change, depending on conditions or on information passed to the program', 'list': 'a data structure that is a changeable ordered sequence of elements', 'tuple': 'a sequence of unchangeable objects', 'dictionary': 'an un...
# Creating a variable, printing, then changing variable value and printing again message = "TIY 2.1" print(message) message = "TIY 2.2" print(message)
def make_shirt(size='large', message='I Love Python'): print(f"""You ordered a {size.lower()} and it says "{message}".""") # Large Shirt, Default Message make_shirt() # Medium Shirt, Default Message make_shirt(size='medium') # Small Shirt, "WUNDERWORLD" message make_shirt(size='small', message='WUNDERWORLD')
import csv import numpy as np import matplotlib.pyplot as plt from datetime import datetime filename = 'data/san_francisco_2018_temperature.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) # Automate temperature and station name indexes. tmax = '' tmin = '' name...
glossary = { 'string': 'a sequence of characters', 'variable': 'a value that can change, depending on conditions or on information passed to the program', 'list': 'a data structure that is a changeable ordered sequence of elements', 'tuple': 'a sequence of unchangeable objects', 'dictionary': 'an un...
def make_shirt(size, message): print(f"""You ordered a {size.lower()} and it says "{message}".""") # Positional Arguments make_shirt('medium', 'WUNDERWORLD') # Key Word Arguments make_shirt(size='medium', message='WUNDERWORLD')
active = True age = None price = None while active: print("How old are you?") age = int(input()) if age < 3: price = 0 active = False elif 3 <= age <= 12: price = 10 active = False elif age > 12: price = 15 active = False print(f"A {age}-year old pays ...
prompt = "Please tell us what you want on your pizza (Enter 'quit' when done):" print(prompt) active = True while active: topping = input() if topping.lower() == 'quit': active = False else: print(f"Adding {topping.lower()}...")
import matplotlib.pyplot as plt; plt.rcdefaults() import matplotlib.pyplot as plt from die import Die # Make two D6 dice. die_1 = Die() die_2 = Die() # Roll die and add results to a list. results = [die_1.roll() + die_2.roll() for roll_num in range(1000)] # Count the frequency of each number rolled and add it to a ...
pizzas = ['pepperoni', 'sausage', 'meat lovers'] for pizza in pizzas: print(f"I love {pizza} pizza!\n") print("I love all types of pizza!")
def decrypt(stream): def gen(): for i, c in enumerate(stream): c = ord(c) lo_bits = i & 0x03 if lo_bits == 0: yield c ^ 0x49 elif lo_bits == 1: yield c ^ 0x43 elif lo_bits == 2: yield c ^ 0x46 ...
""" a module that creates ascii art from images """ # Import an image processing tool from PIL import Image from json import dumps, loads from subprocess import call from time import sleep def main(file): """ main process that converts image and prints ascii art """ # enter choice choice = file ...
""" This script is written to create a widget for use in Lecture_1.ipynb. """ import pandas as pd from datascience import * import numpy as np import matplotlib import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') import ipywidgets as widgets plt.style.use('fivethirtyeight') ### data= Table().read_tabl...
''' This is a function called 'mathfun' where there are two parameters, n1 and n2. We can call 'mathfun' with the arguments n1 and n2 in the last line. n1 and n2 are input by the user. ''' # define the function, called 'mathfun' and put names of parameters inside parentheses def mathfun(n1, n2): # define variables...
#!/usr/bin/python import utils from binascii import hexlify, unhexlify def up(): '''We use a similar printf exploit as in addis_ababa (reading too many values off the stack) ''' #just some garbage, but: # - 0x12 so that it works as an address (or else crashes) # - 0x7f long because we're using...
##append 和extend区别 # a=[1,2,3] # b=[4] # a.append(b)##将整个列表插入到a # print(a) # a.extend(b)##插入列表元素 # print(a) # # c=[5,6,7] # a.append(c) # print(a) # # a=[1,2,3] # a.extend(c) # print(a) ##列表拓展方式 # import time # def dur(op,clock): # duration=time.time()-clock # print('%s finished.Duration %.6f seconds.' %(op,d...
# -*- coding: utf-8 -*- """ Create functions that output pseudo-random numbers """ # Range of the random numbers m = 2**25 # a-1 is divisible by all prime factors of m, # a-1 is a multiple of 4 if m is a multiple of 4 a = 184513*4+1 # c and m are relatively prime (pgcd(c, m) = 1) c = 1640393*2+1 # Linear...
''' =============================== A Test model about Perceptron =============================== Perceptron model with different order We can see the Perceptron will get different decision boundary ''' print(__doc__) ######################################################### # author : Quentin_Hsu ...
''' Created on May 20, 2013 @author: user ''' counter = {"25 cent":0,"10 cent":0,"5 cent":0,"1 cent":0} def display(): for keyvalue in counter.keys(): if keyvalue != 0: print "%s %s numbers" %(keyvalue,counter[keyvalue]) def dollorexchange(value): a = divmod(value,25) cou...
import matplotlib import matplotlib.pyplot as pyplot import numpy as np arr1 = list() arr2 = list() point = input("Enter No of points :") for i in range (int (point)): s = input() li = s.split() x = arr1.append(int (li[0])) y = arr2.append(int (li[1])) slope = [] intercept = [] xval1 = []...
# Given a string, write a function to check if it is a permutation of a palindrome # Input: Tact Coa # Output: True -- Ex: "taco cat", "atco cta" def palindromePermutation(str): str = str.lower().replace(" ", "") strdict = {} for c in str: if c in strdict.keys(): strdict[c] += 1 ...
""" We are writing a tool to help users manage their calendars. Given an unordered list of times of day when people are busy, write a function that tells us the intervals during the day when ALL of them are available. Each time is expressed as an integer using 24-hour notation, such as 1200 (12:00), 1530 (15:30), or 8...
# The function is expected to return a string. # The function accepts string as parameter. def logic(my_input): temp1='' list1=list(my_input) for i in range(0,len(my_input),4): if i+4>len(list1): break temp1=list1[i] list1[i]=list1[i+2] lis...
nterms=int(input('enter the no.')) n1=0 n2=1 count=0 if nterms<1 : print ("enter the positive no.") elif nterms==1 : print(n1) else: print(n1,',',n2,end=',') while count<nterms: nth=n1+n2 print(nth,end=',') count=count+1 n1=n2 n2=nth
# https://gist.github.com/lebedov/f09030b865c4cb142af1 """ Retrieve intraday stock data from Google Finance. """ import csv import datetime import re import pandas as pd from urllib.request import urlopen from _datetime import date def get_google_finance_intraday(ticker, period=60, days=1): """ Retrieve intr...
'''In Python, anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.''' double = lambda x: x * 2 print(double(5))...
# -*- coding: utf-8 -*- """ Created on Thu Sep 20 16:36:48 2018 @author: 123 """ class TreeNode(): def __init__(self, key, val, left=None, right=None, parent=None): self.key = key self.val = val self.leftChild = left self.rightChild = right self.parent = parent sel...
''' Created on 19 March 2017 @author: Nigel Fernandez ''' ''' The optimization is based on the fact that if the set of sums for a cell contains all numbers in [0, 50] then any cells on top of this cell will also contain [0, 50]. Recursively, we will finally reach the top cell which will contain the set of sums having...
def fizzbuzz(num1, num2): for number in range(1, 100 + 1): if number % num1 == 0 and number % num2 == 0: print('FizzBuzz') elif number % num2 == 0: print("Fizz") elif number % num1 == 0: print('Buzz') else: print(number) fizz...
#!/usr/bin/env python class Solution: def permute(self, s): results = [] self.helper("", s, results) return results def helper(self, prefix, leftOver, results): if not leftOver: results.append(prefix) for i in xrange(len(leftOver)): sel...
# Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их # окладов (не менее 10 строк). Определить, кто из сотрудников имеет оклад менее 20 тыс., # вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников. user_data_file_path = "Task_03_Data.txt" su...
# Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение. # При вызове функции должен создаваться объект-генератор. # Функция должна вызываться следующим образом: for el in fact(n). # Функция отвечает за получение факториала числа, # а в цикле необходимо выводить только первые n ч...
# Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку. print(f"Result: {[value for value in range(20, 240) if value % 20 == 0 or value % 21 == 0]}")
# Пользователь вводит строку из нескольких слов, разделённых пробелами. # Вывести каждое слово с новой строки. Строки необходимо пронумеровать. # Если в слово длинное, выводить только первые 10 букв в слове. # Get user data and generate words collection original_string = input("Please input your words separated by whi...
# Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. # В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия. # Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. import sys def calculate_salary(pri...
# -*- coding: utf-8 -*- """ Created on Fri May 4 00:13:07 2018 @author: paul """ okchar = "hlc" info = "a" low = 0 high = 100 guess = int((low+high)/2) print('Please think of a number between 0 and 100!') print('Is your secret number ' + str(guess) + ' ?' ) info = input('Enter h to indicate the gue...
# -*- coding: utf-8 -*- from Tkinter import * root = Tk() li = 'Diego Matias Martin Carla Lorena Roberto'.split() mov = 'los juegos del hambre Cars La caida del halcon negro'.split() listb = Listbox(root) listb2=Listbox(root) for item in li: listb.insert(0, item) for item in mov: listb2.insert(0, item) listb...
# -*- coding: utf-8 -*- calif=int(input("Cual es el porcentaje que saco el empleado: ")) if calif>=90: print ("Obtuvo el nivel maximo_ ") elif calif>=75 and calif<90: print ("obtuvo el nivel medio_ ") elif calif>=50 and calif<75: print ("obtuvo el nivel regular_ ") elif calif<50: print ("Esta fuera de n...
# -*- coding: utf-8 -*- class animal(): def __init__(self, nombre): self.nombre = nombre self.patas = 4 self.tipo = "can" x = animal("Tobys") #y = animal() print (x.nombre) print (x.patas) print (x.tipo)
# -*- coding: utf-8 -*- class Empleado: def __init__(self): self.nombre=input("Nombre del empeado: ") self.sueldo=float(input("Sueldo del empleado: ")) def imprimir(self): print ("NOMBRE: ",self.nombre) print ("SUELDO: ",self.sueldo) def impuestos(self): if self.su...
# coding : utf-8 #-------------------------------------------------------------------- # IMPORT #-------------------------------------------------------------------- #My own libraries and classes from Classes.categorie import Categorie from Classes.product import Product #Python libraries a...
# coding : utf-8 class Brand: """Brand of a product brands_tags : name of the brand (str)""" def __init__(self, brand_tags): self.brand_tags = brand_tags.lower() #-------------------------------------------------------------------- # METHODS #---------------------------...
peso = float(input('Digite o peso em kg: ')) alt = float(input('Digite a altura em m: ')) imc = peso/pow(alt, 2) print() if imc < 18.5: print('Seu imc é {:.2f}. Você está abaixo do peso'.format(imc)) elif 18.5 <= imc < 25: print('Seu imc é {:.2f}. Você está com peso ideal'.format(imc)) elif 25 <= imc < ...
# Área da parede n1 = float(input('Qual a altura da parede em m? ')) n2 = float(input('Qual a largura da parede em m? ')) print() print('A área da parede é: {} m². Considerando que 1l de tinta pinta 2 m², você vai gastar {:.2f}l de tinta.'.format(n1*n2, n1*n2/2))
# Ordem de apresentação from random import shuffle al1 = input('Qual o nome do primeiro aluno? ') print() al2 = input('Qual o nome do segundo aluno? ') print() al3 = input('Qual o nome do terceiro aluno? ') print() al4 = input('Qual o nome do quarto aluno? ') lst = [al1, al2, al3, al4] shuffle(lst) print() ...
# Adivinhando número import random, time pensador = random.randint(0, 5) numero = int(input('Digite um número de 0 a 5: ')) print() print('Processando ...') time.sleep(5) if numero == pensador: print('Parabéns!!! Você escolheu {} e o computador também escolheu {}.'.format(numero, pensador)) else: prin...
# Adivinhando número com while import random, time pensador = random.randint(0, 10) numero = int(input('Digite um número de 0 a 10: ')) cont = 1 while numero != pensador: cont += 1 print() print('Processando ...') time.sleep(1) print() numero = int(input('Numero errado. Digite outro n...
# Sorteio de alunos import random al1 = input('Qual o nome do primeiro aluno? ') print() al2 = input('Qual o nome do segundo aluno? ') print() al3 = input('Qual o nome do terceiro aluno? ') print() al4 = input('Qual o nome do quarto aluno? ') lst = [al1, al2, al3, al4] escolhido = random.choice(lst) print() ...
num1 = int(input('Digite um número inteiro: ')) print() num2 = int(input('Digite outro número inteiro: ')) print() if num1 > num2: print('O número {} é maior que {}.'.format(num1, num2)) elif num1 < num2: print('O número {} é menor que {}.'.format(num1, num2)) else: print('Os números são iguais.') ...
# Matriz 3 x 3 e cálculos lista = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] soma = maior = somapar = 0 for i in range(0, 3): for j in range(0, 3): lista[i][j] = (int(input(f'Digite o elemento [{i}][{j}]: '))) print() print('=' * 40) for i in range(0, 3): for j in range(0, 3): print(f'[{lista[i...
# Média de notas de alunos import statistics lista1 = [] lista2 = [] while True: aluno = str(input('Digite o nome do aluno: ')) nota1 = float(input('Digite a primeira nota: ')) nota2 = float(input('Digite a segunda nota: ')) lista1.append(aluno) lista2.append(nota1) lista2.append(nota2...
# Lista e funções sorteia e soma par. import random, time lista = [] def sorteia(): print('Os valores sorteados foram: ', end=' ') for i in range(0, 5): sorteio = random.randint(0, 100) print(f' {sorteio}', end=' ') time.sleep(1) lista.append(sorteio) def somaPar(): ...
# Soma de vários números, média, maior e menor. Uso de fstring. numero = i = soma = media = menor = maior = 0 cont = 0 teste = 'S' while teste == 'S': numero = int(input('Digite um número inteiro: ')) cont += 1 soma += numero if cont == 1: menor = numero maior = numero els...
import pygame import time import random #Wither- adding a block that shortens the snake. if 0 you die pygame.init() #global variables white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 155, 0) display_width = 800 display_height = 600 gameDisplay = pygame.display.set_mode((displa...
import math as m import webbrowser import time def LCM(a, b): if a > b: greater = a else: greater = b while (True): if ((greater % a == 0) and (greater % b == 0)): lcm = greater break greater = greater + 1 return lcm def Factorial(n): if n!=...
from board import Board, QBoard, Move class Checkers: def __init__(self,size=10,population=3): self.environment = Board(size,population) self.player_turn = 1 def tstart(self,debug=False): while not self.environment.finished: self.ask_for_next_move(deb...
""" server.py - host an SSL server that checks passwords CSCI 3403 Authors: Matt Niemiec and Abigail Fernandes Number of lines of code in solution: 140 (Feel free to use more or less, this is provided as a sanity check) Put your team members' names: """ import socket from Crypto.Pub...
# encoding: utf-8 """ It will create .txt-file for each .jpg-image-file - in the same directory and with the same name, but with .txt-extension, and put to file: object number and object coordinates on this image, for each object in new line: <object-class> <x_center> <y_center> <width> <height> Where: <object-class...
# Calculating my Body Mass Index (BMI) #latest commit #latestest commit print("Dimitri BMI") weight = float(input('Enter Dimitri weight: ')) height = float(input('Enter height: ')) BMI = weight/(height **2) print ("Dimitri, your super BMI is", BMI)
ramit = { 'name': 'Ramit', 'email': 'ramit@gmail.com', 'interests': ['movies', 'tennis'], 'friends': [ { 'name': 'Jasmine', 'email': 'jasmine@yahoo.com', 'interests': ['photography', 'tennis'] }, { 'name': 'Jan', 'email': 'jan@hotmail.com', 'interests': ['movies',...
list_of_nums = [2, 123, 96, 123, -2221, 58, 42, 77, 33] def only_evens(list_of_nums): new_list = [] for number in list_of_nums #check if number is even if number % 2 == 0: #if yes, store in new list return new_list
# # SimpleAI Traveling Salesman Problem # Author: Aaron Hung # Date: 5/05/15 # Purpose: Traveling Salesman Problem solution using SimpleAI's framework for state space search using Hill Climbing algorithm. # from simpleai.search import SearchProblem, hill_climbing_random_restarts from simpleai.search.viewers i...
print("hello world") print('hello world') #print("This is cool :emoji") #this works with python 3 ctrl+command+space #single line comment """ multi line comment - use triple quotes single/double this is interesting """ ''' another way of multi line comment this is also cool ''' commentStr = """** Multi line commen...
''' Classes have instance and class Variables Class vars: are common for all instance vars: are specific to the instance '''' class Student: print("hello student") info = "This is a student" student1 = Student() #Instance Variables student1.name = "Neha" student2 = Student() student2.name = "Parth" s...
### Conditional ### # simple conditional number = 8 if number % 2: print "The number is odd." else: print "The number is even." # zero test before division num = 20 dnom = -3.7 if dnom != 0: print num/dnom # without else, but with elif s = "00041" print s, " is " if len(s) > 4: print "too long" elif len(s) < 4:...
### List ### # list of numbers x = [1,2,3,5,4] print x x.append(0) print x print x[1] print x[0] print x[2:] print x[:-1] print x[2:4] # get length of a list print len(x) print len(x[2:4]) # sort list print x x.sort() print x # list of strings y = ["John", "Jane", "Charlene", "Paul"] print y y.reverse() print ...
#! /bin/python3 import sys import array import numpy def sortchar(teststring): print(teststring[::2], teststring[1::2]) def main(): testlines = int(input().strip()) linearr = [] for n in range(0, testlines): linearr.append(input()) for x in range(0, testlines): print(linearr[x][::...
""" #判斷何種三角形 當三個邊長能構成三角形時,再判斷該三角形是否為正三角形,若否,則判斷是否為等腰三角形: 1. 不能成為三角形:任兩邊和不大於第三邊,或任一邊長不大於0。 2. 正三角形:三個邊相等。 3. 等腰三角形:任兩邊相等,平方和大於第三邊的平方。 4. 一般三角形:非正三角形與等腰三角形。 此題必須寫一個運算的function int getTriangle(int a, int b, int c); 輸入說明: --------------- 輸入三個整數邊長 輸出說明: --------------- 1. 不能成為三角形:輸出 not triangle。 2. 正三角形:輸出...
""" #數值運算 分別輸入 num1 num2 求出兩數的 Sum,Difference,Product,Quotient。 結果須輸出到小數點第二位 print("%.2f" %x1); 輸入: 25 2 輸出: Difference:23.00 Sum:27.00 Quotient:12.50 Product:50.00 """ import math def cal(a,b): sum=a+b de=math.fabs(a-b) quo=a/b pro=a*b return sum,de,quo,pro def main(): ...
##########FUNCTION############ #If the length of the text is less than the length #of the string then return false and if #the text starts with the string then return true #else stop from reaching max recursion depth def find(text, string): if (len(text) < len(string)): print(string, " does not match...
#using 'yield' to compute primes 'on demand' def naturals(n): yield n yield from naturals(n+1) #creating generator object: naturals s=naturals(2) #obtaining primes by sieving through natural number list def sieve(s): n=next(s) yield n yield from sieve(i for i in s if i%n!=0) #creating generator ...
import math from math import sqrt; from itertools import count, islice num = int(input("Please enter an integer: ")) def is_Prime(num): return all(num%i for i in islice(count(2), int(sqrt(num)-1))) def main(): if is_Prime(num): print (num, "is a prime number") else: print (num, "...
#ten_things = ("Apples Oranges Crows Telephone Light Sugar") #first_list = ten_things.split(' ') #print (first_list) more_things = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] second_list = more_things.split(',') print (second_list)
import sys for line in sys.stdin: n = int(line) # The key for this problem is to realize that if you have less printers than # the number of statues to be printed, the optimal strategy is to simply # let all the printers print a new printer. p = 1 #number of printers at start days = 0 #number of days that have p...
import math def sum_squares(range): i = 0 result = 0 while i < range + 1: result += i * i i+=1 return result def square_sum(range): i = 0 result = 0 while i < range+1: result += i i+=1 return result * result def find_dif(range): return square_sum(ra...
import math def sieve_of_eratosthenes(limit = 125): sieve = [True] * limit sieve[0] = sieve[1] = False for (i, isprime) in enumerate(sieve): if (isprime): for n in range(i * i, limit, i): sieve[n] = False return sieve print(sieve_of_eratosthenes(100)) def is_prime...
''' Crie um programa que recebe dois valores reais inseridos pelo usuário e imprima o maior deles. ''' #Função que verifica se o numero é inteiro# def valor_inteiro(): numero=int(input('Digite um numero : ')) if numero > 0 : print('O numero é maior que 0') elif numero < 0 : print('O numero é...
# Problem 8 # # The four adjacent digits in the 1000-digit number that have the # greatest product are 9 × 9 × 8 × 9 = 5832. # # [See 0008.txt] # # Find the thirteen adjacent digits in the 1000-digit number that have # the greatest product. What is the value of this product? import functools import operator import tim...
# Problem 4 # # A palindromic number reads the same both ways. The largest palindrome # made from the product of two 2-digit numbers is 9009 = 91 × 99. # # Find the largest palindrome made from the product of two 3-digit # numbers. import eutils.strings as strings import time start = time.time() digits = 3 ans = 0 f...
print("+++++++++++++++++++++++++++++++++++++++++") print("+ Welkom bij de cluedo rollen zoektocht +") print("+++++++++++++++++++++++++++++++++++++++++") print("+ Wij gaan je hier wat vragen stellen +") print("+ om te kijken of je geschikt bent +") print("+ voor 1 van onze vele rollen. +") print("+++++++...
import pygame, math from pygame.locals import * class loadSprite(): '''This should be where the sprite is processed into a pygame usable image and a couple other functions we might use related to sprites aswell''' def __init__(self, spriteImagePath): '''Initial atributes of the the image''' self.sprite = pyga...
"""Provide motion profiles for smooth and efficient motion""" import math from .utils import RobotCharacteristics, phase_time, signum class PositionProfile: """Motion profile representing a specific desired move Resolves time to optimal position """ def __init__(self, robot: RobotCharacteristics, ...
#!/usr/bin/env python3 def validate_user(username, minlen): # assert is used in situations that are not expected, but may cause our code to misbehave. assert type(username) == str, "username must be a string" if minlen < 1: # use raise to check for conditions that are expected to # happen ...
import unittest #unnitest module import import pyperclip from user import User class TestUser(unittest.TestCase): ''' Test class that defines the test cases for user class behaviours ''' def setUp(self): ''' Setup method to run before each test cases ''' self.new_u...