text
stringlengths
37
1.41M
def bubble_sort(arr): for i in range(len(arr)): for j in range(len(arr)-1-i): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr print(bubble_sort([100, 4, 1, 3, 200, 5,3,4,1,2])) def selection_sort(arr): for i in range(len(arr)-1, 0, -1): maxI...
#!/usr/bin/env python3 """ Fix names in auth_users. Usage: ./fix_names data/site/epcon.db Uses nameparser package to do the hard work of splitting names into first and last name. Written by Marc-Andre Lemburg, 2019. """ import sqlite3 import sys import nameparser ### def connect(file): db ...
#!/usr/bin/env python """ Use BeautifulSoup to follow links to scrape data from understat.com To setup - `pip install bs4` """ import argparse import json import os from datetime import datetime, timedelta import pytz import requests from bs4 import BeautifulSoup from tqdm import tqdm LEAGUE_URL = "https://underst...
#!/usr/bin/env python # coding: utf-8 # # Exercici 3 # # Crea una funció que donada una taula de dues dimensions, et calculi els totals per fila i els totals per columna. # In[2]: import numpy as np num = np.array([[12,3,1,4],[55,2,6,9]]) suma_fila = np.sum(num, axis = 0) suma_columna = np.sum(num, axis = 1) pr...
# -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python interpreter will load...
# -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python interpreter will load...
# -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python interpreter will load...
# Created by Victor Honorato Pinheiro 05/09/2021 ''' A game in python than generate random maze everytime. FULL PERMISSION FOR PERSONAL OR COMERCIAL USE The maze generator use the Randomized Prim's algorithm Check (https://en.wikipedia.org/wiki/Maze_generation_algorithm#Randomized_Prim's_algorithm) ''' import pygame i...
class Node(object): def __init__(self, value, next_node = None): self.value = value self.next_node = next_node def detect_cycle_with_dict(head): nodes_seen = {} current_node = head while current_node != None: if current_node in nodes_seen: return True no...
def reverse_sentence(sentence): words = [] current_word = "" i = 0 while i < len(sentence): if sentence[i] == " ": words.append(current_word) current_word = " " else: current_word += sentence[i] i += 1 words.append(current_word) i ...
def reverse_string(string): if len(string) == 1: return string return reverse_string(string[1:]) + string[0] print(reverse_string("abc"))
# Problem Set 4C import string from MIT60001_ps4a import get_permutations ### HELPER CODE ### def load_words(file_name): ''' file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters. Dependin...
# Problem Set 2, hangman.py # Hangman Game # ----------------------------------- # Helper code import random import string WORDLIST_FILENAME = "MIT60001_ps2.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this...
"""API MediaWiki file""" import requests class Wiki: """Uses Wikipedia's API to fetch extract and link of the page""" def __init__(self, question): self.question = question self.url = 'https://fr.wikipedia.org/w/api.php' self.params = {'action': 'query', 'generat...
is_underage = int(input('What is your age:')) if is_underage >= 21: print('you may drink, smoke, and drive if you wish!') elif is_underage >= 18: print('You may smoke and drive!') elif is_underage >= 16: print('you may drive!') else : print('Enjoy your bike and the buss kid!')
from functools import reduce def multiply(x: int,y: int) -> int: return x*y def find_numbers(begin: int, end: int) -> list: """ :param begin: range start, int :param end: range end, int :return: list of numbers where number %7==0 and number %5 != 0 >>> find_numbers(5, 15) [7, 14] """ ...
# this will print the date and time # import datetime # print (datetime.datetime.now()) # this will print a string with the date & time on 2 different lines # import datetime # print("The date and time is") # print (datetime.datetime.now()) # this will print everything on one line # import datetime # print("The dat...
#################### ### BRIAN TIPOLD ### ### UBER PATHING ### #################### ## First time learning python ;) ### INIT ### import sys import csv import random #CONSTANTS INFINITY = sys.maxsize #VARIABLES graph = [] # graph requests = [] # list of requests netw...
""" # Copyright Nick Cheng, 2018 # Distributed under the terms of the GNU General Public License. # # This file is part of Assignment 1, CSCA48, Winter 2018 # # This is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundat...
""" Helped function to plot data using matplotlib """ import matplotlib.pyplot as plt def plot_top_n(data_counts, title, xlabel, top=10): """ Produces a matplotlib plot with the given title and xlabel displaying the top results in data_counts Params: data_counts: a Counter object titl...
import random import sys class Cell: def __init__(self, index, value): self.index = index self.value = value class Board: field = [] region_1 = [] region_2 = [] region_3 = [] region_4 = [] def __init__(self): self.create_board() def create_board(self): ...
from mergesortwhichisnotmyne import mergeSort def merge_sort(arr): #spliting if len(arr) > 1: mid = len(arr)//2 right = arr[mid:] left = arr[:mid] print("spliting completed") # recursive call merge_sort(right) merge_sort(left) #iterato...
from turtle import Turtle class Scoreboard(Turtle): def __init__(self): super().__init__() self.hideturtle() self.penup() self.color('white') self.setposition(0, 270) self.score_left = 0 self.score_right = 0 self._write_score() def add_score_to...
student_grades = [57, 74, 49, 0, 87, 66, 89] for g in student_grades: assert student_grades[g] != 0 if student_grades[g] >= 52: print('This student passed.') else: print('This student failed.') print('Program complete')
def multExcept(ln): rn = [] tot = 1 for x in ln: tot = tot * x for i in enumerate(ln): rn.append(tot/ln[i[0]]) return rn def multExceptNoDiv(ln): rn = [] for i in enumerate(ln): tot = 1 for j in enumerate(ln): if i[0] == j[0]: tot = tot*1 ...
def addToK(ln,k): # find if any 2 numbers in ln sum to k ld = [0] # list of differences found = False for x in ln: if x in ld: found = True ld.append(k-x) return found if __name__ == '__main__': print(addToK([10,15,3,7], 17))
import integrator import math # Pure Python implementation def python_midpoint(): difference = 1 n = 90600 f = lambda x: math.sin(x) while (difference > 1E-10): n += 1 sum_of_integral = integrator.integrate(f, 0, math.pi, n, method="midpoint", implementation="default") difference = abs(2 - sum_of_integral) ...
class Solution: def is_palindrome(self, x: int) -> bool: num = str(x) length = len(num) count = -1 for i in range(int(length / 2)): if num[i] != num[count]: return False count -= 1 return True
n = int(input('Enter the range of the fibonacci series to be printed : ')) def fib(n): # create list to hold the numbers of the series numbers = [0] * (n + 1) numbers[1] = 1 for i in range(2, n + 1): numbers[i] = numbers[i - 1] + numbers[i - 2] return numbers print fib(n) ...
class Student: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender s1 = Student('Parthibhan', 21, 'M') print s1 print s1.age
# decimel(.) precision of three for 0.3333 print '{0:.3f}'.format(1.0/3) # decimel(.) precision of 7 print '{0:.7f}'.format(1.0/3) # decimel precision 5 print '{0:.5f}'.format(55.0/33) # fill with underscores if width is less print '{0:_^5}'.format('Hello') print '{0:_^6}'.format('Hello') print '{0:_^11}'.format('Hel...
def total(initial=5, *numbers, **keywords): count = initial for number in numbers: count += number for key in keywords: count += keywords[key] return count print total(10,1,2,5,99, vegetables=50, fruits=100, juices = 3)
# This is example of format method in python name = 'PARTHIBHAN' age = 20 print ' {0} is learning python at the age of {1} '.format(name,age) print ' playing with python at {0} '.format(age) # {0} represnts the the first argument passed to foramt method # The numbers are optional print ' My age is {} '.format(age)
b=1 a=int(input("введите число: ")) while (a!=1): b=b*a a=a-1 print("факториал числа:",b)
def add_nums(): number1 = 1 number2 = 2 answer = number1+number2 print( "{} plus {} is {}".format(number1,number2,answer)) add_two_numbers() def greetings_from_collaborator(name): print("Hi, I am your collaborator, {} :)".format(name)) greetings_from_collaborator("Gloria")
""" This module holds accessory functions that helps to accomplish the other tasks, such as calculates a piece column/line based on index and the number of columns or lines. """ def get_col_by_index(index, cols): """ It calculates the chess board column based on array index representations """...
OPERATORS = {'+': (1, lambda x, y: x + y), '-': (1, lambda x, y: x - y), '*': (2, lambda x, y: x * y), '/': (2, lambda x, y: x / y)} def calc(formula: str) -> int: def simplification(formula_string: str) -> str: formula_string = formula_string.replace(' ', '') formula_string = formul...
def maximum_prime(n): m = 2 z = n #используем z, чтобы в дальнейшем сохранить выполнение цикла while True: if m > z: break else: if n%m == 0: #Здесь делим на все числа подряд if n == m: #Т.к. простые числа будут удалять ...
# Example 1: # # Input: "III" # Output: 3 # Example 2: # # Input: "IV" # Output: 4 # Example 3: # # Input: "IX" # Output: 9 # Example 4: # # Input: "LVIII" # Output: 58 # Explanation: L = 50, V= 5, III = 3. # Example 5: # # Input: "MCMXCIV" # Output: 1994 # Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. class So...
# Example 1: # # Input: s = "anagram", t = "nagaram" # Output: true # Example 2: # # Input: s = "rat", t = "car" # Output: false class Solution: def isAnagram(self, s: str, t: str) -> bool: s_dict = {} t_dict = {} for char in s: if char in s_dict.keys(): s_dict[...
""" Autor: Carbajal Ramos Juan Jesús Fecha: 04/07/19 """ #Realice un programa en Python que dado como datos los sueldos de 10 trabajadores de una empresa, #obtenga el total de nómina de la misma. Puede utilizar un ciclo for o un ciclo while. def main(): st = 0.0 for i in range(0, 10): print('Sueldo',...
""" Autor: Carbajal Ramos Juan Jesús Fecha: 05/07/19 """ import math class Punto(object): def __init__(self, x, y): self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y def setX(self, x): self.x = x def setY(self, y): ...
#!/usr/bin/env python3 """ This would make a good library file for Chequeings and Savings bank accounts. """ class Account: """ Abstract base class for other types of accounts like Current (i.e. Chequeing) and Savings. """ def __init__(self, name, balance, min_balance): self.name = name ...
class Dog : species = 'firstdog' def __init__(self,name,age): self.name= name self.age = age print(Dog) a = Dog('mikky','5') print(a.name)
# # # # # str1 = "12345" # # list1 = list(str1) # # print (list1) # # b=",".join(list1) # # print(b) # # print(type(b)) # # c=b.split(",") # # print(c) # a=["1","3","5",6] # b=",".join(map(str,a)) # c=b.replace(",","") # print(type(b)) # d=list(c) # print(d) # print(d.index("1")) # d.remove("6") # print(d) # d.insert(3...
from pprint import pprint def main(): print("Note: when computing matrix, elements of seq x will be drawn vertically and that of seq y will go horizontally:") s1 = list(str(input("Enter seq for x:"))) s2 = list(str(input("Enter seq for y:"))) x = [int(ord(i)) for i in s1] y = [int(ord(i)) for i ...
import itertools import time # read in our number set with open('Data.txt', 'r') as f: data = f.read().split() """ # @desc: trivial implementation to find the best way to partition the set into two sets of as close to equal sum as possible # @param: elements: list of numbers (n < 30) # @return: two p...
from sys import stdin N = int(stdin.readline()) inputsum = sum([int(stdin.readline()) for _ in range(N)]) if N / 2 > N - inputsum: print("Junhee is cute!") else: print("Junhee is not cute!")
#!/usr/bin/env python3 # Created by: Seti Ngabo # Created on: Sept 2021 # this program calculates the area and perimeter of a rectangle # with dimensions 5cm x 3cm def main(): # this function calculates the area and perimeter print("If a rectangle has the dimensions:") print("5cm x 3cm") print("")...
def valid_file(given_file): """ :param given_file: name of the supplied file :return: if the file is of valid format Note: Lazy Check """ if ".csv" not in given_file: print("Not a .csv type file? ") return False else: return True filename = input("Filename: ") new_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 14 17:07:40 2021 @author: n7 """ import os from . import text as tx from . import utils as ut def tabular(df, col_style=None, index=False): r""" Generate LaTeX tabular environment code for a DataFrame. Parameters ---------- d...
def main(): #write your code below this line string = str(input("Enter a string: ")) integer = int(input("Enter an integer: ")) Float = float(input("Enter a float: ")) Boolean = input("Enter a boolean: ") print("You give the string " + string) print("You gave the integer " + str(integer)) ...
import pandas as pd import sqlite3 import numpy as np from sklearn import preprocessing from math import radians, cos, sin, asin, sqrt import seaborn as sns from statistics import mode import matplotlib.pyplot as plt db = sqlite3.connect('ui/education.db') c = db.cursor() def haversine(lon1, lat1, lon2, lat2): '...
def checkio(number): # define string container wordedNumber = [] # define a few special cases numberLookup = { '1': 'one' , '2':'two' , '3':'three' , '4':'four' , '5':'five' , '6':'six' , '7':'seven' , '8':'eight' , '9':'nine' , '10':'ten' ...
import re """ This program supports two ways of validating ssn; from a txt-file or from direct input in program. 1) If you wish to validate multiple ssn: Go to main() -> set ssn_txt = True -> set filename 2) If you wish to validate on specific ssn: Go to main() -> set_txt = False -> specify the ss...
#Import packages import csv import json from pprint import pprint #Read vegetables.csv into a variable called vegetables. with open('vegetables.csv', 'r') as f: reader = csv.DictReader(f) vegetables = [dict(row) for row in reader] # Convert Ordered Dict to regular dict (python 3.6 or higher) #group veggies by...
from datetime import datetime raw_date = "1-May-12" #-d doesn't work on my computer with strptime (it's #fine with strftime), but some googling/trying it and #seeing what happens tells me that strptime works fine #with %d even for non-zero-padded date_format = "%d-%B-%y" parsed_date = datetime.strptime(raw_date, date...
numbers = [2, 3, 5, 8, 9] for num in numbers: if num % 2 == 0: print("The number " + str(num) + " is even") else: print("The number " + str(num) + " is odd")
#for find the list input in a function with loop: # data=[ # [1,2,3,4,5], # [6,7,8,9,10], # [11,12,13,14,15], # [16,17,18,19,20] # # ] # for i in data: # for j in i : # if j==13 or j==18: # print(j) # break #n=len(data) #print(n) # x=[ # ["Ram","Shyam","Hari"], #...
# # if # a = 5 # b = 10 # c = 30 # # if a == b: # print("yes") # else: # print("No") # a = 5 # b = 4 # c = 30 # if a > b and a > c: # print("A") # elif b > a and b > c: # print("B") # else: # print("c") # if a > b:-Nested statement # if a > c: # print("A") # else: # print(...
names = ["deter", "Bernd", "Martin"] print(names) # liste absteigend sortieren names.sort(reverse=True) print(names) # Zahlen aufsteigend sortieren numbers = [1, 7, 3, 7] numbers.sort() print(numbers) numbers = [0.9, 0.1, 0.5] numbers.sort(reverse=True) print(numbers)
print(list(range(2,5))) L = [] for x in range(1,11): L.append(x*x) print(L) l2 = [x*x for x in range(1,11)] print(l2) print([x*x for x in range(1,11) if x %2 ==0]) # 双层循环 print([m+n for m in 'ABC' for n in 'abc']) l = {1:'a',2:'b',3:'c',4:'5'} print([(k,v) for k,v in l.items()]) # 练习 l3 = ['Hello', 'World', ...
print(hex(255)) # 位置参数 def power1(x,n): s = 1 while n > 0: s = x * s n = n - 1 print(s) power1(2,5) # 默认参数 def power2(x,n=2): s=1 while n > 0: s = x * s n = n - 1 print(s) power2(2) def student(name,age,city='北京',height='120'): print('name:',name,'age:',...
#!/usr/bin/python from random import randint # Dice Simulation 1 n = int(raw_input("How many iterations should I perform?\n")) counter = 0 for i in range(n): dice1 = randint(1,6) dice2 = randint(1,6) if dice1 == 6 or dice2 == 6: counter += 1 print "Estimated probability of getting a 6 if two dic...
# 5. Nonlinear Fit import numpy as np f = lambda x, a, b : np.exp(-a*x) + b # define a lambda function with three arguments x = np.arange(0, 4, 0.01) y = f(x, 2.5, 1.4) # generate y values from the lambda function y = y + 0.25*np.random.randn(len(y)) # add Gaussian noise to the values import pylab as pl pl.plot(x, y...
class Animal: """An abstract animal""" def __init__(self, weight, age): # store your own copy of weight and age such that we can # refer to them later self.__weight=weight self.__age = age # look at move() function self._weightLossPerDistance = 1.0 def age...
# make a binary file from a text file # v short import argparse as ap parser = ap.ArgumentParser(description = 'Save a binary copy of a txt file.') parser.add_argument('file', metavar = 'FILE', type = ap.FileType('r'), help = 'Path to the text file to copy and save.') parser.add_argument('-o', metavar = 'OUTFILE_NAM...
''' This code is designed to build a classic hangman game Starts on page 132 of the 'Self-Taught Programmer ''' def hangman(): import random word_list = ['arbitrary','benign','chemical','derail','echo','fetter','gargoyle','hairstyle','indigo','jalapeno','kangaroo'] word = random.choice(word_list) wrong...
# Chapter 4 challenges # 1. Write a function that takes a number as an input and returns that number squared. def squared(x): ''' function squares your input :param x: int. : return: squared x. ''' return x**2 print('Below result should be 4') print(squared(2)) # 2. Create a function that ac...
while True: print("Main circle") if input("input:") == "1": flag = 1 while flag == 1: print("Second circle") if input("Input:") == "1": continue else: print("End of Second circle") flag = 0 print("Conti...
bill = float(raw_input("Total bill amount? ")) # may be better to start off with bill_input to indicate this is input #next line, you would then create bill to convert to float() level_of_service = raw_input("Level of service? ") if level_of_service.lower() == "good": tip = bill * 0.20 elif level_of_service.lower(...
width = int(raw_input("Width? ")) height = int(raw_input("Height? ")) counter = 0 while counter <= height: if counter == 0 or counter == height: print "*" * width counter += 1 else: print "*" + (" " * (width - 2)) + "*" counter += 1
bill = float(raw_input("Total bill amount? ")) level_of_service = raw_input("Level of service? ") split = float(raw_input("Split how many ways? ")) if level_of_service.lower() == "good": tip = bill * 0.20 elif level_of_service.lower() == "fair": tip = bill * 0.15 elif level_of_service.lower() == "bad": tip...
today_seats = [ 'Xavier', 'Clinton', 'Andrew', 'Jimmy' ] yesterday_seats = [ 'Xavier', 'Andrew', 'Clinton' 'Jimmy' ] #repeat a check: #is the person in this seat different from yesterday? current_row = 0 while current_row < len(today_seats): if today_seats[current_row] == yeste...
# coding: utf8 from __future__ import unicode_literals import os import random import sys import time import pickle import math import io # EzLearner 0.2 #TODO: # 1) Main menu - Modes: Version / Thème # 2) gestion des parenthèses / des slashs ''' n = number of words Every word start with weight 16. Iitial capacity...
# combat functions import utilities import random import time health_points = 0 rounds = 0 accuracy = 0.00 enemy = { "name": "Octavio", "hp": 100, "rounds": 1, "accuracy": 1.00 } def combat(rounds1, health_points1, player_steps): global rounds rounds = 6 global health_points health_...
from flask import Flask, request import json import re app = Flask(__name__) @app.route("/words/avg_len", methods=['POST']) def average_word_length(): words = extract_words_from_input_text(request.get_json()) # get the total length of all the words within the text sum_of_lengths = sum([len(word) for word ...
def convert(number): remainders = [] current_number = number to_binary = [] while True: quotient = current_number / 2 remainder = current_number % 2 current_number = quotient remainders.append(remainder) if quotient == 1 or quotient == 0: break if quotient != 0: to_binary.app...
# Given: Existing array should maintain the property of the max heap def max_heapify(array, index, length): # # maintain the property of max heap # Step 1: Consider the element at `index` is largest largest = index # Step 2: Compute left child left = 2*index + 1 # Step 3: Compute right child ...
#-*- coding: UTF-8 -*- import random fahr, wind = eval(input("enter three of sides for triangle(ex. Farhrenhiat, wind speed):")) if -58<= fahr <= 41 and wind >=2: effectiveFahr = 35.74 + 0.6215*fahr - 35.75*(wind**0.16) + 0.4275*fahr*wind**0.16 print("Effective Temperature: ", format(effectiveFahr,".5f")) else: #...
#-*- coding: UTF-8 -*- import random year, month = eval(input("Enter the year and month...(ex, 2000, 2): ")) if month == 1: print("Last Date: ", year,"-",month,"-31") elif month == 2: if year % 4 ==0 and year % 100 !=0 or year % 400==0: print("Last Date: ", year,"-",month,"-29") else: print("Last Date: ", ye...
#-*- coding: UTF-8 -*- import sys status = eval(input("0 - single filer\n" + \ "1 - married filing joinly\n" + \ "2 - married filing seperatly\n" + \ "4 - head of househod\n" + " which filer do you select? ")) income = eval(input("enter your taxable inocme ? ")) tax = 0 if status == 0: if in...
#-*- coding: UTF-8 -*- stuNo = eval(input("enter the number of students: ")) max1 = 0 max2 = 0 for i in range(0, stuNo): score = eval(input("enter the score of a student: ")) if max1 < score: temp = max1 max1 = score if max2 < temp: max2 = temp print(max1, max2) print(i) print("max1: ", max1, "max...
#-*- coding: UTF-8 -*- import math radius = 3 print("area is", radius*radius*math.pi, end='and ') print("circle length is ", 2*radius*math.pi,".")
#-*- coding: UTF-8 -*- import random number1 = random.randint(0,100) number2 = random.randint(0,100) hab1 = number1 + number2 hab2 = eval(input("enter two integer number for an answer: ")) if hab1 == hab2: print("Successful. number1: ",number1, "number2: ", number2, "hab: ", hab1) else: print("Try...again num1,...
#-*- coding: UTF-8 -*- import random number = random.randint(0,100) print("Why don't you enter a magic number between 0 and 100:") guess = -1 while guess != number: guess = eval(input("Enter a magic number:")) if guess == number: print("successful", number) elif guess > number: print("less than the guess")...
#-*- coding: UTF-8 -*- import random a,b,c,d,e,f = eval(input("enter coefficients for the 2x2 equation(ex:a,b,c,d,e,f):")) if (a*d-b*c) == 0: print("no soultion") else: x = (e*d - b*f)/(a*d - b*c) y = (a*f - e*c)/(a*d - b*c) print("x = ", x, "y = ", y)
#-*- coding: UTF-8 -*- # enter integer variable from a user seconds = eval(input("input the nubmer [seconds]: ")) # get the values of the minutes and seconds minutes = seconds // 60 remainingSeconds = seconds % 60 # show the result print("About input sconds, ", seconds,"[sec], ==> minutes,", minutes, \ "[minutes],...
#-*- coding: UTF-8 -*- import math print("degree sin cos") for deg in range(0, 360, 10): rad = math.degrees(deg) print(format(deg, "<4d"), \ format(math.sin(rad),"10.4f"), \ format(math.cos(rad),"10.4f"))
#-*- coding: UTF-8 -*- ''' def sum(s, t): result = 0 for i in range(s, t+1): result += i return result def main(): print("sum from 1 to 10:", sum(1,10)) print("sum from 20 to 37:", sum(20,37)) main() ''' def max(a, b): if a > b: result = a else: result = b return result def main(): i ...
#-*- coding: UTF-8 -*- import random number1 = random.randint(0,9) number2 = random.randint(0,9) number3 = random.randint(0,9) answer = eval(input(str(number1) + "+" + str(number2) + "+" + str(number3) + "= ")) print(number1, "+", number2, "+", number3, "=", answer)
#Imports import random from bs4 import BeautifulSoup import requests import datetime import calendar ## Instructions ## """ This is a chatbot that will intiate a conversation with the user. The bot will ask the user various questions, which can be seen in the questions array. """ ## End of Instructions ## #...
prev = int(input()) print("Start = " + str(prev)) i = 1 while(1): value = input() i += 1 if (value == "END"): print("SUCCESS, End = " + str(current)) exit() else: current = int(value) if (current != prev + 1): print("WRONG! LINE=" + str(i) + " Got " + str(current) + ", expected " + str(prev + 1) + ".") ...
#Exercício 04. ​ Crie uma função que recebe como parâmetro um número real ​ n #e retorna True caso o número seja par. #Criando a função e verificando se o numero e par def numero_real_par(numero): if numero % 2 == 0: return True else: return False #obs: para usar esta função no interpretador ...
'''Exercício 09. ​ Crie um menu onde o usuário pode escolher quais das funções do exercício 08 será chamada. O programa deve imprimir o resultado e solicitar que o usuário escolha uma outra função. O menu deve possuir uma opção de saída do programa. Ex. menu = """ ======= MENU ======= 1) SOMA(A, B) 2) SUBTRACAO(A, B) 3...
from sklearn import datasets import numpy as np # Read Data iris = datasets.load_iris() X = iris.data[:, [2, 3]] y = iris.target # Split dataset into SEPARATE Training and Test Datasets from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, ran...
import string def cesar(key, phrase): ''' функція декодуваня слів ''' str_arr = string.ascii_lowercase str_arr2 = string.ascii_lowercase[key:] + string.ascii_lowercase[:key] str_arr += string.ascii_uppercase str_arr2 += string.ascii_uppercase[key:] + string.ascii_uppercase[:key] cliper_dict= {...
name = (input('Введіть Ваше Прізвище Імя Побатькові: ')) print(name) nameI = name.title() nameI = nameI.split() print(nameI) for i in range(len(nameI)): n = nameI[i] print(n[0], end="")
""" @author: Shubham Shantaram Pawar """ import pandas as pd import numpy as np import matplotlib .pyplot as plt def computeCost(X, y, theta): m = len(y) h = np.matmul(X, theta) J = (1/(2 * m)) * np.sum(np.square(np.subtract(h,y))) return J def gradientDescent(X, y, theta, alpha, nu...
numeros = (int(input('digite um numero: ')), int(input('digite outro numero: ')), int(input('digite mais um numero: ')), int(input('digite o ultimo numero: '))) print(f'os numeros digitados foram {numeros}') print(f'o numero 9 apareceu {numeros.count(9)} vez(es)') if 3 in numeros: p...