text
stringlengths
37
1.41M
# Program to make bibtex file using the bibcodes of references in ADS ''' This program reads the bibliography codes one-by one from an input file "references" and download the bibtex entry from ADS and then put them in a "reference.bib" file in the alphabetical order of the authors' names. For the same authors, it wil...
class Node: def __init__(self,value): self.value=value self.nextNode=None n1=Node(5) n2=Node(6) n3=Node(7) n4=Node(8) n1.nextNode=n2 n2.nextNode=n3 n3.nextNode=n4 def traverse_with_two_pointers(left,right): if right is None: return left left=traverse_with_...
towers=[4,4,0,2,1,6] #recursive def min_jumps(towers,i,N): if i>=N: return 0 if towers[i]==0: return float('Inf') min=float('Inf') for j in range(1,towers[i]+1): if(i+j)<=N: jumps=min_jumps(towers,i+j,N) if (jumps<min and jumps!=...
# -*- coding: utf-8 -*- """ Created on Mon Feb 8 17:14:57 2021 @author: pc """ nombre=input('Ingrese su nombre: ') apellido=input('Ingrese su apellido: ') edad=input('ingrese su edad: ') lugar=input('ingrese el lugar donde vive: ') space=" " print( ) print('bienvenid@'+space+nombre+space+apellido+ ...
import sys import os nombre=input("Hola, cual es tu nombre?: ") print("hola",nombre)
""" https://leetcode.com/contest/biweekly-contest-32/problems/find-longest-awesome-substring/ """ class ACSolution: """O(n) time. O(1024) space. 1752ms.""" def longestAwesome(self, s: str) -> int: res, cur, n = 0, 0, len(s) seen = {0:-1} for i, c in enumerate(s): cur ^= 1 <...
""" https://leetcode.com/contest/weekly-contest-201/problems/find-kth-bit-in-nth-binary-string/ """ class Solution: """Brute force. AC'd.""" def findKthBit(self, n: int, k: int) -> str: t = "011100110110001" if n <= 4: return t[k-1] for _ in range(n-4): t = t + ...
################################################# # 15-112-n18 hw9 # Your Name:Eric Chen # Your Andrew ID:tianyich # Your Section:B ################################################# """ def slow1(lst): # N is the length of the list lst assert(len(lst) >= 2) O(1) a = lst.pop() ...
import math class Position: def __init__(self, x, y): self.x = x self.y = y def getCardinal(c,d): a = c b = d theta = math.asin((b.y-a.y)/math.sqrt((b.y-a.y)**2+(b.x-a.x)**2)) if(b.x-a.x < 0): theta = math.pi-theta cardinals = ['n', 'w', 's', 'e'] return cardinal...
""" Problem: Imagine robot sitting on top left position on a grid. Move it all the way to bottom right position. You can only move right and down. Approach: Think about using top-down approach logic. How many ways can you get to last position (nth). Obviously, there's two ways. To get to position grid[row][col], you e...
import unittest from contextlib import contextmanager """ def answerReturn(): ans = input('enter yes or no') if ans == 'yes': return 'you entered yes' if ans == 'no': return 'you entered no' """ @contextmanager def mockRawInput(mock): original_input = __builtins__.input __builtins_...
import copy class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if self.head == None: self.head = new_node else: ...
class Queue: def __init__(self): self.queue = [] def insert(self, val): self.queue.append(val) def get_value(self): return self.queue.pop(0) new_queue = Queue() new_queue.insert(30) new_queue.insert(40) new_queue.insert(50) new_queue.insert(60) new_queue.insert(70) print(new_...
def reverse_built_in(string): arr = [char for char in string] arr.reverse() return ''.join(arr) def reverse_built_in_two(string): return string[::-1] def reverse_iterative(string): arr = [char for char in string] a = 0 b = len(string)-1 while a < len(string)/2: holder = arr[a...
class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.top = None self.count = 0 self.min = 0 def __str__(self): temp = self.top output = [] while temp: output.append(str(...
def is_palindrome(a): return a == ''.join(reversed([char for char in a])) def is_palindrome_two(a): beg = 0 end = len(a)-1 while(beg < end): if a[beg] != a[end]: return False beg += 1 end -= 1 return True print(is_palindrome_two('deeeed'))
''' Classes / objetos Python * Python é uma linguagem de programação orientada a objetos. A Programação Orientada a Objetos (POO) é um paradigma de programação baseado no conceito de Classes e Objetos. Classes podem conter dados e código: * Dados na forma de campos (também chamamos de atributos ou propriedades); e Có...
'''' Função Input * O input()função permite a entrada do usuário. * Use o parâmetro prompt para escrever uma mensagem antes da entrada: Função Int * O int()função converte o especificado valor em um número inteiro * Converte uma string em valor inteiro ''' print('Função Input') print('Enter your name:') x = inp...
'''Separando Strings''' frase = "Olá, bem-vindo ao Treinamento Mestre da automação" print(frase.split()) print(frase.split(",")) print(frase.split("-")) nomes = "Tarcisio, Lucca, Carol, Raquel, Daniel" print(nomes.split()) print(nomes.split(",")) hashtags = "music #guitar #gamaer #coder #python" print(hashtags.split()...
''' Python RegEx * Um RegEx, ou Expressão Regular, é uma sequência de caracteres que forma um padrão de pesquisa. * RegEx pode ser usado para verificar se uma string contém o padrão de pesquisa especificado. Módulo RegEx * Python tem um pacote embutido chamado re, que pode ser usado para trabalhar com Expressões reg...
import math import random class createLevel: def __init__(self, word): self.gameDetails(word) self.visiblilty = [False for _ in range(self.length)] for i in range(self.visibleLetter): self.visiblilty[random.randint(0,self.length-1)] = True for i in range(self.length): ...
#creating class class Solution: #defining function with input haystack and needle def strStr(haystack, needle): len1=len(haystack) print ('len1 : ' , len1)#get lenght of haystack len2=len(needle) print ('len2 : ' , len2) # get lenght of needle if len1<len2: # if...
file = open("books.txt", "r") #your code goes here book_list = file.readlines() for book in book_list: if book[-1] == '\n': print("{0}{1}".format(book[0], len(book) - 1)) else: print("{0}{1}".format(book[0], len(book))) file.close()
# -*- coding: utf-8 -*- """ Created on Thu Mar 11 18:43:06 2021 @author: Aman gupta """ class Node: def __init__(self, data): self.data = data self.next = None class linkedlist: def __init__(self): self.head = None def insert(self, data): if self.head is None: ...
""" File contains the KPC class """ import GPIOSimulator_v5 as GPIOSimulator from fsm import FSM from keypad import Keypad from led_board import LED_board class KPC: """ The Keypad controller coordinates the Keypad, the FSM and the GPIO-Simulator. It is the main class of the project. In the assign...
def multiply(*args): product = 1 for num in args: product *= num return product def addition(*args): sum = 0 for num in args: sum += num return sum print(multiply(3,5,9,7))
palabras=raw_input("Ingrese La Palabra ") mayuscula=("ABCDEFGHIJKLMNOPQRSTUVWXYZ") cont = 0 for i in palabras: if i in mayuscula: cont = cont+1 print "La cadena tiene", cont, "mayuscula/s"
Num1 = input("Ingrese El Numero 1 = ") Num2 = input("Ingrese El Numero 2 = ") if Num1 % 2 == 0: print "el primer numero par" else: print "El primer numero No es Par" if Num2 % 2 == 0: print "El segundo numero es par" else: print "El segundo numero No es Par"
import random list_holder = [0,1,2,3] list_holder.append("new stuff") print(list_holder[4]) for x in list_holder: print() names = ["hello", "world"] print(names) names.append("stuff") print(names) for x in names: print("name") # 1. list_holder1 = [0,1,2,3,4] print(list_holder1) # 2. list_holder2 = ...
from time import sleep import random from datetime import datetime import itertools as it def producer(): 'produce timestamps' starttime = datetime.now() while True: sleep(random.uniform(0, 0.2)) yield datetime.now() - starttime def tracker(p,limit): ''' Track the...
def fibonacci(n): ''' Return the number of fibonacci sequence ''' assert isinstance(n,int) assert n>=1 a=1 b=1 num=0 while num<n: yield a a,b=b,a+b num=num+1
''' Encapsulamento serve para proteger e esconder certas partes do nosso código (métodos e atributos da classe) Outras linguagens de programação usam modificadores de acesso, ex: public, protected (apenas dentro da classe e das filhas da classe), private (só disponível dentro da classe) ''' from database import Databa...
class A: vc = 123 # Inicializa logo quando instancia, caso não seja instanciado, não altera a variavel da classe. def __init__(self): self.vc = 111 a1 = A() a2 = A() # Muda para todas as instancias A.vc = 321 # Muda apenas para a instancia a1.vc = 9090 # R: {'vc': 9090} print(a1.__dict__) # R:...
import sys import time list_a = [1, 2, 3, 4, 5] ''' Um iterável não é necessáriamente um iterador; Os iteradores são iteráveis; Para saber se é um iterável como listas e strings: ''' print(hasattr(list_a, '__iter__')) # No for, é transformado a lista num iterador para fazer print por exemplo. # O for faz a transfo...
nome = 'Daniel' print(nome[0]) # D # Há também a possibilidade de "fatiar" uma variável do tipo String, # retornando um "pedaço" dela. print(nome[0:3]) # Dan # Se começar com numero negativo, ele pega pelo fim da string. print(nome[-1]) # e # IMUTABILIDADE: Uma string no Python é uma sequência de caracteres imutáve...
from person import Person p1 = Person('Tarcísio', 24) p2 = Person('Danielle', 21) p1.to_speak('paçoca') p2.to_speak('movies') print('Acessando atributo da classe: ', Person.current_year) print(p1.get_birth_year()) print(p2.get_birth_year()) # Class method que é um factory method (fabrica objetos) p3 = Person.by_b...
def longest(): term = 0 ans = [0,0] 'ans = [terms,value]' i2 = 0 for i in range(1,1000001): i2 = i term = 1 while i2 != 1: if i2 % 2 == 0: i2 /= 2 term += 1 else: i2 = i2 * 3 + 1 ...
# Q1-Multiples of 3 and 5 # Sol1 : 窮舉法 import time as t # 計時用 start = t.time() a = 1000 print(sum(i for i in range(a) if i % 3 == 0 or i % 5 == 0)) end = t.time() print(end - start) # Sol2 : 排容原理 (速度足足快了3.5倍) start = t.time() def sum_to(lim, factor): return factor * sum(i for i in range(1, i...
n = int(input()) x = list(input() for i in range(n)) for i in range(1, len(x) - 1): if (x[i - 1] < x[i]) != (x[i] < x[i + 1]): print('NEITHER') break else: print('INCREASING') if x[0] < x[1] \ else print('DECREASING')
valor = 4.6 print(round(valor)) # 5 - round(valor) a função arredonda o valor print(abs(valor)) # 4.6 - abs(valor) a função exibe o valor absoluto vetor = ['gato', 'cachorro','golfinho'] vetor.append('leão') # ['gato', 'cachorro', 'golfinho', 'leão'] print(vetor) vetor.insert(2,'tigre') #['gato', 'cachorro', 'tigre',...
# TRABALHANDO COM DOCUMENTOS PDF E WORD # Documentos PDF import PyPDF2 # Extraindo texto de PDFs objetoPDF = open('101.pdf','rb') leitorPDF = PyPDF2.PdfFileReader(objetoPDF) #lendo o objeto pdf numeroDePaginas = leitorPDF.numPages #numero de paginas print(numeroDePaginas) objetoPagina = leitorPDF.getPage(0) textoExt...
# Percorrendo uma lista inteira com um laço nomes = ['samuel','ruanna','alzenir','joao', 'jose', 'maria'] # percorrendo cada item da lista for nome in nomes: print(nome.title()) #imprimindo cada nome #print("Ainda estou dentro do laço FOR") print("Como não utiliza {} no laço for... ele so executa quem e...
# Um dicionário simples pessoa = { 'nome' : 'samuel', 'idade' : 26, 'sexo' : 'masculino' } print(pessoa['nome']) # ACESSANDO OS ATRIBUTOS DO DICIONARIO PESSOA nomePessoa = pessoa['nome'] print("Meu nome é: " + pessoa['nome'].title()) #ou print("Meu nome é: " + nomePessoa.title()) # Adicionando novos par...
##### ESSA FUNÇÃO SERÁ IMPORTADA POR OUTRO ARQUIVO - FUNCOES.PY def pizza(tamanho, *ingredientes): pizzaCompleta = [] print("Tamanho da PIZZA: " + str(tamanho)) for ingrediente in ingredientes: pizzaCompleta.append(ingrediente) return pizzaCompleta def pizza2(): mensagem = "teste de fun...
def beautify(arr): result = "" for i in range(len(arr)): result = result+"{}\n".format(arr[i]) return result def arreglo_binario(numero): x = '00000000' # 8 bits bits = 8 binarios = [] binarios.append(list(x)) for i in xrange(numero): x = incrementar_binario_string(x...
'''import string s=input() s1='abcdefghijklmnopqrstuvwxyz' s2='ABCDEFGHIJKLMNOPQRSTUVWXYZ' s3='1234567890' l1=[] l2=[] l3=[] for i in range(len(s)): if s[i] in s1: l1.append(s[i]) elif s[i] in s2: l2.append(s[i]) else: l3.append(s[i]) l1.sort() l2.sort() even=[] o...
''' # x = x + 1 # loop several times LOAD_NAME R1, x LOAD_CONST R2, 1 BINARY_ADD STORE_NAME R2, x # now loop back ''' from simulator import * import os start() code1 = Code(row=2, col=5, lineNumbers=True) code2 = Code(row=2, col=5, lineNumbers=True) code1.set_message_area(20, 50) code2.set_message_area(20, 50) stack...
# 1. Variables # nameVariables = "Alexander" # print(nameVariables) # 2. Strings # myStrings = "Hello Python" # print(myStrings) # 3. Numbers # myInteger = 5 # print(myInteger) # myFloat = 5.0 # print(myFloat) # 4. Boolean # myBoolean = True # print(myBoolean) # 5. Data Type # a = 3 # print(type(a))
import random as rd def DNA(length): neclt = ["A", "T", "G", "C"] dnau = str() dnad = str() length = length for i in range(length): dnau += rd.choice(neclt) for j in range(len(dnau)): if dnau[j] == "A": dnad += "T" elif dnau[j] == "T": dnad +=...
#ZigZag Conversion #https://leetcode.com/problems/zigzag-conversion/ #Medium, 01/01/2022 #Tailai Wang class Solution(object): def convert(self, s, numRows): output = "" rowList = [output for i in range(numRows)] rowCounter = 1 decreasing = False if numRows == 1: ...
#3nplus1 b=int(input()) count=0 def collatz(b): l=[b] if b==1: return 1 elif b%2==0: l.append(collatz(b/2)) else: l.append(collatz(b*3+1)) return l print(len(l)) collatz(7)
word = input() output = "YES" valid = "IOSHZXN" for char in word: if char not in valid: output = "NO" print(output)
# 2d array of 0,1,6 representing a maze that your character can walk through # 0 - represents empty space, the character can walk over empty space # 1 - represents a wall, the character cannot walk over a wall # 6 - represents a monster, the character can walk over a monster if you choose to but it will lose a life # ...
#Counting Bits #https://leetcode.com/problems/counting-bits/ #Easy (Daily Challenge), 01/03/2022 #Tailai Wang class Solution(object): def countBits(self, n): """ :type n: int :rtype: List[int] """ output = [0] for i in range(1, n + 1): output.append(outpu...
#soundsFishy a=int(input()) b=int(input()) c=int(input()) d=int(input()) if a<b<c<d: print("Fish Rising") elif a>b>c>d: print("Fish Diving") elif a==b==c==d: print("Fish At Constant Depth") else: print("No Fish")
#find the character let=input() string=input() temp=string.lower() count=0 for letter in temp: if letter==let: count+=1 print(string) print(count)
#Swap Nodes in Pairs #https://leetcode.com/problems/swap-nodes-in-pairs/ #Medium, 08/02/2022 #Tailai Wang # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def swapPairs(self, head):...
#Sum or Root to Leaf Binary Numbers #https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ #Easy (Daily Challenge), 11/01/2022 #Tailai Wang # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = l...
text = input() vertical = 0 horizontal = 0 for char in text: if char == "V": vertical += 1 if char == "H": horizontal += 1 nH = horizontal%2 nV = vertical%2 if nH == 0 and nV == 0: print(1,2) print(3,4) if nH == 0 and nV == 1: print(2,1) print(4,3) if nH == 1 ...
#sorting list1=[] out=[] n=int(input()) for i in range(n): c=int(input()) list1.append(c) for i in range(len(list1)): out1=min(list1) list1.remove(out1) out.append(out1) for i in out: print(i)
#finding-the-percentage n = int(input()) def find_percentage(n): outputlist = [] for i in range (0,n+1): temp = input().split(" ") if len(temp) == 1: for item in outputlist: if item[0] == temp[0]: return(item[1]) runningsum = 0 ...
######################################################################### #Copyright 2013 Akif Patel # #Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2...
#Ejercicio_ListaDatos_07 import time import os try: #Declaramos las listas provincias = ['Ávila','Burgos','León','Palencia','Salamanca','Segovia','Soria','Valladolid','Zamora','Castilla y León'] casos_confirmados = ['414','719','821','262','1.030','567','523','886','192','5414'] nuevos_...
''' There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube_i is on top of cube_j then sidelength_i <= sidelength_j. When stacking the cubes, you can only pick up either the leftmost or the rightmost...
''' Task You have a non-empty set s, and you have to execute N commands given in N lines. The commands will be pop, remove and discard. Input Format The first line contains integer n, the number of elements in the set . The second line contains n space separated elements of set s. All of the elements are non-negative ...
if __name__ == '__main__': outList = [] scoreList = [] for _ in range(int(input())): inList = [] name = input() inList.append(name) score = float(input()) inList.append(score) outList.append(inList) scoreList.append(score) minScore = min(scoreList) se...
data = open('data', mode='r') entry = [] for line in data: entry.append(line) def check(a): try: end=len(a)-1 if end == 0: print('last number') return "Yes" elif a[1]>a[0] and a[1]>a[end]: print('ends less than left plus one') return "No" ...
#!/usr/bin/python import sys cont=0 lado = input (" Introduzca el tamanyo: ") for i in range(lado): print('\n') cont = 0 while cont != lado: cont = cont +1 if i == 0 or i == (lado -1): sys.stdout.write('*') else: if cont == 1 or cont == lado: ...
#!/usr/bin/python num1 = input ('Introduzca el primer numero: ') num2 = input ('Introduzca el segundo numero: ') sum = num1 + num2 rest = num1 - num2 prod = num1 * num2 div = num1 / num2 print ('la suma de los numero es ', sum, ' su resta es ', rest,' su producto es ', prod, ' su division es ', div)
#!/usr/bin/python frase = raw_input('introduzca su frase: ') cortar = frase.split(" ") cortar.reverse() str(cortar) final =' '.join(cortar) print (final)
#!/usr/bin/env python # Simple program to list entries in assurpid sqlite database. import sqlite3 conn = sqlite3.connect('/var/db/assurpid/assurpid.db') print('opened database successfully') print() cursor = conn.execute("SELECT UID, ADMIN, ACCESS_ROOM1, INSIDE_ROOM1 FROM MAIN") for row in cursor: print("For ta...
from pdb import set_trace as breakpoint class Dog(): def __init__(self, name, age, housebroke=True): self.name = name self.age = age self.housebroke = housebroke def bark(self): print(f'{self.name} likes to bark!') class Beagle(Dog): def __init__(self, name, age, housebr...
""" This is a sample mean-reversion algorithm on Quantopian for you to test and adapt. This example uses a dynamic stock selector called Pipeline to select stocks to trade. It orders stocks from the QTradableStocksUS, which is a dynamic universe of over 2000 liquid stocks. (https://www.quantopian.com/help#quantopian_...
def add(n): if n == 1: return 1 return n + add(n-1) def multiply(a,b): if b == 0: return 0 return a + multiply(a,b-1) print(multiply(3,12))
import re text_to_search = """ 1. this is plain text file. 2. what you are going to acheive with this? 3. third line hai ye. 4. this one is forth line. 5. and so on fifth line. 6. sixth. 7. Seventh. 8. eighth line. 9. ninth line. 10. last but not least tenth line. ha ha hahahaha HAHAHAHAH 12 4 3 4 6 3 123.456.6745...
# -*- coding: utf-8 -*- """a2pcej, convert Alphabet to Phonetic Code in English and Japanease. This module convert each alphabet letters to phonetic code, and also convert each alphabet letterts to katakana. """ from __future__ import absolute_import, unicode_literals import argparse import sys from .a2pcej i...
""" file = open("newfile.txt", "w") a = 50.0034534 b = "Hello world" if (a>50): for x in range (0,4): file.write("test number"+str(x)+":\n") file.write("Samyak is "+str(a)+" years old and says "+str(b)+"\n") """ """ class Student(object): name = "" age = 0 major = "" print ("Student:"+str(...
# -*- coding: utf-8 -*- #使用 Python 生成类似于下图中的字母验证码图片 from PIL import Image, ImageDraw, ImageFont, ImageFilter import string import random def generate(length=4): width, height = 240, 60 img = Image.new('RGB', (width, height), (200, 200, 200)) font = ImageFont.truetype('Arial.ttf', 50) draw = ImageDraw...
# -*- coding: utf-8 -*- #敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 def filter_word(list_file='filtered_words.txt'): word_list = [] with open(list_file, 'rb') as f: for line in f.readlines(): word_list.append(line.strip()) input_text =...
import time import threading # Python Threading Example for Beginners # First Method def greet_them(people): for person in people: print("Hello Dear " + person + ". How are you?") time.sleep(0.5) # Second Method def assign_id(people): i = 1 for person in people: print("Hey! {},...
ef divisible_by_ten(nums): count = 0 for n in nums: if n % 10 == 0: count += 1 return count #Uncomment the line below when your function is done print(divisible_by_ten([20, 25, 30, 35, 40])) #expected: 3 because 20,30and 40 are all divisible by 10. def add_greetings(names): empty_lst = [] for n...
# Define the function header to accept one input parameter called num # Print out 1 times num # Print out 2 times num # Print out 3 times num # Return the value of 3 times num def first_three_multiples(num): a = num * 1 print(a) b = num * 2 print(b) c = num * 3 print(c) return(c) # Uncomm...
first_name = "Julie" last_name = "Blevins" def account_generator(first_name, last_name): account_name = first_name[0:3] + last_name[0:3] return account_name new_account = account_generator(first_name, last_name) print(new_account) first_name = "Reiko" last_name = "Matsuki" def password_generator(first_name, la...
class MovingAverage: def __init__(self, lista): a = self.a def compute(self): x=0 print("[", end ="") while x<(len(a)-1): med = (a[x]+a[x+1])/2 if x==0: pass else: print(",", end ="") print(med, e...
# linear_orderly.py # y = 3x – 2 인 경우에 최소 제곱법으로 기울기와 절편 구하기 # 라이브러리 import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model # 학습 데이터 생성 # 0~1까지 난수를 100개 만듦 x = np.random.rand(100, 1) # 값의 범위를 -2~2로 변경 x = 4 * x - 2 # x는 0~1까지의 난수 # y = 3x - 2 y = 3 * x - 2 # 모델 생성 # 최소 제곱법으로 구현 model = l...
########################## Insertion Sort ################################# import math def InsertSort(arr): for i in range(1, len(arr), 1): # Insert i into the right place in the subarray ind = i for j in range(i, -1, -1): # print "ind", ind # print 'j', j ...
set_number = 6557 num1 = int(input()) num2 = int(input()) if(set_number == num1 * num2): print(True) else: print(False)
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) T=23 E=24 print"distance in progress" GPIO.setup(T,GPIO.OUT) GPIO.setup(E,GPIO.IN) GPIO.output(T,0) time.sleep(2) GPIO.output(T,1) time.sleep(0.000001) GPIO.output(T,0) while GPIO.input(E)==0: time1=time.time() while GPIO.in...
import threading from threading import* import time #'d' is the dictionary in which we will store the data d={} #for create operation we can use create use syntax--> create(key_name,value,timeout) # NOTE: timeout is optional we can continue by passing two arguments without timeout def create(key,value,timeou...
# A pangram is a sentence that contains every single letter of the alphabet at least once. # For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, # because it uses the letters A-Z at least once (case is irrelevant). # Given a string, detect whether or not it is a pangram. Return True...
import turtle wn = turtle.Screen() s = turtle.Turtle() s.pensize(3) s.color("blue") wn.bgcolor("lightgreen") def make_square(sz): for i in range(4): s.pendown() s.forward(sz) s.left(90) for i in range(20): make_square(100) s.left(20)
import turtle wn = turtle.Screen() wn.bgcolor("lightgreen") s = turtle.Turtle() s.color("hotpink") s.pensize(3) def make_square(sz): for i in range(4): s.pendown() s.forward(sz) s.left(90) make_square(20) s.penup() s.setx(-20) s.sety(-20) make_square(60) s.penup() s.setx(-40) s.sety(-40) ...
A=int(input(" Enter 1st no: ")) B=int(input(" Enter 2nd no: ")) Result= A+B Print(" Addition is: ",Result)
def check_contain(): """ Решение задачи 3.2 шаг 6 """ # get value of variable from user s, a, b = [input('Enter value in var: ').strip() for _ in range(3)] num = [] if a in b and a in s: print('Impossible') else: while a in s: num.append('1') s = ...
import csv # Drop the last digit from the number. The last digit is what we want to check against # Reverse the numbers # Multiply the digits in odd positions (1, 3, 5, etc.) by 2 and subtract 9 to all any result higher than 9 # Add all the numbers together # The check digit (the last number of the card) is the amount ...
print("Hello world") #this is a comment #1. make notes to myself #2. Comment pieces of code that do not work #3. make my code easier to read print ("Look at what happens her. Is there any space?") print() print() print ("There should be a couple blank lines here.") #math print (3+5) print (5-2) print (3*4) print (6...
data = {"Pablo":[33], "Bob":[14], "Sam":[17, 23]} for key, val in data.items(): print(key, val)
print("How old are you? ", end=' ') age = input() print(f"So, you're {age} old")
print("Hello World\n") #user_name = input('What is your name?') #print('\tHi, ' + user_name.title()) monthes = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] print(monthes[0].title())
def max2(a,b): a=input("ingrese primera variable") b=input("ingrese segunda variable") if a > b: print (a,"es mayor que ",b) elif b > a: print (b,"es mayor que ",a) else: print (a, "y" ,b, "son iguales") return def max3(c,d,e): c=input("ingrese primera variable") ...