text
stringlengths
37
1.41M
# ************************************************************ # Bike assinment is in this file # # class User: # # pass # # michael = User() # # anna = User() # # print(michael,anna) # class User: # def __init__(self,name,email,num): # self.name = name # self.e...
__author__ = 'student' import turtle def draw(l,n): if n == 0: turtle.forward(l) return draw(l/4,n-1) turtle.left(90) draw(l/4,n-1) turtle.right(90) draw(l/4,n-1) turtle.right(90) draw(l/4,n-1) draw(l/4,n-1) turtle.left(90) draw(l/4,n-1) turtle.left(90) ...
import time respuesta = 0 sino = "si" lista =[] while sino == "si": print("Dime una palabra") respuesta = input() lista.append(respuesta) sino = input("Quieres añadir otra palabra mas? si/no\n") for i in lista: print(i) time.sleep (0.65)
""" - Create a script called `[seed.py](http://seed.py)` that populates a SQLite database. By default it should search for the first 150 users from GitHub but the script should accept a param called `total` to customize the number of users. - The fields required for this users are: - username - id - image u...
import unittest import game, player, board class TestGameCheckMove(unittest.TestCase): def test_check_move_valid(self): test_game = game.Game("Player1", "Player2") valid = test_game.check_move((0, 0), test_game.players[0]) self.assertTrue(valid) def test_check_move_invalid(self): ...
var1 = 'hello' var2 = 32 var3 = 36.7 print(type(var1)) print(type(var2)) print(type(var3)) #typecasting var1 = "52" var2 = "34" print((var1)+var2) #typecasting print(int(var1)+int(var2)) var1 = "54" var2 = "32" print(10*int(var1) + int(var2)) #wanna print any thing multiple tyms then we do print(10 * "h...
# Python Basic print("enter no a") a= int(input()) print("enter no b") b= int(input()) addition = a + b print("addition is:", addition) print("type",type(addition))
# Python program for Addition of two integers print("Enter first number ") a= input() print("Enter second number") b= input() addition = a+b print("Addition is:", addition)
# open the text of much ado about nothing and read it in line by line # count the number of lines by Beatrice # for this one, let's just annotate the lines with what is happening file_path = "ado.txt with open (file_path, 'w') as file_input: text = file_input.readline() benedickt_lines = {} counters = 0 for line...
import nltk # given a text file, print the first 100 text characters of it def read_file(path_to_text): # take a file path and return the raw text from it with open(path_to_text, 'r') as fin: raw_text = fin.read() return raw_text def split_text(raw_text): # takes a text and splits it into a se...
# given a file path, store and print it text_path = 'woolf.txte' # hint - it might have worked, but is the output correct? Not all errors are errors Python can detect! print(text_pathed)
# Module dedicated to data wrangling functions import pandas as pd # Función hacer_df() de mining_tb que recibe como parámetro un archivo de excel, hace un dataframe con sólo la primera hoja y sólo las 2 primeras columnas poniendo como índice la primera y, luego, mediante un for va recorriendo el resto de las hojas co...
########################################################################################################### # What this is: Webpage scraper for the Forbes 2000 List # Purpose: Take a list of URLs from CSV, scrape the associated webpages for # the company details, and save as C...
score = 0 First_name = input("What is your First name?") Last_name = input("What is your Last name?") age = input("What is your age?") print("Hello " + First_name + " " + Last_name) print("Welcome to a Nation Wide PANDEMIC") print("Let's see how much you know about Covid-19") # Question 1 answer1 = input("How many c...
''' @file: Question5-lab1.py @author: James Rolfe @updated: 20170130 ''' import random import numpy as np import matplotlib.pyplot as plt # constant declaration LOW_BOUND = 0 HIGH_BOUND = 1 # number of samples taken NUM_OF_SAMPLES = [25, 10, 50, 100, 500, 1000] # number of data points per sample NUM_O...
""" @filename: lms.py @author: James Rolfe @date: 20170327 @reqs: LMSalgtrain.csv, LMSalgtest.csv """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.metrics import mean_squared_error TRAIN_CSV = 'LMSalgtrain.csv' TEST_CSV = 'LMSalgtest.csv' def ...
import sys import collections RetVal = collections.namedtuple('RetVal', ['count', 'array']) def merge_and_count(left_arr, right_arr): arr = [] count = 0 j = 0 k = 0 for i in range(len(left_arr) + len(right_arr)): if j == len(left_arr): arr.append(right_arr[k]) k = ...
#1 name = str("Angelina") print(name) #2 age = int(24) print(age) #3 a = float(4.5) print(a) #4 n = bytes(8) print(n) #5 new_list = list() name_1 = "Angelina" name_2 = "Vadim" name_3 = "Vladislaw" new_list =[name_1, name_2, name_3] for i in new_list: print('name =' , i) #6 k = tuple('hello, world!') print(k) #7 s =...
# Given a non-empty array of decimal digits representing a non-negative integer, # increment one to the integer.The digits are stored such that # the most significant digit is at the head of the list, and each element # in the array contains a single digit. # You may assume the integer does not contain any leading zer...
# Given a sorted array of distinct integers and a target value, # return the index if the target is found. # If not, return the index where it would be if it were inserted in order. def searchInsert(nums: list, target: int) -> int: pos = 0 if target in nums: return nums.index(target) else: ...
#Написать функцию arithmetic, принимающую 3 аргумента: первые 2 - числа, #третий - операция, которая должна быть произведена над ними. # Если третий аргумент +, сложить их; если —, то вычесть; * — умножить; # / — разделить (первое на второе). В остальных случаях вернуть # строку "Неизвестная операция". def arithme...
from prac_08.car import Car import random class UnreliableCar(Car): """Special version of car that includes unreliability""" def __init__(self, name, fuel, reliability): super().__init__(name, fuel) self.reliability = reliability def drive(self, distance): """Drive the car a given ...
""""Matthew Rooke""" MIN_LENGTH = 5 def main(): password = get_password() print_hidden_length(password) def print_hidden_length(password): for character in range(len(password)): print("*", end="") def get_password(): password = input("Enter your password:") while len(password) < MIN_L...
import random from heapq import * # Quicksort routine for given collection of elements. # Simple version defined in wikipedia (uses O(n) memory) def quicksort(elements): # If one or zero elements, then just return (technically already sorted) if (len(elements) <= 1): return elements else: ...
def mean(vals): """Calculate the arithmetic mean of a list of numbers in vals""" assert type(vals) is list, 'input must be list' ivals = [] for n in vals: ivals.append(float(n)) if ivals == []: return 0 else: total = sum(ivals) length = len(ivals) return total/length print(ivals) #print(mean("hel...
""" unosi se cetvorocifreni broj odrediti broj koji se dobija zamjenom trece i druge cifre """ broj = (input("Unesite cetvorocifreni broj ")) cifra1 = int(broj[0]) cifra2 = int(broj[1]) cifra3 = int(broj[2]) cifra4 = int(broj[3]) broj2 = cifra1*1000+cifra3*100+cifra2*10+cifra4 print(broj2)
import json EUR_FILE = 'eur-gbp-2001.json' GBP_FILE = 'gbp-eur-2001.json' def get_forex_data(file_name): with open(file_name, 'r') as file: eur_data = json.load(file)["Time Series FX (Daily)"] euro_daily = [] for day in sorted(eur_data): euro_daily.append((day, eur_data[day]["4. close"])...
import click def manual_fitness(dnr: list) -> int: print(dnr) score = input("Enter score> ") return int(score) def random_dnr(size: int, seq: list) -> list: from random import choice return [choice(seq) for _ in range(0, size)] def evaluate(population: list, fitness_fn: callable) -> list: ...
print("Enter a string") strn = input() print("The String is") print(strn) print(strn[1:]) print(strn[2:]) print(strn[:1:-1])
a = 21 b = 10 c = 0 c = a + b print("Value of addition is ", c) c = a - b print(" Value subraction is ", c ) c = a * b print(" Value of multiplicationis ", c ) c = a / b print ("Value of division is ", c ) c = a % b print (" Value of remainder is ", c)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def partition(self, head: ListNode, x: int) -> ListNode: if not head or not head.next: return head head_lt, head_ge = No...
def pow(n): def inner(x): return x ** n return inner if __name__ == '__main__': cube = pow(3) print(cube(10))
class Solution: def minimumPathCost(self, triangle): ''' :type triangle: list of list of int :rtype: int ''' height = len(triangle) row = height - 2 while row >= 0: for i in range(row + 1): # the number elements in equal the # of the row ...
from numpy import exp, array, random, dot class NeuralNetwork(): def __init__(self): # Seed the random number generator, so it generates the same numbers # every time the program runs. random.seed(1) # initialize weights randomly with mean 0 self.synaptic_weights...
import Materials class Cage: """This class describe one cell""" temperature = None material = None mass = None upd_q = None # q that cell get from other cells fraction = 0 # parameter that is used for change effective_mass checker_transformation = True # exit criteria # const dx...
## Basic Controls elevatorFloor01 = 1 elevatorFloor02 = 1 elevatorFloor03 = 1 elevatorFloor04 = 1 elUser = 1 system = "on" while system == "on": elevatorFloor01int = str(elevatorFloor01) elevatorFloor02int = str(elevatorFloor02) elevatorFloor03int = str(elevatorFloor03) elevatorFloor04int = str(elevat...
# -*- coding: utf-8 -*- """ Created on Tue Sep 14 16:17:49 2021 @author: carmine """ # 7. Реализовать генератор с помощью функции с ключевым словом yield, # создающим очередное значение. При вызове функции должен создаваться # объект-генератор. Функция должна вызываться следующим образом: # for el in fact(n). Функция...
# -*- coding: utf-8 -*- """ 1. Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год». В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать число, месяц, год и преобразовывать их тип к типу «Число». Второй, с декораторо...
from disjointsets import Node,DisjointSets ds = DisjointSets() nodes = [] mst=[] def krus(vert, weight): for i in vert: node = ds.makeset(i) nodes.append(node) print(vert) print(weight) for i in weight: if(ds.union(nodes[i[0]],nodes[i[1]])): mst.append((i[0],i[1])) ...
def fib_iter(n): f1 = 0 f2 = 1 n-=2 print(f1) print(f2) while(n): f3 = f1 + f2 n-=1 print(f3) f1 = f2 f2 = f3 def fib_rec(n): if(n<=1): return n else: return fib_rec(n-1) + fib_rec(n-2) def main(): n = int(input()) print("Iterative: ") fib_iter(n) print("Recursive: ") for i in range(n): p...
def fact_iter(n): fact = 1 for i in range(1,n+1): fact*=i return fact def fact_rec(n): while(n>0): if (n <= 1): return 1 return n*fact_rec(n-1) def main(): n = int(input()) print("Iterative: " + str(fact_iter(n))) print("Recursive: " + str(fact_rec(n))) main()
# -*- coding: utf-8 -*- """ Created on Fri Mar 26 22:58:47 2021 @author: Immanuel """ import datetime import random print("WELCOME TO BANK OF OJI!!!") print("Insert Your Card Here") atmpin = 3005 #we will store the atm pin here# transaction = ["Check Balance","Deposit Money","Withdrawal", "Transfer",...
import numpy as np from main import * """ Ant class """ class Ant: def __init__(self, initial_location, colony): self.path = [initial_location] # Path starts with initial location. self.initial_location = initial_location self.colony = colony self.location = initial_location self.distance_travelled = 0 ...
import random # Split string method names_string = input("Give me everybody's names, separated by a comma. ") names = names_string.split(", ") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 l = len(names) i = random.randint(0,l-1) print(names[i] + " is going to buy the meal today!" + str(l)...
# Method 1 # with open("Working with CSV\weather_data.csv") as f: # data = f.readlines() # print(data) # Method 2 # import csv # with open("Working with CSV\weather_data.csv") as f: # output = csv.reader(f) # temperatures = [] # for row in output: # if row[1]!="temp": # temperat...
#Step 1 import random from HangMan_Art import logo from HangMan_Art import stages from HangMan_Words import word_list print(logo) # word_list = ["aardvark", "baboon", "camel"] #TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word. word = random.choice(word_list) l = [] f...
from turtle import Turtle FONT = ("Courier", 24, "normal") class Scoreboard(Turtle): def __init__(self): super().__init__() self.level = 1 self.penup() self.color("black") self.goto(-280,250) self.hideturtle() self.updateScoreboard() def updateScoreboar...
# Your program should print each number from 1 to 100 in turn. # When the number is divisible by 3 then instead of printing the number it should print "Fizz". # `When the number is divisible by 5, then instead of printing the number it should print "Buzz".` # `And if the number is divisible by both 3 and 5 e.g. 15 t...
# Authors: Amulya Badineni, Michael Giordano, Rishi Konkesa, Jason Swick # Filename: train.py # Description: Implements a training example generator that generates random instances import random # TrainingExample object: will hold values for each attribute in a given training example. Also has "EnjoySport", which is ...
import random print ("Welcome to Camel!") print ("You have stolen a camel to make your way across the great Mobi desert.") print ("The natives want their camel back and are chasing you down!") print ("Survive your desert trek and out run the native.") done = False miles_traveled = 0 thirst = 0 energy = 0 natives_distan...
from enum import Enum import random from os import system, name from time import sleep def clear(): if name == 'nt': _ = system('cls') def attackDice(x): if(x > 3): return 3 elif(x == 3): return 2 elif(x == 2): return 1 else: return 0 def defDice(x): if(x...
with open("01_input.txt") as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line def calc_fuel(mass): return (mass / 3) -2 content = [x.strip() for x in content] total_fuel = 0 for mass in content: this_fuel = calc_fuel(eval(mass)) print this_fuel...
# choose your own adventure game #background story for adventure print ("You are feeling hungry and decide to eat an apple.") print ("Little do you know, this apple has magical properties and transports you to another dimension.") print ("You find yourself in a dark, mysterious woods, and are surrounded by tall trees....
# -*- coding:utf-8 -*- class Solution: def __init__(self): self.stack1=[] self.stack2=[] def push(self, node): # write code here while(self.stack2): self.stack1.append(self.stack2.pop()) self.stack1.append(node) def pop(self): # return xx while(self.stack1): self.stack2.append(self.stack1.pop()) ...
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): if n==0: return 0 if n <= 2: return 1 num1 = 1 num2 = 1 while (n-2): num1,num2 = num2,num1+num2 n -= 1 return num2 s = Solution() print(s.Fibonacci(3))
#Tarea1.Ejercicio5 precio=float(input('Cuanto cuesta: ')) peso=float(input('Cuanto pesa: ')) descuento=0 if peso>=2.01 and peso<=5: descuento=0.10 if peso>=5.01 and peso<=10: descuento=0.15 if peso>=10.01: descuento=0.20 pagar=peso*peso*(1-descuento) print (pagar)
#Fibonacci n=int(input('Termino n: ')) i=2 a=1 b=1 while not (i==n): c=a+b a=b b=c i=i+1 print (c)
#Cinematica import numpy import matplotlib.pyplot as plt vx=float(input('Velocidad en x: ')) x0=float(input('Posicion inicial x: ')) vy=float(input('Velocidad en y: ')) y0=float(input('Posicion inicial y: ')) tfinal=float(input('Tiempo de observacion: ')) tiempo=numpy.zeros(tfinal,dtype=float) posicionx=numpy.zeros(t...
#!/bin/python """ This program will summarize fasta files for sequence length. Outputs total, median, mean, quartiles """ import sys import numpy def median(lst): return numpy.median(numpy.array(lst)) def mean(lst): return numpy.mean(numpy.array(lst)) def FASTA(filename): try: f = file(filename) ex...
import json JSONDATA = None with open('base.json') as f: JSONDATA = json.load(f) origen = input("Nombre de la carpeta donde se busca el archivo: ") destino = input("Nombre del archivo: ") ruta=[] def buscar(inicio,valor): ruta.append(inicio) if inicio==valor: return valor ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint def prepare(): cnt = 10 return [randint(0, cnt) for _ in range(cnt)] def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] # compare avg O(N^2) best O(N) worst O(N^2) # swap avg O(N^2) best O(0) worst O(N^2) def insertion_sort(arr):...
name = input("What is your name?") quest = input("What is your quest?") color = input("What is your favorite color?") print("poop") print ("Ah, so your name is %s, your quest is %s, ") print ("and your favorite color is %s." % (str(name), str(quest), str(color))
def Solution(put): cities = list(range(len(put))) solution = [] for i in range(len(put)): CityA = cities[0] solution.append(CityA) cities.remove(CityA) return solution def routeLength(put, solution): routeLength = 0 for i in range(len(solution)): ...
a = input("your name : ") print("hello "+a+"!")
import numpy as np class Reflection: """ Class for calculating the reflection of vector a, through the orthogonal matrix of vector v """ def __init__(self,v): """ Define the vector v """ self.v = v def __mul__(self, a): """ Calculate the matrix prod...
print("hello world") print("/_____|") print("/_____|") print("/_____|") print("/_____|") Person_name = "John Doe" Person_income = "4" print(Person_name + " is a fine man with several income sources, " + Person_income + " of which comes from IT") person_name = "Habeeb Hand" # person_Income = "44"; person_Income = 4 # ...
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ import math def productabc(): for x in range(math.ceil(math.sqrt(250)), m...
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ def nthPrime(n): x = 1 primes = [] while(len(primes) < n): x += 1 for y in primes: if x % y == 0: break else: primes.append(x) return x print(nthPrime(10...
#! python3 # Creating a circular queue def ArrayQueue(): DEFAULT_SIZE = 10 def __init__(self): self._data = [None]*DEFAULT_SIZE self._size = 0 self._front = 0 def __len__(self): return len(self._data) def is_empty(self): return self._data == 0 def fi...
#! python3 class PositionalList(_DoubleLL): class Position: def __init__(self,container,node): # What's a container self._container = container self._node = node def element(self): return self._node._element def __eq__(self,other): re...
__author__ = 'adm' from datetime import * import time class TimeCounter: def get_zero_year(self, seconds): current_year = datetime.now().year one_year_in_seconds = 365*24*60*60 years_passed = int(seconds / one_year_in_seconds) zero_year = current_year - years_passed return ...
#!/usr/bin/env python # coding: utf-8 """ author -- ToxaZ Couresera Machine Learning Introduction 2nd week assignement 1 - https://www.coursera.org/learn/vvedenie-mashinnoe-obuchenie/programming/u08ys/priedobrabotka-dannykh-v-pandas 2 - https://www.coursera.org/learn/vvedenie-mashinnoe-obuchenie/programming/DVbEI/vazh...
import json f = open('org.json') data = json.load(f) x = input() target1= x y = input() target2 = y p1=[] #recursive function to find parent def find_p(e1): for element in reversed(data): #print(data[element]) li=data[element] print(li) # print(li[0]['name']) for item i...
#REFERENCE # SLIDES: http://www.cs.jhu.edu/~langmea/resources/lecture_notes/hidden_markov_models.pdf # SOURCE CODE: https://nbviewer.jupyter.org/gist/BenLangmead/7460513 import numpy as np import math class HMM(object): ''' Simple Hidden Markov Model implementation. User provides transition, emission an...
#!/usr/bin/env python3 import sys for line in open(sys.argv[1]): if line[0]==">": name=line.strip() else: l = len(line.strip()) if l >= int(sys.argv[2]): print(name) print(line.strip())
# How much longer am I expected to live, given my sex, age, and country? import requests import csv import datetime import math # PARAMETERS: # sex sex = ['male', 'female'] # country c_url = 'http://api.population.io:80/1.0/countries' # get the available list of countries c = requests.get(c_url) c_list = c.json()...
def main(): # Numerical datatype # whole number - int - integer value = 13 number = 7 # float = decimal number float_value = 4.20 # str - strings name = "Emma" other_name = "Mary" # complex number # logical datatype # Boolean - bool done = False run = True #...
try: name = input("Insira o nome do produto: ") qunt = int(input("Insira a quantidade comprada: ")) value = float(input("Insira o valor da unidade: ")) percent = float(input("Insira a porcentagem do desconto (entre 0 e 100): ")) print("Você comprou %s e gastou R$%.2f " % (name, qunt*value*(percent...
num = input("Insira o número: ") count = 0 for char in num: count+= 1 print("O número tem %d dígitos" %(count))
num = int(input("Insira o número: ")) actual = 0 previous = 0 result = '' count = 0 while(count != num+1 ): if count == 0: result +=str(actual+previous)+' ,' previous = 0 actual = 1 elif count == 1: result +=str(actual+previous)+' ,' else: result += str...
p = tuple(map(float, input("Insira as coordenadas do ponto: ").split())) if p[0] * p[1] > 0: if p[0] > 0: print("Primeiro quadrante " + str(p[0]) + " " + str(p[1])) else: print("Terceiro quadrante " + str(p[0]) + " " + str(p[1])) elif p[0] * p[1] < 0: if p[0] < 0: print("Segundo qua...
class GeneralizationTreeNode: def __init__(self, value): self.father = None self.level = 0 self.value = value self.son = None self.bro = None self.tree_height = None def search_node_value(self, value): node = None if value == self.value: ...
## Adapted from http://scikit-learn.org/stable/auto_examples/plot_learning_curve.html import matplotlib.pyplot as plt from sklearn.learning_curve import learning_curve import numpy as np def graphLearningCurves(forest, X, y): # assume classifier and training data is prepared... train_sizes, train_scores, test...
import algorithm spc_to_name = 37 spc_to_sent = 25 script_name = "shrek.txt" subs_name = "shreksubs.txt" num_of_max = 3 num_of_min = 3 # Functions done on TXT files (srt and script) preparing for analysing algorithm.script_clean(script_name, spc_to_name, spc_to_sent) algorithm.clean_subtitles(subs_name) algorithm.c...
def fib(n): if n < 2: return n else: a, b = 0, 1 for i in range(2, n + 1): a, b = b, a + b return b def fib_big(n): n = n % 60 print(fib(n) % 10) n = int(input()) fib_big(n)
HIGHEST_NUMBER = 1000 def isprime(number): #print "Checking isprime() for:", number if number < 1: return False for i in range(2,number): if number%i == 0: return False return True for number in reversed(range(1,HIGHEST_NUMBER+1)): #print "Current number is:...
import os import csv election_data = os.path.join("..","Python-challenge","PyPoll","Resources","election_data.csv") #csvpath = os.path.join("\\Users\\Propietario\\Desktop\\TASKS_SGL\\Python\\Python-challenge\\PyPoll\\Resources\\election_data.csv") #In addition, your final script should both print the analysis to the ...
#DSC 510 #Week 10 #Final Project #Author Tiffany Tesoro #08/09/2020 #TO USE API TO GET DATA import json import requests #Use the Requests library in order to request data from the webservice. #DEFINE USER_INPUT FUNCTION def user_input(): print() #Create a Python Application which asks the user for their z...
#DSC 510 #Week 10 #Programming Assignment Week 10 #Author Tiffany Tesoro #08/09/2020 #TO FORMAT TOTAL PRICE import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') #locale.setlocale(locale.LC_ALL, '') did not work for me #REFERENCE https://stackoverflow.com/questions/14547631/python-locale-error-unsupported-l...
# Katie Simek # 26/07/2020 # Create a program that imports a txt file, then calculate the total words, and output # the number of occurrences of each word in the file. # Create separate print function to make modification changes easier # Have program write to a user named file with just the length of the dictiona...
#DSC 510 #Week 9 #Programming Assignment Week 9 #Author Tiffany Tesoro #08/02/2020 #TO USE API TO GET DATA import json import requests #^^ had some trouble using this until i figured out how to install pip via terminal on my mac #DEFINE JOKE_REQUEST FUNCTION def joke_request(): while True: hearajoke =...
# credit to my homework from Coursera: # Neural Networks and DeepLearning, # Hyperparameter tuning, Regulation and Optimization import pandas as pd import numpy as np import math import matplotlib.pyplot as plt def sigmoid(x): """ Compute the sigmoid of x """ s = 1 / (1 + np.exp(-x)) ...
import pandas as pd import numpy as np import streamlit as st #import the dataset and create a checkbox to shows the data on your website df1 = pd.read_csv("df_surf.csv") if st.checkbox('Show Dataframe'): st.write(df1) #Read in data again, but by using streamlit's caching aspect. Our whole app re-runs every ...
seq = "" with open("sequence.protein.2.fasta",'r') as fr: for line in fr: if line.startswith(">"): continue else: seq += line.strip() while True: position = input("Position: ") if position == "XXX": print("Okay, I will stop.") break else: seq_len = len(seq) try: position = int(position) ex...
message1 = input("Enter a string: ") message2 = input("Enter another: ") if message1 != message2: print(message1+message2) else: print("Two strings are identical.")
H = raw_input('enter hour: ') M = raw_input('enter rate: ') if H >= 100: print 'pay:',int(H)*int(M)*2 else: print 'pay:',int(H)*int(M)
print 'Score Grade \n>=0.9 A \n>=0.8 B \n>=0.7 C \n>=0.6 D \n <0.6 F \n' score = raw_input('Enter score: ') try: ss = float(score) if 0.0 <= ss <= 1.0: if ss >= 0.9: print 'A' elif ss >= 0.8: print 'B' elif ss >= 0.7: print 'C' elif ss >= 0.6: print 'D' elif ss < 0.6: print 'F' else:...
def reverse_message(string): return (string[::-1]) message = input("Enter a string: ") reverse = reverse_message(message) print ("Reversed string: "+reverse)
tabela = ('Atlético - MG', 'São Paulo', 'Flamengo', 'Internacional', 'Palmeiras', 'Santos','Grêmio', 'Fluminense', 'Fortaleza', 'Ceará', 'Corinthians', 'Athletico - PR', 'Bahia','Atlético - GO ', 'Bragantino', 'Sport', 'Vasco', 'Coritiba','Botafogo', 'Goiás ') print("-="* 50) print(f"A lis...
pessoa = dict() galera = list() soma = media = 0 while True: pessoa["nome"] = str(input("Nome: ")) while True: pessoa["sexo"] = str(input("sexo:[M/F] ")).upper()[0] if pessoa["sexo"] in "MF": break print("Erro! Por favor digite M ou F") pessoa["idade"] = int(input("Idade:...