text
stringlengths
37
1.41M
from typing import Dict memo:Dict[int, int] = {0: 0, 1: 1} def fib(n: int) -> int: if n not in memo: return fib(n - 1) + fib(n - 2) return memo[n] if __name__ == "__main__": print(fib(5)) print(fib(10)) print(fib(20)) print(fib(30)) print(fib(40)) print(fib(45)) print(fib(50...
''' CONSIDERANDO DUAS LISTAS DE INTEIROS OU FLOATS (LISTA A E LISTA B), SOME OS VALORES NAS LISTAS RETORNANDO UMA NOVA LISTA COM OS VALORES SOMADOS. SE UMA LISTA FOR MAIOR QUE A OUTRA, A SOMA SÓ VAI CONSIDERAR O TAMANHO DA MENOR. EXEMPLO: LISTA_A = [1,2,3,4,5,6,7] LISTA_B = [1,2,3,4] ----------- RESULTADO = [2,4,6,8] ...
class Variable: def __init__(self,nombre = "",valores = None): self.nombre = nombre self.valores = valores self.cond = False self.proba = [] def get_nombre(self): return self.nombre def set_nombre(self,nombre): self.nombre = nombre def get_valo...
# -*- coding: utf-8 -*- """ Created on Fri Jan 18 22:42:30 2019 @author: raushan kumar """ #Scatter Plot import matplotlib.pyplot as plt x=[] m=int(input("Enter range : ")) print('Enter elements for X-axis:') for i in range(m): x.append(eval(input())) y=[] print("Enter elements for Y-axis: ") for j in range(m):...
import random import time def player(): '''Here the player can read the rules of the game and select one of the "moves" for playing ''' # While loop for keeping here until the player select a correct move while True: player_choice = input(''' ************************************** Select your c...
# program to find the house of a given hogwarts student from sys import argv from sys import exit from cs50 import SQL if len(argv) != 2: print("Oops wrong number of arguments") exit(1) # initialize the database db = SQL("sqlite:///students.db") # program takes input the house house = argv[1].lower().capita...
import ObjetoPedido import os clear = lambda: os.system('cls') lista = ObjetoPedido.listaP #sair da def lista() #input incorreto simples #loop lista class Gerente: def Main(): clear() print("#######PERFIL GERENCIAL#######") print("1-Verificar/Modificar solicitações") ...
def fizz_buzz(num): if ( num % 3 ==0 and num % 5 == 0): return "FizzBuzz" if( num % 3 ==0 ): return "Fizz" if( num % 5 == 0): return "Buzz" return num
#using recurssion to solve the same factorial problem def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) print(factorial(6))
frase = 'Curso em video Python' print(frase) print(frase[3]) # a resposta será s print(frase[3:13]) print(frase[:13]) # do inicio até a posição 12 serão mostradas print(frase[13:]) # do 13 ate o final print(frase[1:13]) print(frase[1:13:2]) # pulando de 2 em 2 print(frase.count('o')) # aqui o programa considera ma...
import math # EX: 45° × π/180 = 0,7854rad n1 = float(input("Digite um angulo: ")) angulo = math.radians(n1) seno = math.sin(angulo) cosseno = math.cos(angulo) tangente = math.tan(angulo) print("Seno de {:.0f}°Graus é {:.4f}" .format(n1, seno)) print('Cosseno de {:.0f}°Graus é {:.4f}'. format(n1, cosseno)) print('Tange...
while True: tabuada = int(input('Qual o valor da tabuada: ')) if tabuada < 0: break print('+' * 15) for c in range(0, 10): c += 1 print(f'{tabuada} x {c} = {tabuada * c}') print('+' * 15) print('ACABOU')
from random import randint maiorvalor = menorvalor = 0 tupla = (randint(0 , 10), randint(0 , 10) , randint(0 , 10) , randint(0 , 10) , randint(0 , 10)) print(f' Os numeros sorteados foram: {tupla}') for c in range (0 , 5): for a in range (0,5): if c == a == 0: maiorvalor = tupla[0] m...
sexo = str(input('Informe seu sexo: ')).upper() if sexo in "FM": print('Sexo registrado, obrigado! ') else: while sexo not in 'FM': rs = str(input('Resposta errada, digite noevamente: ')).upper() sexo = rs print('Registrado com sucesso')
lt = [[], []] for c in range(0, 7): n = int(input(f'Digite o {c}º valor: ')) if n % 2 == 0: lt[0].append(n) else: lt[1].append(n) lt[0].sort() lt[1].sort() print(f'Os valores pares digitados foram {lt[0]}') print(f'Os valores impares foram {lt[1]}')
casa = float(input('Qual o valor da casa R$: ')) sal = float(input('Qual o valor de seu salario R$: ')) ano = int(input('Em quantos anos você deseja pagar: ')) pmensal = casa / (ano * 12) if pmensal >= (sal * 30 / 100): print('\033[031m Emprestimo negado - passou o limite maximo de 30% do salario \033[m', end='') ...
c = s = 0 while True: n = int(input('Digite um numero [999 sai do progrma]')) if n == 999: break c += 1 s += n print(f'Você digitou {c} e total é {s}')
n1 = int(input('Digite um numero ')) n2 = int(input('Digite o segundo numero: ')) n3 = int(input('Digite o terceiro numero: ')) if n1 > n2 > n3: print('{} é o maior numero1'.format(n1)) print('{} é o menor numero'.format(n3)) if n1 < n2 < n3: print('{} é o maior numero2'.format(n3)) print('{} é o menor ...
sexo = str(input('Sexo: ')).strip().upper()[0] while sexo not in 'FM': sexo = str(input('Errado, digite novamente: ')).upper()[0] print('Registrado')
def inverse_captcha(string): s = 0 for idx in range(1, len(string)): # print(string[idx], string[idx-1]) if string[idx] == string[idx - 1]: s += int(string[idx]) if string[-1] == string[0]: s += int(string[0]) return s if __name__ == '__main__': with open(...
class point(): x = 0 y = 0 point1 = point() point2 = point() point1.x = 1 point1.y = 2 point2.x = 3 point2.y = 4 import math def distance_between_points(point1, point2): distance = math.sqrt((point2.x - point1.x) **2 + (point2.y - point1.y)**2) return distance print (distance_be...
#配列を用いたピッチングシミュレーション #3*3行列をステータスとする import numpy as np import sys def pitch(p, bat): #バッターの数値とピッチャーの入力数値が一致したら1,しなければ0の配列を返す pitch = np.where( bat == p, 1, 0) #print(pitch) #pitch配列の中で1を持つ要素数を求める jdg = len(pitch[pitch == 1]) return jdg #バッターの数値、整数値で1から9までの3*3行列 bat = np.random.randint(1, 10, (3, 3...
def Quick_sort(arr,st,fi): if fi <= st : return c = Find_c(arr,st,fi) print(arr,st,c) Quick_sort(arr,st,c-1) Quick_sort(arr,c+1,fi) def Find_c(arr,st,fi): j = st #设置游标 for i in range(st,fi+1): if arr[i] <= arr[fi]: temp = arr[j] arr[j] = arr[i] arr[i] =temp j += 1 i += 1 retu...
import numpy as np import graphs as gp import pdb class maxHeap(object): """docstring for maxHeap""" def __init__(self): super(maxHeap, self).__init__() #names of vertices self.H = [-1] #vertex values self.D = [-1] self.n = 0 def Maximum(self): #retu...
#!/usr/bin/env python #--coding: utf8-- def jiami(num): new_num = '' for item in num: item = int(item) new_item = (item+5) % 10 new_num += str(new_item) print new_num[::-1] if __name__ == '__main__': num = raw_input('请输入一个四位数:') jiami(num)
#!/usr/bin/env python3 #--*--coding: utf8--*-- from functools import partial def add(x, y, z): return x + y +z myadd = partial(add, x=10, y=20) if __name__ == '__main__': print(add(10, 20, 34)) print(add(10, 20, 19)) print(myadd(z=10))
#!/usr/bin/env python #--coding: utf8-- def str_sort(n=3): a_list = [] for i in range(n): strings = raw_input('请输入字符串:') a_list.append(strings) print '初始顺序是%s' % a_list a_list.sort() print '排序后的顺序是%s' % a_list if __name__ == '__main__': str_sort()
#!/usr/bin/env python #--coding: utf8-- b=input('input a number:\n') a=9 n=1 while (1): if a%b==0: break else: a=a*10+9 n=n+1 print '%d 个 9 除于 %d 为整数' % (n,b)
#!/usr/bin/env python3 #--*--coding: utf8--*-- import os def get_fname(): while True: filename = input("请输入文件名:") if os.path.exists(filename): print('文件以存在') else: break return filename def get_contents(): contents = [] while True: content = inp...
#!/usr/bin/env python #--coding: utf8-- def reverse_list(n=3): a = [] for i in range(n): counter = int(raw_input('请输入一个数:')) a.append(counter) print a for i in range(len(a)): if a[i] == max(a): a[0], a[i] = a[i], a[0] for i in range(len(a)): if a[i] == min...
#!/usr/bin/env python #--coding: utf8-- def count(x=1, y=2): sum = 0 for i in range(1, y+1): num = int(str(x) * i) if i == y: print num else: print num , '+', sum += num print '结果是:', sum if __name__ == '__main__': count() count(5,5)
#!/usr/bin/env python3 #--*--coding: utf8--*-- def set_age(name, age): if not 0 < age < 150: raise ValueError('age out of range') #触发 print('%s is %d years old' % (name, age)) def set_age2(name, age): assert 0 < age < 150, 'age out of range' #断言 print('%s is %d years old'...
#!/usr/bin/env python #--coding: utf8-- from random import randint def bl(n=5): a = [] for i in range(n): a.append(randint(1,100)) print a for item in a: print item, print for i in range(len(a)): print a[i], if __name__ == '__main__': bl()
#!/usr/bin/env python #--coding: utf8-- def count(func): def times(**kwargs): return func(**kwargs) * 3 return times @count def fm(name, age): return 'My name is %s and I am %s years old\n' % (name, age) if __name__ == '__main__': dic = {'name':'tom', 'age':25} print fm(**dic)
#!/usr/bin/env python3 #--*--coding: utf8--*-- fiber = [0, 1] for i in range(2,10): new_num = fiber[i-2] + fiber[i-1] fiber.append(new_num) print(fiber)
#!/usr/bin/env python #--coding: utf8-- from random import randint def make_matrix(num=3): matrix = [] for i in range(num): items = [] for j in range(num): item = randint(1, 100) items.append(item) matrix.append(items) return matrix def count(matrix): s...
#!/usr/bin/env python #--coding: utf8-- #采用递归函数 def age(n=5): if n == 1: c = 10 else: c = age(n-1) +2 return c if __name__ == '__main__': print age()
#!/usr/bin/env python3 #--*--coding: utf8--*-- class MyClass(): count = 0 def __init__(self): self.a = 10 MyClass.count += 1 if __name__ == '__main__': print(MyClass.count) mc1 = MyClass() print(MyClass.count) print(MyClass.__dict__) print(mc1.__dict__)
#!/usr/bin/env python #--coding: utf8-- #递归函数 def f1(num): if num == 1: return num return num * f1(num - 1) if __name__ == '__main__': print f1(5) print f1(6)
#!/usr/bin/env python #--coding: utf8-- from random import randint from collections import deque import sys def move(n=5,m=2): if m >= n: print '数据采用有错误' sys.exit() a_list = [] for i in range(n): num = randint(1,100) a_list.append(num) print a_list f = deque(a_list...
#!/usr/bin/env python3 # -*-coding: utf8-*- def get_formatted_name(first_name, last_name, middle_name=''): full_name = first_name + ' ' + middle_name + ' ' + last_name return full_name.title() musician = get_formatted_name(first_name='li', middle_name='ji', last_name='ying') print(musician) musician = get_fo...
#!/usr/bin/env python3 # -*-coding: utf8-*- def make_pizza(size, *toppings): print('\nMake a ' + str(size) + '-inch pizza with the following toppings:') for topping in toppings: print('-' + topping)
#!/usr/bin/env python3 # -*-coding: utf8-*- aliens = [] for alien_number in range(30): new_alien = {'color':'green', 'points':5, 'speed':'slow'} aliens.append(new_alien) for alien in aliens[:3]: if alien['color'] == 'green': alien['color'] = 'yellow' alien['points'] = 10 alien['speed...
#!/usr/bin/env python3 # -*-coding: utf8-*- file = open('tt.txt', 'a') while True: contect = input('请输入:') if contect == 'q': file.close() exit() else: file.write(contect + '\n')
#!/usr/bin/env python #--coding: utf8-- def count(start=0): counter = [start] #作用于流浪作用域,定义为可变变量 def incr(): counter[0] += 1 return counter[0] return incr if __name__ == '__main__': a = count() b = count(10) print a() print a() print b() print b() print ...
#!/usr/bin/env python #--coding: utf8-- a = 077 b = a ^ 3 print 'the a ^ 3 = %d' % b b ^= 7 print 'the a ^ b = %d' % b
#!/usr/bin/env python3 # -*-coding: utf8-*- print('give me two numbers, and i will devide them') print('enter "q" to quit this program') while True: first_number = input('first number: ') if first_number == 'q': break second_number = input('second number: ') try: answer = int(first_numb...
#!/usr/bin/env python3 # -*-coding: utf8-*- import json user_name = input('Please enter your name: ') filename = 'username.json' with open(filename, 'w') as fileobjcet: json.dump(user_name, fileobjcet) print('we will remember you when you come back' + user_name + '!')
#!/usr/bin/env python #--coding: utf8-- def count(): cnt = 0 for i in range(1,5): for j in range(1,5): for k in range(1,5): if i != j and j != k and k != i: print i * 100 + j * 10 + k cnt += 1 print '可以组成的三位数一共有%s个' % cnt if __name...
#!/usr/bin/env python3 #--*--coding: utf8--*-- import os import pickle as p import time def save_money(wallet_file, record_file): amount = int(input('amount: ')) comment = input('comount: ') date = time.strftime('%Y-%m-%d') with open(wallet_file) as fobj: balance = p.load(fobj) + a...
#!/usr/bin/env python3 # -*-coding: utf8-*- def make_pizza(*toppings): print('\nMaking a pizza with the following toppings:') for topping in toppings: print('-' + topping) make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese')
#!/usr/bin/env python #--coding: utf8-- def count(strings): return len(strings) if __name__ == '__main__': strings = raw_input('请输入字符串:') print count(strings)
#!/usr/bin/env python3 # -*-coding: utf8-*- name = input('Please enter youe name: ') print('Hello, '+ name + '!') prompt = "If you tell us who you are , we can personalize the message you see." prompt += '\nWhat is your name? ' name = input(prompt) print('\nHello, ' + name + '!')
#!/usr/bin/env python3 #--*--coding: utf8--*-- alist = ['hello', 'nihao', 'hi'] for index in range(len(alist)): print('%s: %s' %(index, alist[index])) for ind, val in enumerate(alist): print('%s: %s' % (ind, val)) print(list(reversed(alist)))
#!/usr/bin/env python3 # -*-coding: utf8-*- def count_words(file_name): try: with open(file_name) as file_object: contects = file_object.read() except FileNotFoundError: print(file_name + ' this file is not exist') else: words = contects.split() num_words = len(wo...
class User(object): def __init__(self, number): self.__number = number self.__number_2 = 0 def set_number(self, number): self.__number = number def get_number(self): return self.__number def set_number_2(self, number2): self.__number2 = number2 ...
#!/usr/bin/env python3 #--*--coding: utf8--*-- import tkinter from functools import partial # def hello(): # lb1.config(text='hello tedu') # # def welcome(): # lb1.config(text='hello tarena') def say_hi(word): def hi(): lb1.config(text='hello %s' % word) return hi root = tkinter.Tk() lb1 = tk...
#!/usr/bin/env python #--coding: utf8-- from random import randint def q_sort(num_list): if len(num_list) == 0 or len(num_list) == 1: return num_list middle = num_list.pop() smaller = [] larger = [] for num in num_list: if num < middle: smaller.append(num) else:...
#!/usr/bin/env python #--coding: utf8-- from random import randint def link_list(n=5): link_list = [] for i in range(n): link_list.append(randint(1,100)) return link_list def back_link_list(link_list): link_list.reverse() return link_list if __name__ == '__main__': ll = link_list() ...
#!/usr/bin/env python3 # -*-coding: utf8-*- from collections import OrderedDict favorate_languages = OrderedDict() favorate_languages['jen'] = "python" favorate_languages['kenji'] = "c" favorate_languages['natasha'] = "php" favorate_languages["chihiro"] = "java" for name, language in favorate_languages.items(): ...
#!/usr/bin/env python #--coding: utf8-- #深拷贝和浅拷贝 import copy a_list = [1, 2, 3] b_list = ['a', 'b', a_list] c_list = copy.copy(b_list) d_list = copy.deepcopy(b_list) print '浅拷贝是%s: ' % c_list print '深拷贝是%s: ' % d_list a_list[0] = 4 print a_list print '更新后浅拷贝是%s: ' % c_list print '更新后深拷贝是%s: ' % d_list
#!/usr/bin/env python3 import sys from datetime import datetime from datetime import timedelta # date = input('请输入启始日期(格式为YYYY-MM-DD):') def count_date(date,days): #print(date) date_list = date.split('-') year = int(date_list[0]) month = int(date_list[1]) day = int(date_list[2]) if year not ...
#!/usr/bin/env python #--coding: utf8-- import re def count_patt(fname, patt): result = {} cpatt = re.compile(patt) with open(fname) as fobj: for line in fobj: m = cpatt.search(line) if m: key = m.group() result[key] = result.get(key, 0) + 1 ...
#!/usr/bin/env python3 # -*-coding: utf8-*- # -*- coding: utf8 -*- import os def get_fname(): #得到文件名 while True: fname = input("filename: ") if not os.path.exists(fname): break print ('%s already exists. Try another.' % fname) return fname def get_content(): #得到内容 ...
''' Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [ ['A','B',...
''' Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. ''' class Solution(object): def maxProfit(self, prices): """ ...
''' Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. For example: Given the below binary tree, 1 / \ 2 3 Re...
''' segment tree ''' class SegNode(object): def __init__(self, l, r): self.left = l self.right = r self.cover = 0 self.leftchild = None self.rightchild = None class SegTree(object): def __init__(self, s, e): self.start = s self.end = e self.root = self.build(s, e) def build(self, ...
''' Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will be positive integers. Elements in a combination (a1, a2,... , ak...
''' Wildcard Matching My Submissions Question Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function prototype should be: ...
''' Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Range Sum Query 2D The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8. Example...
''' Largest Rectangle in Histogram Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. The largest rectangle is shown in the shaded...
#!/usr/bin/python -tt # -*- coding: latin-1 -*- import sys import re #WHAT DOES THIS PROGRAM DO? It receives a plain text, in the .txt extension, and returns a .html file (with the same name as the .txt file), #created and saved in the same directory in which the .txt file and the .py script are stored. #N.B.: ALL ...
""" Here's a not very efficient calculation function that calculates something important: import time import struct import random import hashlib def slow_calculate(value): "Some weird voodoo magic calculations" time.sleep(random.randint(1,3)) data = hashlib.md5(str(value).encode()).digest() ...
from homework6.task01.decorator_for_class import instances_counter @instances_counter class Example: instance = 25 def __init__(self, arg): self.instance = arg def test_Example_without_creating_instance_object(): assert Example.get_created_instances() == 0 def test_method_get_c...
""" Given a dictionary (tree), that can contains multiple nested structures. Write a function, that takes element and finds the number of occurrences of this element in the tree. Tree can only contains basic structures like: str, list, tuple, dict, set, int, bool """ from collections.abc import Collection, M...
#!/usr/bin/env python # # extract a subset of fasta sequences by tags import sys from sys import argv if len(argv) != 3: print 'Usage: %s <sequence_file> <tag_file>'%argv[0] print 'extract a subset of sequeces from sequence_file as defined in tag_file' sys.exit(-1) tags = open(argv[2]).read().split('\n')...
#%% import numpy as np import pylab as pl from matplotlib import collections as mc import random import matplotlib.pyplot as plt print() print(' ELECTRONIC ARTS SPORTS ') for i in range(20): n=1 for i in range(1,25000): n=n*i n=1 print(' ...
import time print('Welcome to Mad Libs Theatre') k=input('Enter your genre from these options:a.Weird or b.Funny Crime: ') if k=='a': a=input('Are You Ready(y/n):') while a!='n': adjective1=input('Enter an adjective:') adjective2=input('Enter an adjective:') adjective3=input('Ent...
names = ['Andy','Eve','Sally'] print(list(map(lambda x:x[::-1],names)))
def old_macdonald(name): first_half = name[:3] second_half = name[3:] return first_half.capitalize() + second_half.capitalize() print(old_macdonald('fyiluhuoffui'))
# 1. Handle the exception thrown by the code below by using try and except blocks. #for i in ['a','b','c']: # print (i*2) # implementation of try-catch block. #try: # for i in ['a','b','c']: # print i*2 #except: # print("Exception handling for try and catch block") #else: # print("is done!") # 2. Handle the exce...
def splicer(mystring): if len(mystring)%2 == 0: return 'EVEN' else: return mystring[0] #print(splicer('sdjldhkdgh')) names = ['Andy','Eve','Sally'] print(list(map(splicer,names)))
def summer_69(arr): sum = 0 add = True for value in arr: while add: if value != 6: sum += value break; else: add = False while not add: if value != 9: break else: add = True break return sum print (summer_69([2,5,7,6])) print (summer_69([2,4,4,5,6,9,7])) print (summer_69(...
x=0 while x<5: print (f'Current value of x is {x}') x = x + 1 else: print("x is not less than 5")
#Запросите у пользователя значения выручки и издержек фирмы. #Определите, с каким финансовым результатом работает фирма #(прибыль — выручка больше издержек, или #убыток — издержки больше выручки). #Выведите соответствующее сообщение. #Если фирма отработала с прибылью, #вычислите рентабельность выручки (соотношени...
from math import sqrt import numpy as np def simpsons_method(function, int_begin: float, int_end: float, n: int) -> float: if n < 1: print("N turi būti ne mažesnis už 1") return None x = np.linspace(int_begin, int_end, n+1) result_sum = 0.0 for i in range(1, n+1): result_sum...
a=input("enter the string you want to reverse them:") b=a[::-1] print(b)
n=int(input("Enter the value of N:")) a,b,sum,count=0,1,0,1 print("Fibonacci series:",end=" ") while(count<=n): print(sum,end=" ") count +=1 a=b b=sum sum=a+b
# Rapid Pygame # https://github.com/XrXr/RapidPygame # License: MIT from pygame.rect import Rect class Camera: """ Class for keeping track of the camera position. In early stage of development """ def __init__(self, screen_res, level_rect, x_speed=15, y_speed=15, left_threshold=10,...
cels: float; fahr: float escala = str(input("Voce vai digitar a temperatura em qual escala (C/F)? ")) if escala == 'F': fahr = float(input("Digite a temperatura em Fahrenheit: ")) cels = 5.0 / 9.0 * (fahr - 32.0) print(f"Temperatura equivalente em Celsius: {cels:.2f}") else: cels = float(input("Digite ...
valor: float; troco: float; dinheiro: float n: int valor = float(input("Digite o valor da mercadora: ")) n = int(input("Digite a quantidade do produto: ")) dinheiro = float(input("Digite o dinheiro entregue: ")) troco = dinheiro - (valor * n) print(f"O troco é de: {troco:.2f}") if (valor * n) > dinheiro: ...
n1: float; n2: float; media: float n1 = int(input("Digite a primeira nota: ")) if n1 < 0 or n1 > 10: print("Nota invalida. Digite novamente:") n1 = int(input("Digite a primeira nota: ")) n2 = int(input("Digite a segunda nota: ")) if n2 < 0 or n2 > 10: print("Nota invalida. Digite nova...
# Kütüphaneleri yükleyelim. from random import choice from numpy import array, dot, random # Step fonksiyonu kullanılır. unit_step = lambda x: 0 if x < 0 else 1 # Eğitim verisi(matris cinsinden) training_data = [ (array([0,0,1]), 0), (array([0,1,1]), 1), (array([1,0,1]), 1), (array([1,1,1]), 1), ] # rastgele 3 matris ...
num = int(input('入力>')) if num % 2 == 0: print('偶数') pass else: print('奇数') pass
word = {'バナナ':'banana', 'にんじん':'carrot'} word['リンゴ'] = 'apple' del word['にんじん'] word['さくらんぼ'] = 'cheryy' print(word)
############################################################################## ### To use the functions in this lib simply import this python module using ### import myUtils ### Then you'll able able to call functions with the proper arguments using ### returnVal=myUtils.func1(arg1,arg2) ###############################...
import serial # import the serial library import time # import the time library from Tkinter import * #import Tkinter GUI library def n1(): arduino.write('xn1') def n2(): arduino.write('xn2') def n3(): arduino.write('xn3') def n4(): arduino.write('xn4') def n5(): arduino.write('xn5') def t1(): arduino.write(...
#!/usr/bin/env python3 """ Script for plotting up the PCoAs of the distance plots and plotting up the line graphs that show how the mantel tests change in reaction to the line graphs. In general the order of these plots will be quite important as they are dependent on each other. Preceeding plots will define proceedin...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isequal(self,left,right): if left.val!=right.val: return False if (left.left==None)!=(right.right==None):...