text
stringlengths
37
1.41M
''' https://www.codeeval.com/open_challenges/8/ Write a program that reverses the words in an input sentence. ''' test_cases = open("test.txt","r") def reverse(insert_text): for line in insert_text: new = [] wordlist = line.split() n = len(wordlist)-1 while n >= 0: new.append(wordlist[n]) n = n - 1 ...
from random import randint import matplotlib.pyplot as plt # create file writer, if file does not exist it is created # if file exists it will be overwritten file = open('integers.txt', 'w') for i in range(1, 501): file.write(str(randint(i, 500)) + "\n") file.close() integers = [] file = open('integers.txt', 'r'...
# -*- coding: utf-8 -*- """ Created on Wed Jan 27 10:54:59 2021 @author: mmacarty """ TAX_RATE = .20 STANDARD_DEDUCTION = 12200 DEPENDENT_DEDUCTION = 2000 income = float(input("Enter your income: ")) dependents = int(input("Enter number of dependents: ")) taxable_income = income - STANDARD_DEDUCTION - DEPENDENT_DED...
import text def _read_rhyme_dictionary(filename): rhymes = {} with open(filename) as f: for line in f: line = line.strip() if line: words = set(text.split_into_words(line)) for w in words: assert w not in rhymes rhymes[w] = words return rhymes _RHYME_FILE = 'r...
def search_tree(root, dna): """Search for a dna sequence in the given tree.""" i = 0 while i < len(dna): if not dna[i] in root.children: return 0 root = root.children[dna[i]] i += 1 return root.count
"""Get coding of different letters from given Huffman-tree The Node()-object has attributes 'left_child' and 'right_child', which are none if the node has no children. Node() also has an attribute 'character' which is the letter that the node represents. These are in the leaves of the tree. """ def encoding(node...
import time #set up global constants for the puzzle. these can be changed to alter the difficulty. ALLOWED_TIME_FOR_PUZZLE = 30 #player has this many seconds to complete the puzzle NUM_NODES = 3 #the game has 3 nodes. until we fix the update_node() function to be dynamic, this is hardcoded to 3 COLORS = ['red', 'ora...
num=int(input("enter the number")) revs_number = 0 while (num > 0): a = num % 10 revs_number = (revs_number * 10) + a num = num // 10 print(f'the reverse number is {revs_number}')
a = input("enter the string: ") print(f'the given string is {a}') print("reversed string" , reverse(a))
"""1 Escreva um programa que lê̂ duas notas de vários alunos e armazena tais notas em um dicionário, em que a chave é o nome do aluno. A entrada de dados deve terminar quando for lida uma string vazia como nome. A seguir, faça um loop que pede o nome do aluno e mostra sua média. """ #dicionario vazio dicionario = {}...
def anagrams(word, words): return list(i for i in words if sorted(i) == sorted(word)) print(anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']))
class Linklist(object): def __init__(self, obj): self.obj = obj self.next = None def __str__(self): return self.obj def init(): return Linklist('HEAD') def insert(head, index, linklist): if isinstance(head, Linklist): temp = head for i in range(index-1): ...
"""Define a discrete Markov process of arbitrary order.""" import logging import numpy class DiscreteMarkov: """Allawo simulating a discrete Markov process of arbitrary order.""" def __init__(self, transition_probabilities=None, initial_state=None, samples...
from datastructures.Node import Node class LinkedList: def __init__(self, head=None): self.head = head def instet(self, data): newNode = Node(data) newNode.setNextNode(self.head) self.head = newNode def size(self): currentNode = self.head i = 0 wh...
import random random.seed() Nothing=ord('.') Player1=ord('O') Player2=ord('X') Player1has4='OOOO' Player2has4='XXXX' Player1Wins='human wins' Player2Wins='computer wins' Player2Take='computer takes ' DirectionHorizontal='horizontal' DirectionVertical ='vertical' DirectionDiagonal ='diagonal' ErrorMess...
""" Write a program in the language of your choice that will remove the lowest homework score for each student. Since there is a single document for each student containing an array of scores, you will need to update the scores array and remove the homework. { "_id" : 0, "name" : "aimee Zank", "scores" : ...
from typing import Iterable, List def flat(some_list: Iterable[Iterable]) -> List: return [item for sublist in some_list for item in sublist]
import heapq import operator #### Build a tree class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def insert_left(self, child): if self.left is None: self.left = child else: child.left = self.left ...
SEPARADOR = ("*" * 20) + "\n" #Creación de listas # #Lista vacía lista_vacia = list() otra_lista_vacia = [] #Lista con elementos iniciales lista_uno = [1, 2, 3, 4] print(lista_uno) print(SEPARADOR) pass #Agregar elementos a listas existentes lista_uno.append(5) print(lista_uno) lista_uno....
# -*- coding:utf8 -*- # @TIME : 2018/10/30 14:30 # @Author : Chinwe # @File : Name.py # name = raw_input("please input your name") # print("hello" + name) age = 10 if age >= 10: print("少年") elif age < 10: print("孩童") else: print("都不是") arr = ['Tom', 'able', 'kobe'] print(arr) arr.append('sum') pr...
class MenuItem: """Models or specifies each menu item's attributes""" def __init__(self, name, cost, water, milk, coffee): self.name = name self.cost = cost self.ingredients = { "water": water, "milk": milk, "coffee": coffee, } class Menu: ...
from turtle import Turtle FONT = ("Courier", 24, "normal") class Scoreboard(Turtle): def __init__(self): super().__init__() self.color("black") self.penup() self.hideturtle() self.level_numb = 1 self.display_score() def display_score(self): self.goto(-2...
import turtle import pandas screen = turtle.Screen() screen.title("U.S. States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) data = pandas.read_csv("50_states.csv") state_list = data.state.to_list() guessed_states = [] while len(guessed_states) < 50: answer_state = screen.textinp...
#!/usr/bin/env python3 from random import randint file=open('vocab','r',encoding='utf8') vocab=[] for line in file: vocab.append({'l1':line.split('=')[0],'l2':line.strip('\n').split('=')[1],'n':3}) remaining=len(vocab)-1 while remaining>0: thisround = randint(0,remaining) fromlang = 'l'+str(rand...
# -*- coding: utf-8 -*- """ Created on Thu Aug 5 23:08:01 2021 @author: taufiqlibrary """ import matplotlib.pyplot as plt x1 = [2, 3, 4] y1 = [5, 5, 5] x2 = [1, 2, 3, 4, 5] y2 = [2, 3, 2, 3, 4] y3 = [6, 8, 7, 8, 7] # Markers : http://matplotlib.org/api/markers_api.html plt.scatter(x1, y1) plt.scatter(x2, y2, mark...
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return '<h1> 8D 23nd Hello World</h1>' @app.route('/pakistan/<city>') # defining 1st method def index1(city): if (city=='karachi'): return '<h1> karachi is the largest city of Pakistan <br> in future we shall be p...
# Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) def check_route(self, s, node): vis...
from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add_edge(self, u, v): self.graph[u].append(v) def dfs_util(self, v, visited): visited[v] = True print v, for i in self.graph[v]: if visited[i] == False: self.dfs_util(i, visited) def dfs(s...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, x): new_node = Node(x) new_node.next = self.head self.head = new_node def print_list(self): node = self.head while(node): print node.data node = nod...
# https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/549/ def find_single_number(nums): if len(nums) == 0: return x = nums[0] for i in range(1, len(nums)): x = x ^ nums[i] return x nums = [1,2,1] nums = [] nums = [1,1,2,2,3,3,4,5,4] print find_single_number(nums)
"""Minimal Tree: Given a sorted (increasing order) array with unique integer elements, write an algo­rithm to create a binary search tree with minimal height.""" class Node: def __init__(self, x): self.data = x self.left = None self.right = None def create_bst(a): if not a: return None mid = len(a)/2 root ...
def find_min_steps_in_infinite_grid(A, B): total = 0 curr_x = A[0] curr_y = B[0] for i in range(1, len(A)): j = abs(A[i] - curr_x) k = abs(B[i] - curr_y) curr_x = A[i] curr_y = B[i] total = total + max(j, k) return total print find_min_steps_in_infinite_grid([0, 1, 1], [0, 1, 2])
# Comparison Operators # In python, it's 2 == as one equal means that you are assigning values. print(2 == 2) print (3 != 3) #Chaining Comparison Operators with Logical Operators #Use "and" "or" "not" to chain comparisons #Simple comparisons print(1 < 2 < 3) #Logical Operator print(('h' == 'h') and(2 == 2) ) pri...
def arrange_by_columns(entries, column_count): r = len(entries) % column_count if r > 0: entries.extend([None] * (column_count - r)) entries_per_column = len(entries) // column_count columns = [ entries[i * entries_per_column : (i + 1) * entries_per_column] for i in range(column...
# set78 i=int(input())2 if (i%7==0): print('yes') else: print('no')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @File : IO_test1.py # @Author: 橘子 # @Date : 2020/8/4 # @Desc : execise import re # """输入input函数""" # name = input('your name:') # gender = input('you are a boy?(y/n)') # # welcome_str = "welcome to the matrix {prefix}{name}." # welcome_dic = { # 'prefix':'Mr.' i...
num1=input("Enter a number:") num2 =input("Enter another number:") result = float(num1)+float(num2) print(result)
num1=float(input("Enter a number:")) op=input("Enter operator:") num2=float(input("Enter another number:")) if op == "+": print(num1+num2) elif op =="-": print(num2-num1) elif op == "/": print(num2/num1) elif op == "*": print(num1*num2) else: print("Please enter a valid operator")
digits = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' ] dozens = { 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fift...
# Class of tree class Tree(object): def __init__(self, x, y): self.health_level = 0.1 self.infected = False self.infected_months = 0 self.infected_start_time = -1 self.beetle_list = [] self.neighbor_list = [] self.x = x self.y = y self.last_ti...
# -*- coding: utf-8 -*- """ Created on Thu Dec 26 20:09:38 2019 @author: yushi """ # Complete the 'rotateTheString' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING originalString # 2. INTEGER_ARRAY direction # 3. INTEGER_ARRAY amount # def ...
# -*- coding: mac-roman -*- # Exemplo simples entradas / sadas / atribuies # Ernesto Costa # Dada a altura calcula o peso ideal para uma pessoa def main(): """" Tem o peso ideal? """ # mensagem altura = input("A sua altura por favor: ") sexo = raw_input("O seu sexo por favor (M / F): ") if sexo == 'M':...
""" O Mundo do DEI e' um jogo de aventura muito simples basead em texto. Os utilizadores podem perambular num ambiente, e e' tudo. Este jogo deve ser estendido para se tornar mais interessante. Este jogo esta' baseado no "Zuul Game" de M. Kolling e D. Barnes. Autor: R. de Lemos Versao: 15 Novembro 2009 ...
def perfeito(n): return n == sum(divisores(n)) def divisores(n): res = () for i in range(1,n//2+1): if (n % i) == 0: res += (i,) return res def perfeitos(inf,sup): for i in range(inf,sup+1): if perfeito(i): print(i) if __name__ == '__main__': perfeitos(...
def mostra_por_linhas(matriz): """Indexação pelo conteúdo.""" for linha in matriz: for coluna in linha: print("%5d" % coluna, end=' ') print() def mostra_por_linhas_b(matriz): """Indexação pela posição.""" for pos_linha in range(len(matriz)): for pos_coluna in range(len(matriz[0])): print("%5d" % ma...
# -*- coding: mac-roman -*- # exepes - exemplo razes de polinmio # Ernesto costa - 2006 import math def main(): """ Calculo das raizes reais de um poinomio. """ try: a,b,c = eval(input("Os coeficientes sff (a,b,c):\t")) discriminante=pow(b,2)- 4 * a * c raiz_discrim = math.sqrt(discriminante) raiz1=float(...
from turtle import * def quadrado(lado): """Desenha um quadrado de lado lado. """ forward(lado) right(90) forward(lado) right(90) forward(lado) right(90) forward(lado) right(90) def quadrado_2(lado): """Desenha um quadrado de lado lado. """ conta = 0...
#-*- coding:mac-roman -*- from xturtle import * def main(n): reset() pendown() color('blue') for i in range(n): desenha(100,90) right(10) pen(shown=False) raw_input("prima <enter> para terminar. ") def desenha(lado,angulo): for i in range(4): forward(lado) right(angulo) main(36)
def prefixos(cadeia): """Determina todos os prefixos de uma cadeia de caracteres. """ conta = 0 while conta < len(cadeia): print(cadeia[:conta+1]) conta = conta + 1 def prefixos_b(cadeia): conta = 0 while conta < len(cadeia): print(cadeia[: len(cadeia)-conta])...
# -*- coding: mac-roman -*- # ciclos while e for # clculo aproximado do seno def main(): x=eval(input("Valor de x:\t")) n=eval(input("Numero de termos:\t")) print(seno1(x,n)) print("O seno de %4.2f = %5.3f \t" % (x, seno1(x,n))) return 0 def seno1(x,n): res=0 for i in range(n): res = res + (pow(-1,i) * pow...
#-*- coding: mac-roman -*- # turtle while from xturtle import * def main(): lado,angulo_inicial,angulo_viragem,repete=eval(input("Lado e angulos (inicial e de viragem) e repeticoes sff:\t")) reset() for i in range(repete): poligono(lado,angulo_inicial) right(angulo_viragem) input() return 0 def main1(): l...
# -*- coding: mac-roman -*- # hangman # Ernesto Costa - Outubro 2006 from xturtle import * from random import * #--- Programa principal def main(): reset() hideturtle() pendown() # desenha forca() corpo() #mensagens color('black') goto(100,0) write("HANGAM IS WAITTING!",align='left') #gera palavr...
#-*- coding:mac-roman -*- from xturtle import * def main(): reset() pendown() color('red') circulo() pen(shown=False) input("prima <enter> para terminar. ") def circulo(): for i in range(360): forward(1) right(1) main()
#-*- coding: utf-8 -*- from turtle import * from math import * def linha(x1,y1,x2,y2): """ Traça uma linha entre dois pontos.""" up() goto(x1,y1) pd() goto(x2,y2) up() def grafico(func, inf, sup): """Faz o gráfico da função entre os dois valores.""" delta = 0.1 x = inf pu...
"""Objectos_1.""" # max de acordo com função import random def meu_max(elementos,funcao): """qual o maior elemento de acordo com a funcao.""" valores = (funcao(elem) for elem in elementos) return max(valores) if __name__ == '__main__': lista = [random.randint(1,100) for i in range(10)] print(lis...
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # This program is distributed in the hope that it will be useful, ...
"""Ficheiros.""" """ import urllib.request meu_sitio = urllib.request.urlopen("http://ernesto.dei.uc.pt") meus_bytes = meu_sitio.read() minha_cadeia = meus_bytes.decode("utf8") meu_sitio.close() novo_fich = open('/Users/ernestojfcosta/tmp/urlteste.html', 'w') novo_fich.write(minha_cadeia) novo_fich.close() print(mi...
""" O Mundo do DEI e' um jogo de aventura muito simples basead em texto. Os utilizadores podem perambular num ambiente, e e' tudo. Este jogo deve ser estendido para se tornar mais interessante. Este jogo esta' baseado no "Zuul Game" de M. Kolling e D. Barnes. Autor: R. de Lemos Versao: 15 Novembro 2009 ...
# -*- coding: latin 1 -*- # Exemplo 1.1 # Programa para mostrar o comportamento de sistemas simples # Ernesto Costa - Julho 2006 #--- Incio do programa def main(): """ Este programa ilustra o comportamento de um sistema simples. Este sistems descreve o crescimento de uma populao por meio do mapa logstico. ""...
def padrao_1(n): """ Imprime linhas de números entre 1 e n.""" comp = len(str(n)) for i in range(1,n+1): for j in range(1,i+1): print(j,end=comp*' ') print() def padrao_2(n): """ Imprime linhas de números entre 1 e n, com n<100.""" for i in range(n,0,-1): for j i...
import random import turtle def visualiza(pontos): """ Valor de pi pelo método de Monte Carlo. Versão gráfica. """ # Prepara a visualização turtle.setworldcoordinates(-2,-2,2,2) janela = turtle.Turtle() janela.hideturtle() # Desenha os eixos janela.up() janela.goto(-1,0) ...
# 输入3个数字,比大小 num1,num2,num3 ''' 思路: num1>num2>num3 num1最大 num1>num3>num2 num1最大 num2>num1>num3 num2最大 num2>num3>num1 num2最大 num3>num2>num1 num3最大 num3>num1>num2 num3最大 伪代码: num1=int(input("num1:")) num2=int(input("num2:")) num3=int(input("num3:")) if num1<num2 or num1<num3: pri...
class digua: def __init__(self): self.time = 0 self.zhuang = "生的" self.liao = [] def kehu(self,add): self.time += add if 0 < self.time <= 3: self.zhuang = "生的" elif 3 < self.time <= 5: self.zhuang ="半生不熟" elif 5 < sel...
#print even numbers from 1 to 1000 for count in range(1,1001): if count%2 != 0: print count #print multiple of 5 from 5 to 10^6 for count in range(5,1000001): if count%5 ==0: print count #print all values in list a a = [1,2,5,10,255,3] for value in a: print value #print the averate of values in list a sum = 0 ...
from tkinter import * from HoverCanvas2 import HoverCanvas2 class HoverCanvasToutEffacer(Canvas): def __init__(self, parent, lettre, label, pred1, pred2, pred3): Canvas.__init__(self, parent, width = 100, height = 100, bg = 'white',highlightbackground='black') self._dans = False ...
#!/usr/bin/env python # coding: utf-8 # # Have you seen this number before? # # Write a function that receives as an argument a list of numbers. For each number, append to an empty list the word "YES" if this number was previously encountered in the sequence, or "NO" if it was not. # # Example: # ``` # Input data: #...
from Counter import * class Clock(object): def __init__(self): self._hours = Counter("Hours") self._minutes = Counter("Minutes") self._seconds = Counter("Seconds") def Reset(self): self._hours.Reset() self._minutes.Reset() self._seconds.Reset() ...
import abc from typing import Tuple class MessageIO(metaclass=abc.ABCMeta): """Define how to extract text from a message and to append result to a message. """ @abc.abstractmethod def extract_text(self, message) -> Tuple[str, str]: pass @abc.abstractmethod def append_result(self, mes...
import pandas import numpy myarray = numpy.array([[1,2,3],[4,5,6]]) rownames = ['a','b'] colnames = ['one','two','three'] mydataframe = pandas.DataFrame(myarray,index=rownames,columns=colnames) print(mydataframe)
a=input("Enter first string:") b=input("Enter second string:") c=list(set(a)&set(b)) print("The common letters are:") for i in c: print(i)
'''Problem 8A - Train and Peter''' colors = (input()) # stringul de culori f = (input()) # prima faza s = (input()) # a doua faza forw = 0 # verific daca e culorile din prima si a doua faza sunt in colors # in ordinea lor normala if f in colors: # daca prima faza este in colors f_idx = colors.index(f) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 7 14:56:12 2020 @author: aaronberlow """ #Breaking string into components abc = "With three words" stuff = abc.split() print(stuff) print(len(stuff)) print(stuff[0]) print(stuff) for w in stuff: print(w)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 17 10:31:47 2020 @author: aaronberlow """ #list comprehension # long form num_list = [1,7,5,3,2] new_list = [] for i in num_list: new_list.append(i*7) print(new_list) #short numbers = [1, 7, 5, 3, 2] print([i* 7 for i in numbers])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 16 09:45:10 2020 @author: aaronberlow """ def count_characters(string): count_dict = {} for c in string: if c in count_dict: count_dict[c]+=1 else: count_dict[c] = 1 print(count_dict) count_c...
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): # elements = len(arrA) + len(arrB) merged_arr = [] # * elements # instantiate new array for values a, b = 0, 0 # set each array item to 0 to start while a < len(arrA) and b...
import random import time class Character: """Generic character class""" def __init__(self,name): self.name = name self.health = 50 def display(self): print(f"{self.name} has:") print(f"- {self.health} health points") print(f"- {self.defense} defense points") print(f"- {self.attac...
#Создание пользователей class User(): '''Вывод информации о пользователе''' def __init__(self, first_name, last_name, age, city, phone): self.first_name = first_name.title() self.last_name = last_name.title() self.age = age self.city = city.title() self.phone = phone #Количество попыток входа self...
#NAME : BINARY TREE INORDER TRAVERSAL #CATEGORY : STACKS #DIFFICULTY : MEDIUM #LINK : https://leetcode.com/problems/binary-tree-inorder-traversal/ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def in...
#!/usr/bin/env python33 import argparse class Template: def __init__(self, arg): self.arg = arg def calc(self, pprint): if pprint: result = "One arg is: " + self.arg else: result = self.arg print(result) return result if __name__ == '__main__'...
string = "AABBCCD" result_list = [] def refine(str_input): s = str_input s_list = list(s) unordered = list(set(s_list)) for i in range(len(unordered)): result_list.append("c") for i in range(len(unordered)): orignal_pos = s_list.index(unordered[i]) result_list[orignal_pos]...
#!/usr/bin/python3.6 i = int(input()) lst = list(map(int , str(input()).split())) t = int(input()) while t > 0: a = int(input()) n = lst.count(a) if n: print(n) else: print("NOT PRESENT") t -= 1
T = int(input()) chef = "chef" count = 0 for i in range(T): frn = str(input()) for j in range(len(frn)+1): if frn[j:j+2] in chef: test = frn[j:j+2] if len(test) >1: if frn[j:j+3] print(count)
total = int(input()) num = str(input()) num_list = num.split() new_list = [] for i in range(total): new_list.insert(i, int(num_list[i])) print(sum(new_list))
list1 = [1, 2, 3, 7] list2 = [4, 3, 2, 6] def getPairsCount(sum): count = 0 sum=5 for i in range(0, len(list1)): for j in range(0, len(list2)): if list1[i] + list2[j] == sum: print(list1[i],list2[j]) count += 1 return count print("Count of...
from automobile import * class Car(Automobile): def __init__(self,make,model,mileage,price,doors): Automobile.__init__(self,make,model,mileage,price) self.__doors=doors def set_doors(self,doors): self.__doors=doors def get_doors(self): return self.__doors class...
import Tkinter as tk import math class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.title("Canvas animation example") width = 400 height = 300 self.c = tk.Canvas(self, width=width, height=height) self.c.pack() self.f_index = 0 # index so we kno...
""" 6. В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться больше или меньше введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, то вывести загаданное число. Реши...
from datetime import datetime class Event: list_of_events = [] def __init__(self, message, time): self.message=message self.time=time @classmethod def fromDateArgs(event, message, year, month, day, hour, minute): return event(message, datetime(year, month, day, hour, minute, 0)...
num1=int(input("enter the number:")) count1=1 while count1<=num1: if num1%count1==0: print(count1) count1+=1 num2=int(input("enter the number:")) count2=1 while count2<=num2: if num2%count2==0: print(count2) count2+=1
a=0 b=10 while b>0: print("enter the number:") c=int(input()) a=a+c b -=1 print(a/10)
num1=4 num2=6 i=0 j=0 while i<=num1: while j<=num2: if i*j==num1: print(i) else: print(j)
"""Task: Move Cube on Trajectory The goal of this task is to grasp a cube and move it from one goal to the next on a given trajectory. The trajectory is given as a list of tuples ``(t, goal_position)`` where ``t`` specifies the time step from which the goal position is active. So the full type is ``Sequence[Tuple[in...
import math sumatory = 0 numA = int(input("ingrese el numero inicial\n")) numB = int(input("ingrese un numero final\n")) if 0 <= numA <= numB: for i in range(numA, numB + 1): sumatory = sumatory + math.sqrt(i) print(sumatory) else: print("Valor final menor al inicial")
import scrabble import string #printing the word which contains double uu in that from dict for word in scrabble.wordlist: if "uu" in word: print(word)
# 查看帮助 help(filter) help(map) help(reduce) a=[1,2,3,4,5,6,7] # calc = lambda x:x>2 # print(calc(10)) #返回True/False result = filter(lambda x:x>2,a) print(list(result)) print(list(map(lambda x:x+1,a))) b=[4,5,6] print(list(map(lambda x,y:x+y,a,b))) # reduce虽然是内建函数,但是需要导入才可使用 from functools import reduce print(reduce(lam...
chinese_zodiac = "鼠牛虎兔龙蛇马羊猴鸡狗猪" year = input("请输入出生年份") print(year) print(chinese_zodiac[int(year)%12]) for item in chinese_zodiac: print(item) # range用来生成一个序列,可以指定开始和结束的数字 for i in range(13):#没写start就是从0开始;到12结束 print("i is "+str(i)) for i in range(1,13): print(i) for year in range(2000,2019): print(...
# # 读取任务名称 # f = open('txt/name.txt',encoding='utf-8') # # 竖线作为分割 # data = f.read() # print(data.split('|')) # # 读取兵器名称 # f2 = open('txt/weapon.txt',encoding='utf-8') # i=1 # for line in f2.readlines(): # if i%2 == 1: # # Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。 # ...
def main(): enemyAC = 0 attackMod = 0 maxSD = 8 print print "Hello Wulfgar, we know math can be hard sometimes." print "That's why we made this nifty little tool to help" print "calculate the probability of landing a Great Weapon Master attack." print "Please provide the following info and we'll give you ...
#!/usr/bin/python3.5 from datetime import datetime, timedelta, tzinfo, timezone def date_distance(date_str): tz = timezone(timedelta(hours=8)) now_date = datetime.now(tz).date() fmt = '%Y-%m-%d' post_date = datetime.strptime(date_str, fmt) post_date = post_date.replace(tzinfo=tz).date() return...
from datetime import datetime def date_distance(date_str): try: other_date = datetime.strptime(date_str, '%Y-%m-%d') now_str = datetime.now().strftime('%Y-%m-%d') now = datetime.strptime(now_str, '%Y-%m-%d') distance = (now-other_date).days except ValueError: return '{}...