text
stringlengths
37
1.41M
# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 def fib_iterative(n): if n == 1: print(0) return if n == 2: print(1) return a = 0 b = 1 print(a, b, end=" ") for i in range(n - 2): summ = a + b a = b b = summ print(summ, end...
array = [88, 2, 65, 34, 2, 1, 7, 8] array_2 = [88, 2, 65, 34, 2, 1, 7, 8] def bubble(arr): arr_len = len(arr) for i in range(arr_len): for j in range(i + 1, arr_len): if arr[j] < arr[i]: arr[j], arr[i] = arr[i], arr[j] def bubble_v2(arr): arr_len = len(arr) for i ...
def factorial_recursive(number): if number == 2: return 2 return number * factorial_recursive(number - 1) def factorial_iterative(number): summ = 1 while number > 1: summ *= number number -= 1 print(summ) factorial_iterative(10) print(factorial_recursive(5))
from cs50 import get_int x = get_int("Enter Int: ") y = get_int("Enter Int: ") print(f"{x} + {y} = {x + y}") print(f"{x} - {y} = {x - y}") print(f"{x} * {y} = {x * y}") print(f"Floor divided = {x // y}") print(f"Truly divided = {x / y}") print(f"remainder of {x} by {y} = {x % y}")
####################################################### # 1.21 # 思路:把输入的值存入列表中 ####################################################### def read_line(): lines = [] while True: try: lines.insert(0, input("input:").strip()) except EOFError: for i in lines: ...
import re def polynomial_derivative(p: str): """Return the first derivative of the polynomial. p a polynomial in standard algebraic notation """ # use `re` module, matching method as the follow: # sign [-+]? # factor \d*\.*\d* # variable x?\^? # power \d* ...
####################################################### # 1.28 # 思路: ####################################################### def norm(v, p=2): return pow(sum(pow(i, p) for i in v), 1/p) def test(): test_list = [4, 3] print(f'p=2,v={tuple(test_list)}, ||v||={norm(test_list)}') print(f'p=3,v={tuple(te...
# cass inheritance diagram: # # object # / \ # Book User # class Book(object): """Create a new e-book.""" def __init__(self, name, price, publisher): """Return a new book instance.""" self.name = name self.price = price self.publisher = publisher ...
####################################################### # 1.26 # 思路:使用内置函数eval执行字符串命令 ####################################################### def formula(a: int, b: int, c: int): for operator in '+-*/': expresses = [ f'{a} {operator} {b} == {c}', f'{a} == {b} {operator} {c}' ...
def multiply_uniques(a,b,c): """ set in python always store unique value a:3 b:2 c:3 Reult:6 becasue 3 is repated """ if a==b==c: return 0 result = 1 a={a,b,c} for i in a: result *= i return result print(multiply_uniques(3,2,3)) print(multipl...
''' otimização por colonia de formiga aplicado ao problema de caixeiro viajante ''' import random, math # Classe que representa uma formiga class formiga: def __init__(self, cidade): self.cidade = cidade self.solucao = [] self.custo = None #super().__init__() @property ...
a = int(input()) b = int(input()) if a > b: print(a, " is largest") else: print(b, "is largest")
# Content from: https://www.w3schools.com/python/python_strings.asp #Array concept a = "Hello, World!" print(a[0]) print(a[1]) #Slicing concepts, positive index starts from 0th position b = "Hello, World!" print(b[2:5]) print(b[2:6]) #Slicing concepts, negative index starts from -1 position b = "Hello, World!" print...
import math a=2 b=5 print(a*b) print(a**b) print(b**a) print(abs(-4/3)) print(pow(2,3)) print(math.sqrt(25)) if math.sqrt(25) > math.sqrt(16) + math.sqrt(9): print("True") else: print("False") print(round(3.7)) print(round(4.2)) #others ceil floor etc.
def fahrenheit_to_celsius(fahrenheit): return float(fahrenheit-32)*5/9 n = float(input()) fahrenheitTemperature = fahrenheit_to_celsius(n) print("%.2f" %fahrenheitTemperature)
numOne = int(input()) numTwo = int(input()) for i in range(numOne,numTwo+1): print("{0} ".format(chr(i)),end= '')
number = int(input()) if number >=100 and number<=200: print() elif number !=0: print("invalid")
n = int(input()) for firstLetter in range(ord('a'), ord('a') + n): for secondLetter in range(ord('a'), ord('a') + n): for thirdLetter in range(ord('a'), ord('a') + n): print("{0}{1}{2}".format(chr(firstLetter),chr(secondLetter),chr(thirdLetter)))
import math n = int(input()) for i in range(2,n+1): mathSqrt = int(math.sqrt(i)) isPrime = True for j in range(2,mathSqrt+1): if i % j == 0: isPrime = False print("{0} -> {1}".format(i,isPrime))
n=int(input()) stars = 1 if n% 2 ==0: stars += 1 # roof for i in range(0,int((n+1)/2)): padding = int((n-stars)/2) print("-"*padding,end='') print("*" * stars, end='') print("-" * padding) stars +=2 # body for y in range(0,int(n/2)): print("|"+"*"*(n-2)+"|")
n = int(input()) integers = [] for i in range (0,n): integers.append(int(input())) # integers.reverse() or print(integers[::-1])
amount = float(input()) currencyFrom = input() currencyTo = input() def switch(amount,currencyFrom,currencyTo): result = 0.0 toLeva = 0.0 if currencyFrom == "BGN": toLeva = amount if currencyFrom == "USD": toLeva = amount * 1.79549 if currencyFrom == "EUR": toLeva = amount...
n = int(input()) # top mid = int(n / 2) midSize = 2 * n - 2 * mid - 4 # bottom if n <= 4: print("/{0}\\/{0}\\".format('^'*int(mid))) else: print("/{0}\\{1}/{0}\\".format('^'*int(mid),'_'*int(midSize))) if n <= 4: for i in range(0,n-2): print("|{0}|".format(' '*int(n*2-2))) print("\{0}/\{0}/"...
numOne = int(input()) numTwo = int(input()) print(numOne)if numOne>numTwo else print(numTwo)
word = input() sumOfChars = 0 for i in word: if i == 'a': sumOfChars+=1 elif i == 'e': sumOfChars+=2 elif i == 'i': sumOfChars+=3 elif i == 'o': sumOfChars+=4 elif i == 'u': sumOfChars+=5 print(sumOfChars)
speed = float(input()) if speed <= 10: print("slow") elif speed >10 and speed<=50: print("average") elif speed >50 and speed<=150: print("fast") elif speed >150 and speed<=1000: print("ultra fast") else: print("extremely fast")
n = int(input()) factorial = 1 for i in range (1,n+1): factorial *= i print(factorial)
n = int(input()) for row in range(0,n+1): stars = "*"*row space = " "*(n-row) print(space ,end='') print(stars, end='') print(" | ",end='') print(stars, end='') print(space, end='') print()
def iscircular(linked_list): """ Determine whether the Linked List is circular or not """ slow_runner = linked_list.head fast_runner = linked_list.head while fast_runner and fast_runner.next: slow_runner = slow_runner.next fast_runner = fast_runner.next.next ...
#!/usr/bin/env python3 # ================= 代码实现开始 ================= N = 100005 class node: def __init__(self): self.val = self.left = self.right = 0 t = [node() for i in range(N)] root, cnt = 0, 0 def insert(v, x): if x == 0: global cnt x = node() x.val = v return...
#!/usr/bin/env python3 # ================= 代码实现开始 ================= Mod = 1000003 table = [[] for i in range(Mod)] def Hash(x): return x % Mod # 执行操作时会调用这个函数 # op:对应该次操作的 op(具体请见题目描述) # x:对应该次操作的 x(具体请见题目描述) # 返回值:如果输出为"Succeeded",则这个函数返回 1,否则返回 0 def check(op, x): h = Hash(x) ptr = -1 for it in ...
## TODO: define the convolutional neural network architecture import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(sel...
""" Easy JSON Web Token implementation for Flask """ import re import jwt from datetime import datetime, timedelta from flask import current_app, request from .security import Security class JWT: """ Gets request information to validate JWT """ token = None app_key = None app_secret ...
#!usr/bin/python3 # Simple tkinter Calculator from tkinter import * from tkinter import font as tkFont # Clear function def clearScreen(): display.set("") # Display function def dataDisplay(key): if display.get() == "ERROR": clearScreen() word = display.get() + key display.set(word) # Ans...
# AoC 2019 - Day 1 - Part 2 f = open('input.txt', 'r') sum = 0 def fuel_adder(amount): partial = int(amount/3)-2 if partial < 1: return 0 return partial + fuel_adder(partial) for l in f: sum += fuel_adder(int(l)) print(sum)
#Amir Afzali #Counting Sundays Project Euler Question 19 import datetime #The best way to approach the problem would be to take advantage of the datetime library as it should have all the info I need so import it def countingsundays(): #Setting up the ranges for month and years sundays = sum(1 for year in ...
import math a=int(input("enter the element:")) print(a) print(math.factorial(a))
""" This module is used in identifying the cuisine a particular dish belongs to. It does so by converting a dish's ingredients to a vectorized format using the TF-IDF method, and then uses KNN with a choice of similarity measure to get the cuisine. """ import sys import copy import json import math import ran...
import cv2 import numpy as np def resize(image: np.ndarray, width: int = None, height: int = None, inter: int = cv2.INTER_AREA) -> np.ndarray: """ Resize image proportionally :param image: image to resize :param width: new width :param height: new height :param inter: interpolation method ...
# importing another py file import openpyxl from selenium import webdriver from bs4 import BeautifulSoup import requests from email.mime.image import MIMEImage import smtplib from email.mime.text import MIMEText # mime = multipurpose internet mail extension from email.mime.multipart import MIMEMultipart import webbrows...
def binary_search(array, target): start = 0 end = n - 1 while start <= end: mid = (start + end) // 2 if array[mid] == target: return 1 elif array[mid] < target: start = mid + 1 else: end = mid - 1 return 0 t = int(input()) for tc in r...
str = input() print(1) if str == str[::-1] else print(0)
str = input() tmp = "" answer = "" is_tag = False for i in str: if i == '<': is_tag = True answer += tmp[::-1] + "<" tmp = '' elif i == '>': is_tag = False answer += ">" elif i == ' ': if is_tag: answer += ' ' else: answer += tmp...
T=int(input()) for i in range(T): str = list(input()) if str == str[::-1]: result = 1 else: result= 0 print(f"#{i+1} {result}")
class Node: def __init__(self,item,left=None, right=None): self.item=item self.left=left self.right=right class binarytree: def __init__(self): self.root=None def preorder(self,n): if n!= None: print(str(n.item),end=' ') if n.left:...
from copy import deepcopy print("hello ") #문제 설명 #리스트가 주어졌을 때 #동일 요소가 포함되지 않은 연속된 수열의 개수 #단순하게 생각하면 그냥 새로운 원소 나올 때마다 set에 추가하고 비교...? inp = list(map(int,input().split())) sum = 0 print('input',inp) all = [] for i in range(len(inp)): temp = set([inp[i]]) sum +=1 all.append(deepcopy(temp)) ...
class Solution: def reverse(self, x: int) -> int: temp=str(x) if temp[0].isdigit(): result=temp[::-1] result=int(result) if result<pow(2,31)-1 : return result else: return 0 else: result=temp[:0:-1] result=int(...
from human import Human from ai import AI import time class Game: def __init__(self): self.player_one = Human() self.player_two = None self.run_game() self.game_state = None def display_welcome(self): print("Hello and welcome to Rock, Paper, Scissors, Lizard, Spock!") ...
# 文本文件与二进制文件的区别 textFile = open("7.1.txt","rt") print(textFile.readline()) textFile.close() binFile = open("7.1.txt","rb") print(binFile.readline()) binFile.close() # 结果: # 中国是一个伟大的国家 # b'\xd6\xd0\xb9\xfa\xca\xc7\xd2\xbb\xb8\xf6\xce\xb0\xb4\xf3\xb5\xc4\xb9\xfa\xbc\xd2' # 文本文件逐行打印 fname = input("请输入要打开的文件:") fo = ...
import collections from functools import reduce from io import StringIO import random from . import AbstractTeam from .. import datamodel class Team(AbstractTeam): """ Simple class used to register an arbitrary number of (Abstract-)Players. Each Player is used to control a Bot in the Universe. SimpleT...
""" Advanced container classes. """ from collections import Mapping class Mesh(Mapping): """ A mapping from a two-dimensional coordinate system into object space. Using a list of lists to represent a matrix is memory inefficient, slow, (ugly) and requires much effort to keep all lists the same length. ...
""" Basic graph module """ import heapq from collections import deque, UserDict class NoPathException(Exception): pass def move_pos(position, move): """ Adds a position tuple and a move tuple. Parameters ---------- position : tuple of int (x, y) current position move : tuple of int...
#!/usr/bin/env python3 import itertools import random def initial_state(teams): rr = [] for pair in itertools.combinations(teams, 2): match = list(pair) random.shuffle(match) rr.append(tuple(match)) # shuffle the matches for more fun random.shuffle(rr) return rr # def roun...
import pygame from time import * from helper import * from introFunctions import * #start menu running = startMenu() #main game loop begins while running: #Draw #screen.fill(BG) #Background background(season(day)) statBar(day, age, money, exp,jobs[jobIndex]) #stats #conditional buttons# colour = hover...
""" How many connected components result after performing the following sequence of union operations on a set of 1010 items? 1–2 3–4 5–6 7–8 7–9 2–8 0–5 1–9 """ def dynamic_connectivity(): # input_list = [(1, 2), (3, 4), (5, 6), (7, 8), (7, 9), (2, 8), (0, 5), (1, 9)] input_list = [(1, 2), (4, 5)] x = inp...
# Given an integer n, return True if n is within 10 of either 100 or 200 def almost_there(input_int): check_1 = 100 check_2 = 200 if input_int > check_1-10 and input_int < check_1+10: return True elif input_int > check_2-10 and input_int < check_2+10: return True else: retu...
""" Write a function, that reads an array of strings which will represent a list of comma-separated numbers sorted in ascending order, the second element will represent a second list of comma-separated numbers(also sorted). Your goal is to return a string of numbers that occur in both elements of the input array in sor...
# -*-coding:utf-8-*- __author__ = "pawpawDu" # 60 sec/min,60min/hr,24hr/day #oython外壳:代码结构 import time print time.timezone print time.localtime() alphabet = "" alphabet +="abdc" alphabet +="efgj" print(alphabet) #使用\连接,仍是一行 alphabet = "abcd"+\ "efjk"+\ "QEWQEQ"+\ "ddf" print alphabet #4.3使用if elif else #单值...
from tkinter import * import time import string class Menu_game(Tk): def __init__(self): Tk.__init__(self) self.geometry("500x500") self.iconbitmap("Pythonsignev.ico") self.title("Game for Bdouilleurs") self.config(background='#3FAC17') self.resizable(width=False, h...
current_users = ['Yuva','Ravi','basha','Sahil','Lakshman'] new_users = ['sahil','ravi','aravind','pankaj','santosh'] existing_users = [value.lower() for value in current_users] for new_user in new_users: if new_user.lower() in existing_users: print("user name had already taken, enter a new user name") else: print...
#time complexity:O(n) #SC:O(1) #Algo://At each step I need to find the leftmax and rightmax. Then I need to pick minimum of them and add their difference between them and the corresponding left or right element and add it to the count. This is because the water can be trapped upto the height of the minimum of two pilla...
from enum import Enum class ConstraintType(Enum): """ ConstraintType is a callable Enum for use in the integer programming solver. """ @staticmethod def __eq(x, y): return x == y @staticmethod def __leq(x, y): return x <= y @staticmethod def __less(x, y): ...
# # @lc app=leetcode.cn id=2 lang=python3 # # [2] 两数相加 # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers_1(self, l1: ListNode, l2: ListNode) -> ListNode: ans = ListNode(0) while(l...
# -*- coding: UTF-8 -*- import time # Conditions / recursif def f_Meg_recur(a,b,c=0): if b == 0 : return c else : if b%2 == 0: return f_Meg_recur(2*a,b/2,c) else: return f_Meg_recur(a,b-1,c+a) # Conditions / Iteratif def f_Meg_iter(a,b): c=0 while b != 0...
""" Advent 2020 Mission 6 Part 2: The point of this mission is to count every different caracter into different group seperate by empty line and sum all the count to get the answer. """ file = open("input.txt").read().split("\n\n") file = [i.splitlines() for i in file] rep = 0 first = [] for x in range(len(...
class Dog: def __init__(self,breed,color): # "self" is the brain of the object self.breed=breed self.color=color def speak(self): print("bhou...bhou") def jump(self): print("I am jumping") def __del__(self): print("Good Bye!") tommy=Dog("german shepherd","brown") tommy.speak() tommy.jump() print(...
def get_indices(word,char): indices = [] for index,letter in enumerate(word): if letter == char: indices.append(index) return indices print(get_indices("banana","a"))
#!/usr/bin/python import sys # Open a file input = open(sys.argv[1], "r+") valid_tri_count = 0; for line in input: #print line s1 = line[:5].strip() s2 = line[5:10].strip() s3 = line[10:15].strip() if int(s1) + int(s2) > int(s3) and int(s1) + int(s3) > int(s2) and int(s2) + int(s3) > int(s1): ...
""" Boucle "for" va au suivant à chaque tour, Boucle "while" on doit indiquer l'incrément de chacun des tours exemple --> """ sequence = range(10, 20) print("for") #ici le i est optionnel et ne sert qu'à l'affichage i = 0 for elt in sequence: #elt = element print(i, elt, sep = "->") i += 1 print("while") #ic...
""" Definitions of each of the different chess pieces. """ from abc import ABC, abstractmethod from chessington.engine.data import Player, Square class Piece(ABC): """ An abstract base class from which all pieces inherit. """ def __init__(self, player): self.player = player @abstractmet...
from collections import deque def BFS(graph,root): visited = [] queue = deque([root]) while queue: n = queue.popleft() if n not in visited: visited.append(n) queue += graph[n] - set(visited) return visited graph_list = {1:set([3,4]), ...
nome = input("Seu nome:") print ("Olá", nome) resposta = (str(input("Tudo bem com você ?, S/N:"))) if resposta == 'N' or resposta == 'n': resposta2 = input("Porque você não se sente bem?:") print ("Vai ficar tudo bem, não se preocupe com ", resposta2) else: print ("Que bom que você se sente bem,",nome)
# Simple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values #Splitting the datasets into train set and test set from sklearn.m...
''' Bubble sort. Reference: https://medium.com/@george.seif94/a-tour-of-the-top-5-sorting-algorithms-with-python-code-43ea9aa02889 Written by Junzheng 1/13/2020 ''' def bubble_sort(list_to_sort): swapped = True while swapped: length = len(list_to_sort) swapped = False fo...
# The answer for the question is in code using Separator to highlight. # just like this #---------------------------------------------------------------- #---------------------------------------------------------------- #---------------------------------------------------------------- #--------------------------------...
#!/usr/bin/python def search(searched,N): cnt =0 if len(searched) == N+1: return 1 dir = [[0,1],[0,-1],[1,0],[-1,0]] for i in range(len(dir)): next_pos = [searched[-1][0]+dir[i][0],searched[-1][1]+dir[i][1]] if next_pos not in searched: print(searched+[next_pos]) cnt = cnt + search(searched+[next_pos],...
##"""First programm""" ##s= 'Nisl scelerisque justo per hac cras purus lectus maecenas litora facilisi potenti.' ##if len(s)%2 == 0: ## print("Symbols amount is chetnoe") ##else: print("Symbols amount is nechetnoe") """The 2 program""" ##i = True ##num = str([0,2,4,6,8]) ##s1 = input("Enter the value\n") ##while i...
# Exercise 97 file = open("file.txt", "rU") lines = file.readlines() file.close() result = list() for line in lines: l = line.split("|") numbers = l[1].split(" ") values = list() for x in numbers: values.append(int(x)) for y in values: result.append(l[0][y - 1]) result.append...
__author__ = 'Julián' def ordena(l): ordenada = list() for i in l: if len(ordenada) == 0: ordenada.insert(0,i) else: for x in l: if i < x: ordenada.insert(l.index(x),i) break return ordenada print(ordena([1,3,2...
import math # Exercise 1 def get_data(): sequence = [] print("Write a sequence of numbers (type 0 for exit): ") while True: number = int(input()) if number != 0: sequence.append(number) else: break return sequence def get_mean(sequence): aux = 0 ...
""" FUNCIONES CON PARAMETROS Limites al declarar funciones Los nombres no pueden comenzar con digitos No pueden utilizar una palabra reservada Las variables deben tener diferentes nombres Los nombres de las funciones deben ser descriptivas de lo que hacen las funciones """ hello = 'hola' print(hello) ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def __init__(self): self.results = [] """ Exhaustive appproach: create a list at every node...
def eggs(cheese): cheese.append('Hello') spam = list(range(1,4)) # spam = [1, 2, 3] eggs(spam) print(spam) # Deep copy list import copy ham = ['A', 'B', 'C', 'D'] cheese = copy.deepcopy(ham) cheese[1] = 42 print('ham:\t',end = '') print(ham) print('cheese:\t',end = '') print(cheese)
print('My name is') #for i in range(5): #for i in range(12, 16): for i in range(0, 10, 2): print('Jimmy Five Times ' + str(i)) i = 0 while i < 5: print('Jimmy Five Times ' + str(i)) i += 1
from file_loader.file_loader import load_lists_from_file from algorithm3.algorithm3 import divide_and_conquer, max_crossing_subarray import unittest class Algorithm3Test(unittest.TestCase): def test_algorithm3_providedInput_shouldReturnMatchProvidedOutput(self): test_lists = load_lists_from_file('Problem...
""" 递归: 让方案更清晰,没有性能上的优势 """ class find_the_key(object): def look_for_key_normal(self,main_box): pile = main_box.make_a_pile_to_look_through() while pile is not empty: box = pile.grab_a_box(): for item in box: if item.is_a_box(): pile.appe...
""" Mini-application: Buttons on a Tkinter GUI tell the robot to: - Go forward at the speed given in an entry box. This module runs on your LAPTOP. It uses MQTT to SEND information to a program running on the ROBOT. Authors: David Mutchler, his colleagues, and Landon Bundy. """ # ---------------------------------...
import networking import socket # We are creating a socket object here for the connection socketOBJ = socket.socket() # Get local machine name localM = socket.gethostname() # This is the port that we will be working on (in this case it's TCP/UDP netbus) port = 12345 # We have to use the bind function to activate IP soc...
def my_sum(my_integers): result = 0 for x in my_integers: result += x return result def sum_of_args(*args): result = 0 for x in args: result += x return result def concatenate(**kwargs): print(f'kwargs={kwargs}') result = '' for x in kwargs.values(): resu...
import numpy as np from knn import KNN ############################################################################ # DO NOT MODIFY ABOVE CODES ############################################################################ # TODO: implement F1 score def f1_score(real_labels, predicted_labels): """ Information ...
import math def intersection( function, x0, x1 ): # function is the f we want to find its root and x0 and x1 are two random starting points x_n = x0 x_n1 = x1 while True: x_n2 = x_n1 - ( function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n)) ) if abs(x_...
""" Counting Summations Problem 76 It is possible to write five as a sum in exactly six different ways: 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 How many different ways can one hundred be written as a sum of at least two positive integers? """ def partition(m): """Returns the number of d...
""" Python implementation of bogobogosort, a "sorting algorithm designed not to succeed before the heat death of the universe on any sizable list" - https://en.wikipedia.org/wiki/Bogosort. Author: WilliamHYZhang """ import random def bogo_bogo_sort(collection): """ returns the collection sorted in ascending...
"""Find mean of a list of numbers.""" def average(nums): """Find mean of a list of numbers.""" sum = 0 for x in nums: sum += x avg = sum / len(nums) print(avg) return avg def main(): """Call average module to find mean of a specific list of numbers.""" average([2, 4, 6, 8, 20...
"""Password generator allows you to generate a random password of length N.""" from random import choice from string import ascii_letters, digits, punctuation def password_generator(length=8): """ >>> len(password_generator()) 8 >>> len(password_generator(length=16)) 16 >>> len(password_genera...
""" Greater Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor """ def gcd(a, b): """Calculate Greater Common Divisor (GCD).""" return b if a == 0 else gcd(b % a, a) def main(): """Call GCD Function.""" try: nums = input("Enter two Integers separated ...
import numpy as np import nnfs # See below for details of nnfs # https://www.youtube.com/watch?v=gmjzbpSVY1A from nnfs.datasets import spiral_data nnfs.init() # X Feature Set # y target or classification X = [[1, 2, 3, 2.5], [2.0, 5.0, -1.0, 2.0], [-1.5, 2.7, 3.3, -0.8]] X, y = spiral_data(100, 3) # 100...
#暴力搜索(不推荐),与动态规划均可解 class Solution(object): def longestPalindrome(self, s): """ :s的类型: str :返回值类型: str """ left = right = 0 n = len(s) for i in range(n - 1): if 2 * (n - i) + 1 < right - left + 1: break l = r = i while l >= 0 and r < n and s[l] == s[r]: l ...
x = input('Введите х: ') y = input('Введите y: ') x=float(x) y=float(y) y=y+x print (y)
name = input('Введите имя: ') fam = input('Введите фамилию: ') stud = input('Введите номер студенческого билета:') print('Привет, ' + name) print(fam) print(stud)