text
stringlengths
37
1.41M
motorcycles=['honda','yamaha','suzuki'] print(motorcycles) #修改元素 motorcycles[0]='ducati' print(motorcycles) #方法append()添加元素到列表末尾 motorcycles.append('ducati') print(motorcycles) #方法insert()在列表的任何位置中添加新元素,并将往后的每个元素右移一个位置 motorcycles.insert(0,'ducati') print(motorcycles) #从列表中删除元素——1.已知要删除的元素在列表中的位置,使用del语句; #del list[0:-...
name="anthony" print(name.title()) print(name.upper()) print(name.lower()) print("------") print("My name is "+name.title()+", Nice to meet you!") say_hello="My name is "+name.title()+", Nice to meet you!" print(say_hello)
print("Please input what toppings you want to add:") active=True#使用标志 toppings=[]#列表存放topping while active: topping=input() if topping == 'quit': break; else: toppings.append(topping) if len(toppings) == 1: print("The toppings you have added is:\n"+toppings[0]) elif len(toppings) == 0: print("Are you sure?") e...
def findSmallestIndex(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selectionSort(arr): resultArr = [] for i in range(len(arr)): smallest = fin...
list = [3, 8, 9, 5, 4, 2] # 여기에서 7이 있으면 true 없으면 false를 리턴하는 함수를 만들어보세요. def findNumber(number): for item in list: if(item == number): return True return False print(findNumber(2)) print(findNumber(7))
def search(arr, num): start = 0 end = len(arr) - 1 while(True): pivot = (start + end) // 2 if arr[pivot] == num: return pivot elif arr[pivot] > num: end = pivot else: start = pivot numbers = [1, 2, 3, 4, 5] result = search(numbers, 4) pri...
list = [8, 2, 10, 6, 1] min = list[0] for i in range(1, len(list)): if min > list[i]: min = list[i] print(min) print('daaasdf'.index('a'))
from math import sqrt from datetime import datetime def is_prime(n): for i in range(2, int(sqrt(n))): # n까지 하면 n-1까지 반복 됨 if n % i == 0: return False # 한번이라도 나누어 떨어지는 수가 나오면 False return True # n - 1까지 나누었으나 모두 나머지가 있다면 True # 99999989 # print(is_prime(99999989)) # print(is_prime(199999963)...
from math import sqrt def sieve(N): ns = list(range(2, N + 1)) # 2부터 50까지 숫자 생성 for i in range(2, int(sqrt(N)) + 1): # 루트 N이하의 자연수 for j in range(len(ns) - 1, 1, -1): if ns[j] % i == 0 and ns[j] > i: # 자기 자신은 지우면 안되기 때문에 > i ns.pop(j) return ns from _datetime import ...
def swap(a, b): temp = a a = b b = temp print(a, b) swap(1, 2)
# 소수(prime)인지 판별하기 1 # 주어진 숫자까지 2부터 모두 나누어 보는 방법 def is_prime(num): for i in range(2, num//2 + 1): # num // 2까지 반복 if num % i == 0: return False # 나머지가 0인지 return True # 이유는 약수중에 가장 큰 것은 num // 2보다 작기 때문 # ex) 20의 약수는 20, 10, 5, 4, 2, 1 인데 이중 자신을 제외하고 가장 큰 것은 10 # ex2) 6 -> 6, 3, 2, 1 primes ...
statement = "1.8 + (3*2)".replace(" ", "") print(statement) def tokenizer(statement): arr = [] accu = "" for word in statement: if word in "[]{}()+-*/^": if accu != "": arr.append(accu) accu = "" arr.append(word) else: accu...
arr = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11] def binarySearch(arr, targetNum): midIndex = len(arr) // 2 indexValue = arr[midIndex] print(midIndex, indexValue) return -1 print(binarySearch(arr, 8))
l = ['A', 'B', 'C'] def fn2(arr): if len(arr) == 2: return [f'{arr[0]}{arr[1]}', f'{arr[1]}{arr[0]}'] else: r = [] for i in range(len(arr)): extracted = arr.pop(0) for string in fn2(arr): r.append(f'{extracted}{string}') arr.append(ext...
from datetime import datetime def while1(s): while '()' in s or '{}' in s or '[]' in s: sp = s.split('()') s = ''.join(sp) sp = s.split('{}') s = ''.join(sp) sp = s.split('[]') s = ''.join(sp) return len(s) == 0 s = f'{"("*(2*pow(10,4))}{"{"*(2*pow(10,4))}{"["*(2*pow(10...
numbers = [12, 49, 20, 4, 25, 2, 14] memo = [1] * len(numbers) print(len(numbers), len(memo)) for i in range(0, len(numbers) - 1): for j in range(i + 1, len(numbers)): if numbers[j] > numbers[i]: memo[i] = memo[i] + 1
list = [] print(list) for i in range(10): list.append(i) print(list) list.append(10) print(list)
string = 'out of sight, out of mind' count_each = [0] * 26 for char in string: if char.isalpha() == True: print('------ isalpha ----')
def sum(num): result = 0 while (num > 0): result = result + num num = num - 1 return result print(sum(100))
def solution(numbers): s_l = list(map(str, numbers)) s_l.sort(key=lambda x: x*3, reverse=True) return str(int(''.join(s_l))) print(solution([6, 10, 2]) == '6210') print(solution([3, 30, 34, 5, 9]) == '9534330') # print(solution([6, 10, 2, 70]) == '706210') # print(solution([6, 10, 2, 70, 72]) == '72706210'...
is_odds = lambda x : x % 2 == 1 def multiply1(n, a): if(n == 1): return a if (is_odds(n)): return multiply1(n // 2, a + a) + a else: return multiply1(n // 2, a + a) print(multiply1(4, 5)) print(multiply1(4, 6))
# for문 쓰지 말고 해보세요 def sum_start_to_end(start, end, accu): if(start > end): return accu else: return sum_start_to_end(start + 1, end, accu + start) print("result:", sum_start_to_end(1, 100, 0))
word = "test" # 가장 많이 등장하는 알파벳 찾기 def highFrequencyTimes(word): map = {} for chr in word: if map.get(chr) == None: map[chr] = 1 else: map[chr] = map[chr] + 1 max = 0 for item in map: if max < map[item]: max = map[item] print(max) highFreq...
list = [3, 8, 9, 5, 4, 2] odds = [] evens = [] for item in list: if(item % 2 == 1): odds.append(item) else: evens.append(item) print("odds:", odds) print("evens:", evens)
numbers = [10, 22, 9, 33, 21, 50, 41, 60, 80] numbers2 = [50, 3, 10, 7, 40, 80] def lis(numbers): memoList = [1 for _ in range(len(numbers))] for i in range(len(numbers)): for j in range(i + 1, len(numbers)): if numbers[i] < numbers[j] and memoList[i] + 1 > memoList[j]: mem...
def simplify(str): stack = [] result = "" for chr in str: if(chr == "+"): if(len(stack) > 0 and stack[len(stack)-1] == 1): result = result + "-" else: result = result + "+" elif(chr == "-"): if(len(stack) > 0 and stack[len(s...
def solution(arr1, arr2): # 3 * 2행렬 answer = [ [-1] * len(arr2[0]) for _ in range(len(arr1))] arr1_column_cnt = len(arr1[0]) for i in range(len(arr1)): for j in range(len(arr2[0])): answer[i][j] = 0 for i_col in range(arr1_column_cnt): answer[i][j] += ar...
string = "ABCDEDE" array = [] for i in range(len(string)): array.append(0) print(array, len(array))
string = "1+2*(3-4)" #["1", "+", "2", "*", "(", "3" ,"-" , "4", ")"] def stringTokenizer(string): return[] result = stringTokenizer(string) print(result)
def get_another(num): if num == 0: return 1 else: return 0 def get_paths(graph, start, goal): queue = [start] result = [] while queue: n, path = queue.pop() if n == goal: result.append(path) else: graph[n].pop() def solution(roads): ...
def solution(operations): queue = [] for operation in operations: spl = operation.split(" ") number = int(spl[1]) if spl[0] == "I": queue.append(number) elif spl[0] == "D" and number == 1: # 최대값 지움 queue.index(int(spl[1])) elif spl[0] =...
def solution(numbers): for num in numbers: # numbers에서 num을 하나씩 뽑는다 print(num) numbers = [9, 22, 3, 7, 4, 5] solution(list)
numbers = [8, 5, 9, 10] middle = len(numbers) // 2 left = sorted(numbers[0:middle]) right = sorted(numbers[middle:len(numbers)]) sorted_arr = [] pointer_left, pointer_right = 0, 0 while pointer_left < len(left) and pointer_left < len(right): if left[pointer_left] <= right[pointer_right]: sorted_arr.append...
arr = [1,2,3,5,6,7,8,9,10,11] def simpleSearch(arr, targetNum): for index in range(0, len(arr)): print(arr[index]) return -1 print(simpleSearch(arr,8))
def count_sheeps(sheep): return (sheep.count(True)) array1 = [True, True, True, False, True, True, True, True , True, False, True, False, True, False, False, True , True, True, True, True , False, False, True, True ] print(count_sheeps(array1...
print ( "введите число" ) a = int ( input() ) print ( "ваше число" ) print (a * ( -1 ) )
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] result = list(set(a) & set(b)) print(result) #c = [] #for i in a: #if i in b: # c.append(i) #print(c) # через функцию #c = list(filter(lambda elem: elem in b, a)) #print (c)
from math import * x = int(input("Enter x:")) y = ((e**(2*x)*sqrt(x)-((x+1/3)/x))**1/3)*abs(2.5*x) print(y)
from math import * x = int(input("Enter x:")) y = (abs(7.2 - 10*x)/(x**2 + e**x)**1/3)*atan(4*(x/3)/(1.1**3+x**2)**1/2) print(y)
from math import * x = int(input("Enter x:")) y = (sqrt(sin(x/2)**3))+(e**(1.3*x)+e**(-1.3*x))*(1/(abs(x+5/2))) print(y)
from math import * x = int(input("Enter x:")) y = 2*pi*x - abs( sin(10.5*x)*1/2)*1/(x**2+1/7)**1/3 print (y)
from __future__ import print_function from collections import defaultdict as dd """ In class exercise from 1/27/17 """ file = open('SoManyWords.txt', 'r') word_count = dd(int) stop = False for line in file: # inspired by/taken from http://stackoverflow.com/a/16922328 for word in line.split(): word_cou...
import pygame import random from utils import * # Define the cloud object by extending pygame.sprite.Sprite # Use an image for a better-looking sprite class Cloud(pygame.sprite.Sprite): def __init__(self): super(Cloud, self).__init__() self.surf = pygame.image.load("images/cloud.png").convert() ...
number = int(input()) input_list = [] for _ in range(number): input_list.append(int(input())) for i in range(len(input_list)): index = i for j in range(i+1,len(input_list)): if input_list[index] > input_list[j]: index = j input_list[i], input_list[index] = input_list[ind...
x = int(input()) for i in range(1, x+1): if i == 1: print(' ' * (x-i)+'*') else: print(' ' * (x-i)+'*'+' '*(i*2-3)+'*')
class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return root binary_tree_list, queue = [], [root] while len(queue) != 0: children, parent_val = [],...
""" Good morning! Here's your coding interview problem for today. This problem was asked by Amazon. There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. ...
""" Good morning! Here's your coding interview problem for today. This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain dupli...
""" Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost. Print the total meal cost, where it is the rounded integer result of the entire b...
#!/bin/python # http://hr.gs/abbbca import os # Complete the twoArrays function below. def twoArrays(k, A, B): A = sorted(A) B = sorted(B, reverse=True) result = "YES" for i in xrange(len(A)): if A[i] + B[i] < k: result = "NO" break return result if __name__ ==...
#!/bin/python # Standardize Mobile Number Using Decorators def wrapper(f): def fun(l): # complete the function formatted = ["+91 "+_[-10:-5]+" "+_[-5:] for _ in l] f(formatted) return fun @wrapper def sort_phone(l): print '\n'.join(sorted(l)) if __name__ == '__main__': l =...
#!/bin/python # http://hr.gs/16xx class Player: def __init__(self, name, score): self.name = name self.score = score def __repr__(self): return "("+self.name+","+str(self.score)+")" def comparator(p1, p2): cmp = p2.score - p1.score if cmp == 0: if p1.name...
#!/bin/python # http://hr.gs/eddcca from itertools import combinations_with_replacement x = raw_input().split() #string = sorted(set(list(x[0]))) string = sorted(list(x[0])) k = int(x[1]) L = list(combinations_with_replacement(string,k)) for j in L: print ''.join(j)
""" Training a GNN for Graph Classification ======================================= By the end of this tutorial, you will be able to - Load a DGL-provided graph classification dataset. - Understand what *readout* function does. - Understand how to create and use a minibatch of graphs. - Build a GNN-based graph cl...
def comp(array1, array2): # your code # if array1 or array2 have None values return False if array1 == None or array2 == None: return False if len(array1) == 0 or len(array2) == 0: return True # create empty list to capture the elems #create empty dictionary to track th...
def sum_pairs(arr,k): # check the length of the arr is > 2 if len(arr) < 2: return 'invalid input' # create sets for tracking seen = set() output = set() for elems in arr: target = k - elems if target not in seen: seen.add(elems) else: output.add( (min(elems, target), (max(elems, target)))...
#### ## Edited by Ryan McArdle Nov. 2020 ## ## Give original credit #### import math from collections import namedtuple def struct(name, members): cls = namedtuple(name, members) cls.__repr__ = lambda self: "%s(%s)" % (name, ','.join(str(s) for s in self)) return cls class vec2(struct('vec2', ('x', 'y...
#Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.Note that after backspacing an empty text, the text will continue empty. def strings(inp1,inp2): s1=[] s2=[] f1=True f2=True for i in inp1: if i == '#' a...
# -*- coding: utf-8 -*- """ Created on Tue Jan 14 10:49:23 2020 Refrescando mis skills de programador. Voy a hacer un juego de poker sencillo para refrescar mi memoria @author: JFEMENIAFERRER """ import random class Card(): RANK = (2,3,4,5,6,7,8,9,10,11,12,13,14) SUITS = ('D','S','C','H') ...
#Write a python program to find and display the number of circular primes less than the given limit. #There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. def check_prime(number): #remove pass and write your logic here. if the number is prime return true, else return fals...
"""Describes the items in the game.""" class Item: """The base class for all items""" def __init__(self, name, description, value, canPick): self.name = name self.description = description self.value = value self.canPick = False def __str__(self): return "{}\n====...
""" Search a 2D Matrix II Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. """ class Solution: d...
""" Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? """ class solution: def missingNumber(self, nums): c...
#importing modules from collections import deque # Definition for a Node. class TreeNode: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution: def levelOrder(self, root: 'TreeNode'): if root == None: return [] result =...
from tkinter import * from tkinter.scrolledtext import ScrolledText import tkinter.filedialog import tkinter.messagebox import tkinter.simpledialog root=Tk() root.title("My NotePad") text=Text(root) file='' text='' root.initialfile=("myfile.txt") root.configure(width=90,height=80) textPad=ScrolledText(root,width=200,...
import numpy as np import matplotlib.pyplot as plt from optimizer import Optimizer def f(x): return np.square(x) / 10 - 2 * np.sin(x) def main(): x_0 = -13 a = 0.1 opt = Optimizer.get_optimizer('rms_prop') x = opt.run(x_0, f, a) x_f = x[-1] plt.plot(np.linspace(-20, 20, 200), f(np.lin...
#### Reverse words in a given string def reverseString(str): if(len(str) == 0): return newString = "" for index in reversed(range(0,len(str))): newString = newString + str[index] print(newString) str = "i love you" reverseString(str)
### Longest Increasing Subsequence | DP-3 def findLongestIncreasing(list): if(len(list) == 0): return list1 = [1]*len(list) for index in range(1,len(list)): for index1 in range(0,index): if(list[index1] < list[index]): list1[index] = max(list1[index1]+1,list1[index])...
### Sort a linked list of 0s, 1s and 2s class Node(object): def __init__(self,data): self.data = data self.next = None def printList(root): while(root!= None): print("element is :{}".format(root.data)) root = root.next def sortList(root): count0 = 0 count1 = 0 c...
class Guests: def __init__(self, name, location, status): self.name = name self.location = location self.status = status class Human(Guests): def get_person(self): return f'''{self.name}, {self.location}, stile IN life "{self.status}"''' Vol1 = Human('Джони пуля в...
# https://leetcode.com/problems/majority-element/ # using Moore Voting Algorithm class Solution: def majorityElement(self, nums: List[int]) -> int: cnt=0 ele=-1 n=len(nums) for i in range(n): if cnt==0: ele=nums[i] if nums[i]==ele: ...
#https://practice.geeksforgeeks.org/problems/inversion-of-array/0 def merge(x,y): ans=0 arr=[] i=j=0 n1=len(x) n2=len(y) while i<n1 and j<n2: if x[i]<=y[j]: arr.append(x[i]) i+=1 else: ans+=n1-i arr.append(y[j]) j+=1 ...
from math import floor #importing the function floor() file=open('mass_github.txt', 'r') #Inputting mass from text file (mass.txt) sum=0 #setting sum to null def fuel_total(mass): fuel=floor(mass/3)-2 if fuel <= 0: return 0...
#!/usr/bin/python """ mat2hist.py - script that reads a .csv file filled with grades, gpas, and exams scores and creates two dictionary datastructures, one for indexing via a student's dummieid and one for indexing via a course name. Once created, the dictionaries are stored in ...
import unittest from barrenLandAnalysis import Farm class BarrenLandAnalysis_Test(unittest.TestCase): """ Unitesting of Barren Land Analysis module and find_area_of_fertile_lands function Args: param1: (int) Height of the farm param2: (int) Width of the farm param3: (se...
import numpy as np from sklearn import datasets X = np.arange(1, 101).reshape(20, 5) a = X[:,0] b = X[9] c = X[2:4].reshape(5,2) # print(X) # print(a) # print(b) # print(c) # print(f"Shape of X: {X.shape}") # print(f"Shape of a: {a.shape}") # print(f"Shape of b: {b.shape}") # print(f"Shape of c: {c.shape}") print(d...
def calc(s): nums=[] st=s.split("+") #print(st) for i in range(len(st)): nums.append(st[i].split("*")) #print(nums) count=0 for i in range(len(nums)): lon=len(nums[i]) if lon >= 2: for j in range(lon-1): if j==0: a=int(nums[i][j]) * int(nums[i][j+1]) ...
#!/usr/bin/env python ########################################################################### ## ## The class to handle P3D simulation data in python. An object is created ## that has the run parameters attached with it. The basic usage of the ## class can be done in the following ways. ## ## Example 1: ## > fro...
from tkinter import * root = Tk() root.title("File system project") root.geometry("200x250") lbl = Label(root, text="A list of favourite countries...") lbl.pack() listbox = Listbox(root) listbox.insert(1, "India") listbox.insert(2, "USA") listbox.insert(3, "Japan") listbox.insert(4, "Austrelia") listbox.pack() def ...
x1= float(input('Digite o tamanho do altura da parede ')) x2= float(input('Digite o tamanho da largura da parede ')) a = x1 * x2 quan= a/2 print('O valor da área é {} e a quantidade de tinta para pintá-la é {}.'.format(a,quan))
dia = input('dia que vc nasceu ' ) mês = input('mês em que vc nasceu ' ) ano = input('ano em que você nasceu ' ) print ('Você nasceu no dia', dia, 'do mês de',mês,'do ano de' , ano)
""" Parent class for exportable objects. Author: L. Lamm (lamm@ifam.rwth-aachen.de) """ import json class Exportable(object): """Parent class for .json exportable objects""" def __init__(self): """Empty constructor""" pass def data2dict(self, export_list=[]): """Store attributes ...
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Perceptron class MyPerceptron: def __init__(self): self.w = None self.b = 0 self.l_rate = 1 # xuexilv def fit(self, x_train, y_train): # shape[1] 为第一维的长度,.shape[0] 为第二维的长度 self.w = np....
my_name="Elsa" my_age=18 my_title="queen" print"hello i am %s and i am the %s"%(my_name,my_title)#if use %s then just output the data,if use %r,then the print will be in' ' print"i am %d years old"%my_age #can't use indent again #1="elsa" #print 1 pi=3.14 earth_circum=2*pi*6873 print"the circumferrence of the earth...
cats=30 dogs=30 if cats<dogs: print"more dogs than cats" elif dogs<cats: print"more cats than dogs" else: print"same number of cats and dogs"
s = input() ban = "aiueo" for i in range(len(s)): if s[i] not in ban: print(s[i], end = "") print()
from collections import defaultdict n = int(input()) dic = defaultdict(int) for i in range(n): dic[int(input())] += 1 print(len(dic))
s = input() choku = "choku" for i in range(len(s)): if s[i] not in choku: print("NO") exit() if s[i] == "c": if s[i + 1] != "h": print("NO") exit() elif s[i] == "h": if s[i - 1] != "c": print("NO") exit() print("YES")
nums = list(int(input()) for _ in range(3)) data = sorted(nums) for i in range(3): print(3 - data.index(nums[i]))
from collections import defaultdict s = input() dic = defaultdict(int) str = "ABCDEF" for i in range(len(s)): dic[s[i]] += 1 for i in range(len(str)): if i != len(str) - 1: print(dic[str[i]], end = " ") else: print(dic[str[i]])
import math a, b, x = map(int, input().split()) if x <= a ** 2 * b / 2: bottom = (x * 2 / (a * b)) hype = math.sqrt(bottom ** 2 + b ** 2) print(math.degrees(math.atan2(b, bottom))) else: x = a ** 2 * b - x height = x * 2 / (a ** 2) print(math.degrees(math.atan2(height, a)))
n = int(input()) print("YES" if n % 3 == 0 or "3" in str(n) else "NO")
from math import sqrt n = int(input()) for i in range(n, 0, -1): if int(sqrt(n)) ** 2 == i: print(i) exit()
import numpy as np from mypackage.min_degree import annihilate_min_deg_poly #This example demonstrates the utility of the method matrix = [[0,1],[1,0]] print("Matrix:") print(np.array(matrix)) a = annihilate_min_deg_poly(matrix) print("Min degree polynomial:") print(a) print() matrix = [[0,1,0],[1,0,0],[0,0,1]] print...
''' CNN MNIST digits classification Project: https://github.com/roatienza/dl-keras Dependencies: keras Usage: python3 <this file> ''' # numpy import numpy as np from keras.models import Sequential from keras.layers import Activation, Dense, Dropout from keras.layers import Conv2D, MaxPooling2D, Flatten from keras.da...
class Dog: """ This is the class for Dog """ def __init__(self, name): self.name = name def add_weight(self, weight): self.weight = weight def compare(x, c): if False: print("yes") else: print("no") return x.weight > c.weight ...
def EMAIL_ADDRESS_SLICER(): """ Displays the username and domain name of an email address : return: None """ # get user's email address emailAddress = input('Enter your email address: ').strip() try: # make a list with the email address split_address = emailAddress.split('@')...
if __name__ == '__main__': for _ in range(int(input())): num = int(input()) occurr = 2 ** (num - 1) sum1 = num * (num + 1) // 2 print(sum1*occurr)
# array is always sorted # first value will always be 0 # linear def smallest_missing(arr): # loop through the array using their indices for i in range(len(arr)): # check that each element matches its index if arr[i] != i: # if it doesn't match, return i (because it's the smallest ...
#リンゴの値段100円,リンゴの個数2個,消費税10%で単純なレイヤーを計算してみる class MulLayer(object): def __init__(self): self.x = None self.y = None def forward(self,x,y): self.x = x self.y = y out = x*y return out def backward(self,dout): dx = dout*self.y dy = dout...