text
stringlengths
37
1.41M
# 函数返回值return name = '小明' print(name) name1 = name print(name1) def sum_(num1, num2): # 一般情况下,函数定义内部的所有数据,仅能在函数定义的内部使用 res = num1 + num2 res = num1 + num2 print(res) # 如果想要外界获取到函数内部的计算结果,需要通过return关键字将结果返回外界 # 否则,函数调用处返回的结果为None return res # 注意:return 代表代码运行结束,表示返回结果,后续代码不会继续执行 # 调用函数...
import random debug = False rules = "Jotto is a game in which two players will each guess\n" \ "each other's word by guessing 5-letter english words.\n" \ "After guessing a word, you are told how many of your\n" \ "letters were in the opponent's word. These are not\n" \ "necessarily in...
import re s=input() pattern = r'[a-zA-Z]' a =re.findall(pattern, s.lower()) if(list(a) == list(reversed(a))): print('YES') else: print('NO')
def s_intersection(x1, y1, x2, y2, x3, y3, x4, y4): left = max(x1, x3); top = min(y2, y4); right = min(x2, x4); bottom = max(y1, y3); width = right - left; height = top - bottom; if (width < 0 or height < 0): return 0; return width * height; def s(x1, y1, x2, y2): l = abs(...
# Comparisons: # Equal: == # Not Equal: != # Greater Than: > # Less Than: < # Greater or Equal: >= # Less or Equal: <= # Object Identity: is # False Values: # False # None # Zero of any numeric type # Any empty sequence. For example, '', (), []. # Any empty mapping...
def play(): print('Example: "Hey a bird" can go through, but "Hi I\'m Justin" cannot go through.') print('Recognize the pattern? Type a word that can go through the Green Glass Door.') print('*Hint.* Think about something that is a dessert and is used as a constant in math.') answer = input('Answer: ') ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2013-2017 Recursos Python # www.recursospython.com # from functools import partial import atexit import os import keyboard MAP = { "space": " ", "\r": "\n" } #Contadores especificos para TiltLord q=0 w=0 e=0 r=0 # Ubicación y nombre del archivo q...
import random CELL_NULL, CELL_X, CELL_O = range(3) WIN_NULL, WIN_X, WIN_O = range(3) class Cell: def __init__(self, x, y, state=CELL_NULL): self.x = x self.y = y self.state = state # initialize cells = [] for i in range(3): for j in range(3): cells.append(Cel...
import system repeat = 'no' logged = False isused = 'yes' security = 'yes' while isused == 'yes': while logged == False: print('') print(';;;;;;;;;;;;;;;;;;;;;;;;;;;;'.center(50)) print('; ATM INDONESIA ;'.center(50)) print(';--------------------------;'.center(50)) ...
# radix sort def countingsort(a,exp1): n=len(a) output=[0]*n count=[0]*(10) for i in range(0,n): index=(a[i]//exp1) count[int(index%10)]+=1 for i in range(1,10): count[i]+=count[i-1] i=n-1 while i>=0: index=(a[i]/exp1) output[count[int(index%10)]-1]=a[...
def isprime(n): flag=1 for i in range(2,n//2+1): if n%i==0: flag=0 break return flag def checksum(a,b): return isprime(a) and isprime(b) and isprime(a+b) # print(c) if __name__ == "__main__": c=0 limit=int(input("Enter the upper range of the limit...
# to add two polynomials def add(a,b,m,n): size=max(m,n) sum=[0 for i in range(size)] for i in range(0,m,1): sum[i]=a[i] for i in range(n): sum[i]+=b[i] return sum def printpoly(poly,n): for i in range(n): print(poly[i],end="") if i!=0: print("x^",i,en...
def balanceparen(exp): stack=[] for char in exp: if char in ["(","{","["]: stack.append(char) else: if not stack: return False currentchar=stack.pop() if currentchar=="(": if char!=")": return Fal...
print('1024的二进制:'+bin(1024)) #转换2进制 print('1024的16进制:'+hex(1024)) #转换16进制 print(oct(1024)) x = 5.23222 print("%.2f" %x) print(round( x , 2 )) s='hello ahoa jjad, Aoedk ?' print(s.islower()) s2 = 'wwwhsjhhwjwwwwwwww' print(s2.count('w')) set1 ={2,3,1,5,6,8} set2 = {3,1,7,5,6,8} print(set1.difference(set2)) print(set...
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will #be: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. de...
# Find Eulerian Tour # # Write a function that takes in a graph # represented as a list of tuples # and return a list of nodes that # you would follow on an Eulerian Tour # # For example, if the input graph was # [(1, 2), (2, 3), (3, 1)] # A possible Eulerian tour would be [1, 2, 3, 1] def find_eulerian_tour(graph): ...
T = int(raw_input()) for x in range(T): S = raw_input() tokens = list(S) elements = [] j = 0 for i in range(len(tokens)): if not elements: j = i j+=1 elements.append(tokens[i]) else: if elements[j-1] != tokens[i] : elements.append(tokens[i]) j+=1 S = ''.join(str(alphabet) for alphabet in...
import unittest # Given a list of words, print a tuple of (first-letter, word) for each word, in order. def tuple_word(lst): for word in lst: print (word[0], word) print tuple_word(['this', 'is', 'a', 'list']) class Test(unittest.TestCase): data = [ (['this'], ('t', 'this')) ...
"""Reverse word order, keeping spaces. As a simple case, an empty string returns an empty string: >>> rev("") '' A simple word is also the same: >>> rev("hello") 'hello' Here, we reverse the order of the words, preserving the space between: >>> rev("hello world") 'world hello' Here, we re...
'''Rotate arrays by k indices to left or right''' def rotate_array_left(lst, k): length = len(lst) result_left = [] for idx in range(length): result_left.append(lst[(k % length + idx) % length]) return result_left def rotate_array_right(lst, k): length = len(lst) result_right = [] ...
import unittest def insertion_sort(alist): for index in range(1,len(alist)): # element to be compared current = alist[index] # comparing current element with the sorted portion and swapping while index > 0 and alist[index - 1] > current: alist[index] = alist[index - 1] ...
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': arr = [] for idx in range(6): arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')] arr.append(arr_t) def max_hourglasses(arr): max = None for i in range...
"""Convert a hexadecimal string, like '1A', into it's decimal equivalent. >>> hex_convert('6') 6 >>> hex_convert('10') 16 >>> hex_convert('FF') 255 >>> hex_convert('FFFF') 65535 """ def hex_convert(hex_in): """Convert a hexadecimal string, like '1A', into it's decimal equivalen...
import unittest def shortest_point(matrix): found_row = [] found_col = [] for row_num, row in enumerate(matrix): for col_num, element in enumerate(row): if element == 1: found_row.append(row_num) found_col.append(col_num) first_coord = abs(found...
import unittest import collections '''Given an array of integers and an integer k, find the number of unique k-diff pairs in the array''' def find_pairs_1(nums, k): lst_tupes = set() for idx1, num1 in enumerate(nums): for idx2, num2 in enumerate(nums): diff = abs(num1 - num2) ...
import unittest def merge(lst1, lst2): '''Function to merge two arrays''' new_lst = [] idx1 = 0 idx2 = 0 while idx1 < len(lst1) and idx2 < len(lst2): if lst1[idx1] <= lst2[idx2]: new_lst.append(lst1[idx1]) idx1 += 1 else: new_lst.append(lst2[idx2]...
from python.basic.stack_by_list import Stack from string import digits, ascii_lowercase def infix_to_postfix(string: str) -> str: """ 生成后缀表达式 :param string: :return: """ stack = Stack() # 运算符优先级 d = { '*': 3, '/': 3, '+': 2, '-': 2, '(': 1, ...
from python.basic.stack_by_list import Stack def divide_by2(i): s = Stack() while i != 0: r = i % 2 s.push(r) i //= 2 res = '' while not s.is_empty(): res += str(s.pop()) return res if __name__ == '__main__': assert divide_by2(5) == '101' assert divide_...
print() print() print ("__________") variabletype="int" print (variabletype) print ("__________") a=1 b=a print(f"initial value of {type(a)} a is {a} with id of {id(a)}") print(f"initial value of {type(b)} b is {b} with id of {id(b)} ") a=5 print(f"after change the value of {type(a)} a is {a} with id of {id(a)} ") prin...
#importing pandas to deal with the dataset import pandas as pd #readnig the datasets that we will work on it test = pd.read_csv("test.csv") train = pd.read_csv("train.csv") #show our data to extract information about it and specify the features that we will predict on it test.head() test.columns #specifying the feat...
from cv2 import cv2 import numpy as np img = cv2.imread('photo.jpg') height , width = img.shape[:2] print(height,width) r_matrix = cv2.getRotationMatrix2D((height/2,width/2) , 90 ,.5) r_image = cv2.warpAffine(img , r_matrix , (height, width)) cv2.imshow('orig', img) cv2.waitKey(0) cv2.imshow('rotated', r_image...
# ----------------------------------------------------------------------------- # Name: Nisheeth Shah # Id: 29599644 # Start Date: 21/05/2018 # Last Modified Date: 22/05/2018 # Assignment 3: Task 1: Setting up the preprocessor # ----------------------------------------------------------------------------- cl...
import numpy as np import sys ''' This program implements the Strassen's matrix multiplication algorithm to multiply two square matrices of size 2^n * 2^n. Input: Matrices A and B of dimensions 2^n * 2^n respectively. Output: The product matrix A * B of dimensions 2^n * 2^n. Approach: We implement the Strassen's...
import sys from random import randint ''' This file implements the simulation of the famous monty-hall problem. https://en.wikipedia.org/wiki/Monty_Hall_problem. Input: Number of iterations to run the simulation. Output: Probability of a switching win (explained below) Monty Hall Problem: Suppose you're on a g...
# Source: https://stackoverflow.com/questions/44497352/printing-colors-on-screen-in-python import numpy as np import matplotlib.pyplot as plt from skimage import io palette = np.array([[255, 0, 0], # index 0: red [ 0, 255, 0], # index 1: green [ 0, 0, 255], # index ...
import unittest from calvin.numbers import Numbers class NumbersTest(unittest.TestCase): """ Test Numbers method """ def setUp(self): self.fixture = Numbers() def test_fibonacci(self): actual = self.fixture.fib(35) self.assertEqual(9227465, actual) def test_fibonacci_...
class ListNode(object): def __init__(self, value=None, next=None): self.value = value self.next = next def getNodes(self,r): if self is None: return r if self.next: self.next.getNodes(r) r.insert(0,self.value) return r def __repr__(s...
class WordSearch(object): def exist(self, board: [], word: str) -> bool: for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == word[0]: if WordSearch.__search_adjacent(board, word[1:], i, j): return True ...
from typing import List class Numbers(object): """ Implementation on String Manipulation """ def fib(self, n): """ :type s: str :type t: str :rtype: str """ if n == 0: return 0 elif n == 1: return 1 else: return self.fib(n-1)+self.fib(n-2...
class Two_1(object): def remove_dupe(self, head): s = set() previous = None while (head != None): if head.value in s: previous.next = head.next else: s.add(head.value) previous = head head = head.next
''' % [rot_mat] = rotmax (angle) % To obtain the rotation matrix around the X axis given the % rotation angle. % inputs: % angle % rotation angle, in radians. % outputs: % rot_mat % rotation matrix (3, 3) % % Valdemir Carrara, Sep, 1998''' import math import numpy as np def rotma...
''' % [rot_mat] = quatrmx (quaternion) % To compute the rotation matrix given the quaternions. % inputs: % quaternion % attitude quaternions (4) Q = q1 i + q2 j + q3 k + q4 % outputs: % rot_mat % rotation matrix (3, 3) % % Valdemir Carrara, Sep. 1998 ''' import numpy as np def quatrmx...
''' % [quaternions] = ezxzquat (euler_angles) % To transform Euler angles from a X-Y-Z rotation % into quaternions. % inputs: % euler_angles % Euler angles from a X-Y-Z rotation, in radians (3) % outputs: % quaternions % quaternions corresponding to the Euler angles % % Valdemir Carrar...
''' def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) print(factorial(5)) ''' import sys def factorial(n): listArr = range(1,n) s = iter(listArr) while (1): try: n = n*next(s) except: return n try: accept_user_input = int(input ("enter number for factorial...
import nltk from nltk.corpus import stopwords stop_words = stopwords.words('english') def tokenize(text): return nltk.word_tokenize(text) def preprocess(text, remove_stop=True): tokenized = tokenize(text.lower()) if remove_stop: return [w for w in tokenized if w.isalpha() and w not in stop_words...
##this is the example ##program of the python tutorial """ ########## BEST Practices for the beginners ################ 1. Never save ur program in the installation directory, it treat your program as libraries This leads to slower module search 2. Never use the inbuilt funtion names as user defined variable...
#!/usr/bin/env python __author__ = 'Will Dennis' __email__ = 'wdennis@nec-labs.com' import random num_to_guess = random.randint(1, 100) user_input = -1 guess_count = 0 while user_input != num_to_guess: user_input = int(raw_input("Please enter your guess: ")) guess_count += 1 if user_input > num_to_gues...
# Definição do Objeto Biblia import xml.etree.ElementTree as ET import string import re import sys class Biblia(object): """ Define objeto Biblia """ def __init__(self, arquivo): '''Inicializa o objeto com a Biblia XML''' self.arquivo = arquivo tree = ET.parse(arquivo) self.biblia = tree.getroo...
def list_visited(position, visited_houses, string): for c in string: if c == '^': position = (position[0], position[1]+1) elif c == '>': position = (position[0]+1, position[1]) elif c == '<': position = (position[0]-1, position[1]) elif c == 'v':...
import re def has_three_vowels(string): res = re.findall(r"[aeiou]",string) if len(res) >= 3: return True else: return False def has_double_letter(string): res = re.search(r"(\w)\1",string) if res: return True else: return False def has_not_ugly(string): ...
inp = input("enter any string to compress: ") count = 1 for i in range(1, len(inp) + 1): if i == len(inp): print(inp[i - 1] + str(count), end="") break else: if inp[i - 1] == inp[i]: count += 1 else: print(inp[i - 1] + str(count), end="") ...
import abc class MachineLearningModel: @abc.abstractmethod def predict(self, input): raise NotImplementedError("Implement your sound!") class CustomClassifier(MachineLearningModel): def predict(self, input): print("Cool ML stuff happening...")
import numpy as np import matplotlib.pyplot as plt class insertionSortOperator: def __init__(self,loadedArray, plot): self.toSort = loadedArray self.sorted = False self.plot = plot if len(loadedArray) < 2: self.sorted = True else: self.propagate = 1...
def cipher(S): x = '' for i in S: if ord('a') <= ord(i) <= ord('z'): s = chr(219 - ord(i)) else: s = i x = x + s return x S = 'rx2gg4' print(cipher(S))
#!/bin/python3 # # Write your code here :-) from gpiozero import Robot import time robby = Robot(left=(8, 7), right=(9, 10)) SLEEP_TIME_SECONDS = 0.5 TURN_SPEED = 1 def do_short_leg(): ''' Move forward for X seconds, then turn right 90 degrees. ''' robby.forward() # starts forward motion and return...
// Source : https://oj.leetcode.com/problems/two-sum/ // Author : Uditanshu Problem- ********************************************* Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not ...
import pygame,sys,random blockH = 10 blockW = 150 score = 0 speed = 2 #block object class Block: def __init__(self, x, y, color, speed): self.x = x self.y = y self.w = blockW self.h = blockH self.color = color self.speed = speed def draw(...
''' Your task is to find the number of inversions in the file given (every row has a single integer between 1 and 100,000). Assume your array is from 1 to 100,000 and ith row of the file gives you the ith entry of the array. Write a program and run over the file given. ''' import random def main(): #arr = range(10) ...
import sys def magic(x, y): return x + y * 2 x = sys.argv[1] y = sys.argv[1] answer = magic(x, y) print('The answer is: {}'.format(answer))
import sys # prompt messages can be passed as a parameter to the input function temp_cel = input("Enter temperature in celcius ") # try except is cleaner way of handling type checks try: # convertion can be stored back to the same variable temp_cel = float(temp_cel) except ValueError: print("Cannot conver...
a_var = 'global value' def outer(): a_var = 'local value' print('outer before:', a_var) def inner(): nonlocal a_var a_var = 'inner value' print('in inner():', a_var) inner() print("outer after:", a_var) outer()
''' Your local university's Raptors fan club maintains a register of its active members on a .txt document. Every month they update the file by removing the members who are not active. You have been tasked with automating this with your python skills. Given the file currentMem, Remove each member with a 'no' in thei...
import re pattern = r'\d+' s = "2019/4/23,海军70年" it = re.finditer(pattern, s) # print(dir(next(it))) #  迭代到的内容为match对象 for i in it: print(i.group()) # 获取match对象内容 # 完全匹配目标字符串内容 obj = re.fullmatch(r"\w+","J_bob") print(obj.group()) # 匹配目标字符串开始位置 obj = re.match(r"[A-Z]\w+","Hello World") print(obj.group()) # 匹...
# 3.大作业:把一个文件夹下面至少1000个文件拷贝到另一个文件夹下面 # ,使用多进程(进程池,多线程,线程池) # 怎么证明你拷贝的文件没有问题, # 什么是哈希(Hash)?  # 给一段信息做指纹:指纹是唯一的,没有碰撞 def file_copy(): f=open(file, 'r') s = f.read() f.close() def file_paste(): f2=open(file2,'w') f2.write(s) f2.close()
# n#=input("请输入季度:") # n=int(n)# # if n==1: # print("第一季度有1,2,3月") # elif n==2: # print("第三季度有7,8,9月") # print("第四季度有10,11,12月") # else # n=input("请输入学生成绩:") #n=int(n) #if 0<=n<=100: # print("输入合法") #if 0<=n<=59: # print("不及格") # elif 60<=n<=79: # print("及格") # elif 80<=n<=89: ...
from multiprocessing import Process import time class mytime(Process): def __init__(self,interval): Process.__init__(self) self.interval=interval def run(self): while True: time.sleep(self.interval) print(time.ctime(),"休息一下") if __name__=="__main__": t=mytim...
# while 0<1: # x=input('用户名:') # y=input('密码:') # if x=="tarena" and y=="123456": # print('欢迎你回来') # break # else: # print("错误,请重新输入!") # i=1 # while i<=3: # x=input('用户名:') # y=input('密码:') # if x=="tarena" and y=="123456": # print('欢迎你回来') # break #...
class Solution: def __init__(self): self.path = [] def isHappy(self, n: int) -> bool: sqsum = self.sqsum(n) # print(sqsum) if sqsum in self.path: return False self.path.append(sqsum) return sqsum == 1 or self.isHappy(sqsum) def sqsum(self, n:...
""" Gym wrapper classes that transform the action space of Gym-Duckietown to alternative representations. The original actions of Duckietown are the normalized wheel velocities of the robot. These alternative action representations are - Discrete - Wheel velocity - Braking - Wheel velocity - Clipped (to [0,...
class DigitError(Exception): def __init__(self, text): self.text = text num = 0 result = [] while num != 'stop': try: num = input('Введите число или "stop": ') if num == 'stop': continue for el in num: if el.isdigit(): valid = True ...
def passport(name, surname, year_of_birth, city, email, phone): """Принимает данные о пользователе и выводит одной их строкой Именованные параметры: name -- Имя surname -- Фамилия year_of_birth -- год рождения city -- город email -- почта phone -- телефон """ return f'Имя - {na...
class Date: def __init__(self, input_date): self.input_date = input_date @classmethod def method_integer(cls, date): result = [int(i) for i in date.input_date.split('-')] return result @staticmethod def valid_method(day, month, year): invalid = 'Невалидное значение'...
# Номер 5 - вариант 2 f_obj = open('text5-2.txt', 'w') numbers = input('введите числа разделенные пробелами: ') f_obj.write(numbers) f_obj.close() f_obj = open('text5.txt', 'r') numbers_in = f_obj.read() result = sum([int(num) for num in numbers.strip().split(' ')]) print(result)
# Номер 5 вариант 1 with open('text5-1.txt', 'w+') as f_obj: try: numbers = input('введите числа разделенные пробелами: ') f_obj.write(numbers) f_obj.seek(0) numbers_in = f_obj.read() result = sum([int(num) for num in numbers.strip().split(' ')]) print(result) exc...
from functools import reduce def muli_culc(prev_num, num): """Перемножает предыдущее число в списке со следующим prev_num - предыдущее число num - следующее число """ return prev_num * num numbers = [number for number in range(100, 1001, 2)] print(reduce(muli_culc, numbers))
# how to manupulate a loop with i and j def forLoops(Arr): size = len(Arr) sum = 0 #i starts from 0 to size for i in range (0, size): #j starts from i to size, # bubble sort uses this method for j in range ( i, size-1 ): if ( Arr[i]>Arr[j]): temp = ...
# Given a list of intervals A and one interval B, find the least # number of intervals from A that can fully cover B. # # If cannot find any result, just return 0;. 1point3acres.com/bbs # # For example: # Given A=[[0,3],[3,4],[4,6],[2,7]] B=[0,6] return 2 since we can use [0,3] [2,7] to cover the B # Given A=[[0,3],[4,...
class Solution: def areSentencesSimilarTwo(self, words1, words2, pairs): """ :type words1: List[str] :type words2: List[str] :type pairs: List[List[str]] :rtype: bool """ if len(words1) != len(words2): return False parents = dict() for w in wo...
""" Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For example: Given "aacecaaa", return "a aacecaaa". Given "abcd", return "dcb abcd". """ class Solution(object): def sh...
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). """ class Solution(object): def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums...
def depthSumInverse(nestedList): ret=[0] helper(nestedList, ret) return ret[0] def helper(nestedList, ret): maxh=0 my_sum=0 for nl in nestedList: if type(nl)==int: my_sum+=nl else: maxh=max(maxh,helper(nl,ret)) maxh+=1 ret[0]+=my_sum*maxh retu...
def flatten(l): ret=[] for it in l: if type(it)==int: # do not use 'int', int, list directly. ret.append(it) else: # list ret.extend(flatten(it)) return ret print flatten([[1,1],2,[1,1]]) print flatten([1,[4,[6]]])
import collections def shortestDistance(grid): # start from content 1, calculate distance to all 0's m=len(grid) n=len(grid[0]) distances=[[0]*n for _ in range(m)] # 0 node in grid, distances to all 1's cnt=[[0]*n for _ in range(m)] # 0 node in grid, all 1 nodes it can reach. buildings=sum(va...
def joseph1(nums,k): # nums from 1 to N if not nums: return -1 ind=0 while len(nums)>1: ind=(ind+k-1)%len(nums) nums.pop(ind) return nums[0] print joseph1([1,2,3,4,5,6,7,8,9,10],3) # 4 print joseph1([1],3) # 4 print joseph1([1,2],3) # 4 print joseph1([1,2,3],3) # 4 print '******...
import collections class Solution(object): def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ from_to=collections.defaultdict(list) for pair in tickets: from_to[pair[0]].append(pair[1]) from_to[pair[0]]...
import Queue class Solution(object): def findMaximizedCapital(self, k, W, Profits, Capital): """ :type k: int :type W: int :type Profits: List[int] :type Capital: List[int] :rtype: int """ q=Queue.PriorityQueue() projects=sorted(zip(Capital,Pr...
import copy class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ret=[] nums.sort() self.perm(ret,nums,0) return ret def perm(self,ret, nums, ind): if ind==len(nums)-1: ...
import collections def maxSlidingWindow(nums, k): ret=[] qu=collections.deque() for i in range(len(nums)): while len(qu)>0 and qu[0]<=i-k: qu.popleft() while len(qu)>0 and nums[qu[-1]]<nums[i]: qu.pop() qu.append(i) if i>=k-1: ret.append(nums[qu[0]...
class ListNode(object): def __init__(self,val): self.next=None self.val=val class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ if not head or not head.next: ...
redo=1 while redo == 1: import random #first sentence praising student x=random.randint(0,8) y=random.randint(0,8) if y == x: y=random.randint(0,8) adjectivecomments=["great", "fantastic", "super", "excellent", "outstanding", "top notch", "first class", "supreme", "wonderful"] ...
def flatten(element, flat_arr=None): """ This method takes nested array as a parameter and returns as flattened version of it. :element : list example: element=[1,[2,3,[4],5,[6]]] output = [1,2,3,4,5,6] """ if flat_arr == None: flat_arr = [] if not isinsta...
def add(n1,n2): return n1+n2 def subtract(n1, n2): return n1-n2 def multiply(n1, n2): return n1*n2 def divide(n1, n2): def divide(n1, n2): if n2 != 0: return n1/n2 else: return ("Error: Division by Zero") def main(): print (add(100,10)) print (subtract(100,10)) pr...
import numpy as np class Perceptron: def __init__(self, learning_rate=0.01, n_iters=1000): self.lr = learning_rate self.n_iters = n_iters self.activation_func = self._unit_step_func self.weights = None self.bias = None # X is the training samples # y is the traini...
""" Задание 7.03 Написать программу для нахождения факториала. Факториал натурального числа n определяется как произведение всех натуральных чисел от 1 до n включительно """ number = int(input('Input number: ')) i = 1 s = 1 while i <= number: s *= i i += 1 print(s) ...
#Create a lambda function that takes a name # as input and outputs it in the format “Hello, {name}” answer = lambda x: f'Hello, {x}!' print(answer(input('Input name here: ')))
""" Задание 3.04 Ввести предложение. Если число символов в предложении кратно 3 - добавить ! к концу строки. Вывести строку на экран. """ s = input('input string: ') if not len(s) % 3: print(f's!') """ Задание 3.05 Ввести предложение. Если в предложении есть слово code - выве...
""" Задание 5.05 Создать список с фамилиями. Вывести все фамилии, которые начинаются на П и заканчиваются на а """ s = input('Input las name (for stop input "0"): ') a = [] if not len(s): print('end') else: while s != "0": a.append(s) s = input('Input las name (for stop i...
#A list of words is given. # Generate a new list with inverted words list_=list(map(str, input('Input words with space: ').split())) print(list(map(lambda x: x[::-1], list_)))
""" Create class Car. Attributes: brand, model, year of manufacture, speed (default 0). Methods: increase speed (speed + 5), decrease speed (speed - 5), stop (reset speed to 0), display speed, turn (change the sign of speed). All attributes are private. """ class Car: def __init__(self, brand, model, ye...
""" Задания 3.09 Вычислить квадратное уравнение ax2 + bx + c = 0 (*) D = b2 – 4ac; x1,2 = (-b +/- sqrt (D)) / 2a Предусмотреть 3 варианта: 1) Два действительных корня 2) Один действительный корень 3) Нет действительных корней """ a = int(input('Input a = ')) b = ...