text
stringlengths
37
1.41M
#This is day 10, Functions with outputs/returns #Exercise 1 - Days in Month def is_leap(year): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False def days_in_month(year, month): if month > 1...
#This is day 4, randomization and python lists #Exercise 3 - Crown marks the spot (Working in Maps with Nested Arrays): # 🚨 Don't change the code below 👇 row1 = ["⬜️","⬜️","⬜️"] row2 = ["⬜️","⬜️","⬜️"] row3 = ["⬜️","⬜️","⬜️"] map = [row1, row2, row3] print(f"{row1}\n{row2}\n{row3}") position = input("Where do you w...
#!/usr/bin/env python # encoding=utf-8 (pep 0263) """ Implementace algoritmu A* """ from linked_lists import Cons, Nil class BestSearch(object): def __init__(self, bound, is_goal, move_anyYC, h): self.total = 0 self.bound = bound self.is_goal = is_goal self.move_anyYC = move_anyYC...
#!/usr/bin/env python # encoding=utf-8 (pep 0263) from linked_lists import LinkedList, Nil def alphabeta(pos, alpha, beta): poslist = moves(pos) if poslist == Nil: return (None, staticval(pos)) return bounded_best(poslist, alpha, beta) def bounded_best(poslist, alpha, beta): pos = poslist.hea...
#!/usr/bin/env python # encoding=utf-8 (pep 0263) from linked_lists import LinkedList, Nil def member(x, ys): if ys == Nil: return False if x == ys.head: return True return member(x, ys.tail) # demonstracni vypis if __name__ == "__main__": print("Member - 3. varianta") print("Vysl...
#!/usr/bin/env python # encoding=utf-8 (pep 0263) from linked_lists import LinkedList, Cons, Nil def append(xs, ys): if xs == Nil: return ys else: return Cons(xs.head, append(xs.tail, ys)) def qsort(xs): if xs == Nil: return Nil if xs.tail == Nil: return xs ms, vs ...
import numpy as np class KMeans(): def __init__(self, n_clusters): """ This class implements the traditional KMeans algorithm with hard assignments: https://en.wikipedia.org/wiki/K-means_clustering The KMeans algorithm has two steps: 1. Update assignments 2. Updat...
# Create a program that asks the user to enter their name and their age. Print out a message addressed to them that # tells them the year that they will turn 100 years old. Add on to the previous program by asking the user for # another number and printing out that many copies of the previous message. # Instatiation ...
#1 foot= 0.305 meter #1 meter =3.281 foot def get_valid_unit(input1,input2): #function definition for checking valid units if input1=='m'or 'ft' and input2=='m' or 'ft': print('Convert from unit:',input1) print('Convert to unit:',input2) else: print('Enter a valid unit (m for met...
import requests import pandas as pd import getpass import json import sys accountName = getpass.getuser() #importing API key as system arguments key = sys.argv[1] print('Gathering user details, please wait...') print('') #reads csv file to get email address and user details df = pd.read_csv(f'/Users/{accountName}/Do...
from tkinter import * root = Tk() myLabel = Label(root, text="Hi!!") myLabel2 = Label(root, text="This is the first python window tried by me!!") myLabel.grid(row=0, column=0) myLabel2.grid(row=1, column=5) root.mainloop()
""" This module focuses on testing the `break_control` function. Please note: These are only EXAMPLE tests, you will need to extend and think of corner cases to allow for further testing. """ import unittest from invasion import AlienInvasion class BreakControlTests(unittest.TestCase): def test_break_control_s...
N = [-10, -5, 1, 2, 3, 6, 5] def print_positive(array: list): for num in array: if num > 0: print(num) print_positive(N)
# Mateusz Leputa March 2021 # Dashboard Space Program import time import streamlit as st import numpy as np import pandas as pd import plotly.graph_objects as go import plotly.express as px from sim import World, Vehicle earth = World() rocket = Vehicle() print(type(rocket)) rocket.place_on_surface(earth) def...
def add_to(mat, m): """ :param m: int :param mat: list :return: list """ if len(mat) >= m or len(mat[0]) >= m: return mat for i in range(len(mat)): while len(mat[i]) != m: mat[i].append(0) while len(mat) != m: mat.append([0] * m) retur...
class Car(object): def __init__(self): print('Instance of car has been created') def start(self): print('Car has been started') def stop(self): print('Car has been stopped') class BMW(Car): def __init__(self): print('Instance of BMW is been created') def start...
# ------------------------------------------------------------------------- # Author: Quang Tran # Date: May 9th, 2019 # ------------------------------------------------------------------------- """ Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [...
# ------------------------------------------------------------------------- # Author: Quang Tran # Date: May 10th, 2019 # ------------------------------------------------------------------------- """ Question: Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value...
import numpy as np def f(a): return (4/(1+a*a)) def main(): n=10000000 midpoint = .5 sum = 0. h = 1/n for i in range (1, n+1): sum+= f(midpoint/n) midpoint+= 1 piest = sum * h print("Pi estimation = " + str(piest)) if __name__ == "__main__": main()
import os import csv csvpath = os.path.join("..", "PyBank", "Resources", "budget_data.csv") with open(csvpath) as csvfile: csvreader = csv.reader(csvfile) csv_header = next(csvreader) row = next(csvreader) dates = [] change = [] months = 0 total = 0 increase = 0 increase_month = ...
arr = [3,22,17,1,40,8,31,137, 12, 4, 19, 20, 2, 9] # arr = [7, 12, 4, 19, 20, 2, 9] # arr = [3,22,17,1,20,8,31,13] print(arr,"Begin selection \n") # TO-DO: Complete the selection_sort() function below def selection_sort( arr ): length = len(arr) breakcount =0 # loop through n-1 elements for i in range(0, len(arr...
# coding:utf8 # Keras 快速开始 在MNIST上构建一个简单的神经网络 # Author: DFan from keras.models import Sequential from keras.layers import Dense from keras.datasets import mnist from keras.utils import to_categorical # 下载并载入MNIST数据集 (train_images, train_labels), (test_images, test_labels)= mnist.load_data() # reshape数据集,并归一化 train_i...
def generator(start, end, skip): x = start y = end z= skip while x<y: print(x) x+= z generator(0,5,2)
def tt(): import time x = 1 time.sleep(x) return x def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a - b def multiply (a, b): print "MULTIPLYING %d * %d" % (a, b) return a * b def divide(a, b): print "DIVIDING %d / %d" % ...
# Exercise 15: Reading Files # You know how to get input from a user with raw_input or argv, Now you will learn about # reading from a file. You may have to play with this exercise the most to understand what's # going on, so do the exercise carefully and remember your checks. Working with # files is an easy way to...
# script to try to learn more about the 'return' statement in functions import time def add(a,b): import time print "this function is adding two values %d and %d " % (x,y) time.sleep(.5) print "ADDING %d + %d" % ( a , b ) return a + b x = int(raw_input("enter a number ")) y = int(raw_input("enter another ...
## ------------------------------------------------------------------------------------------------- ## ## Call functions (could be found in shimamura33/Functions/Python) ## ## ------------------------------------------------------------------------------------------------- ## import ...
#字符串切片练习 f = "12345678" # print(f[0]) # print(f[-1]) f1 = f.replace("1","2") # print(f1) # print(f[:]) # print(f[2:]) # print(f[2:4]) # print(f[1:5:2]) # print(f[::-1]) import io s = "hello world" s1 = io.StringIO(s) print(s1.seek(2)) print(s1.write("m")) print(s1.getvalue())
# 1. Create a checking account class and derive it from Account class # -deposit() : Any amount can be deposited # -withdraw() : Maximum 6 withdrawals allowed per month. Withdrawal capped at 700 # 2. Create a Savings Account Class and derive it from Account class # -deposit() : Any amount can be deposited #...
#Escreva uma função recursiva que imprima de um número x até um y x = int(input("Digite o valor de 'x':")) y = int(input("Digite o valor de 'y':")) def imprimir(x,y): if(x == y): return x if(x < y): print(x) return imprimir(x + 1, y) print(x) return imprimir(x - 1, y) print(im...
# 2차원 리스트를 1차원 리스트로 만들기 my_list = [[1, 2], [3, 4], [5, 6]] # 방법 1 - sum 함수 answer = sum(my_list, []) print(answer) # 방법 2 - itertools.chain import itertools answer = list(itertools.chain.from_iterable(my_list)) print(answer) # 방법 3 - itertools와 unpacking import itertools answer = list(itertools.chain(*my_list)) pri...
import re # ^ used to check for pattern in the beginning beginsWithHelloRegex = re.compile(r'^Hello') mo1 = beginsWithHelloRegex.search('Hello there!') # print(mo1) # Will not work mo2 = beginsWithHelloRegex.search('Are you there? Hello!') # print(mo2) # $ at the end to check for pattern at the end endsWithWorldRegex...
#!/usr/bin/env python3 import tkinter as tk class CountChar(tk.Tk): def __init__(self): super().__init__() self.label = tk.Label(self, text="Text:") self.label.grid(row=0, column=0) self.string = tk.Entry(self) self.string.grid(row=0, column=1) self.count = tk.B...
# Exercise 27. Memorizing Logic list = ['and', 'or', 'not', '!=(not equal)', '==(equal)', '>=(greater-than-equal)', '<=(less-than-equal)', 'True', 'False'] print "These are the Truth Terms:" for item in list: print "* %s" % item print "\nNOT True?" not_list = {'not False': True, 'not True': False} for...
# |> 1 Jan 1900 was a Monday. # |> Thirty days has September, # |> April, June and November. # |> All the rest have thirty-one, # |> Saving February alone, # |> Which has twenty-eight, rain or shine. # |> And on leap years, twenty-nine. # |> A leap year occurs on any year evenly divisible by 4, but not on a century unl...
# The following iterative sequence is defined for the set of positive integers: # n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # # Although it has not been proved yet (Collatz Problem), # it is thought that all starting numbers finish at 1. # # Which starting number, under one million, produces the longest chain...
a = int(input('First quarter: ')) while a > 10: a = int(input('You typed it wrong. First quarter: ')) b = int(input('Second quarter: ')) while b > 10: b = int(input('You typed it wrong. Second quarter: ')) c = int(input('Third quarter: ')) while c > 10: c = int(input('You typed it wrong. Third quart...
# from itertools import dropwhile # # with open('somefile.txt', encoding='utf-8') as f: # for line in dropwhile(lambda line: line.startswith('#'), f): # print(line, end="") from itertools import islice items = ['a', 'b', 'c', 1, 4, 10, 15] for i in islice(items, 3, None): print(i)
""" 私有属性和方法 """ class Person: __nick_name = "qinl" def __init__(self, name, age): self.__name = name self.__age = age @property def nick_name(cls): return cls.__nick_name def __play(self): if self.__age < 19: print("正在玩飞行旗") else: ...
import threading # class FizzBuzz: # def __init__(self, n: int): # self.n = n # self.start = 1 # self.cond = threading.Condition() # # # printFizz() outputs "fizz" # def fizz(self) -> None: # while self.start <= self.n: # with self.cond: # self.co...
import threading class ZeroEvenOdd: def __init__(self, n): self.n = n self.sema_z = threading.Semaphore(1) self.sema_e = threading.Semaphore(0) self.sema_o = threading.Semaphore(0) # printNumber(x) outputs "x", where x is an integer. def zero(self) -> None: for i i...
import sys print(sys.getdefaultencoding()) with open('somefile.txt', 'rt', encoding='utf-8') as fp: f = fp.read() print(f) # with open('somefile.txt', 'rt', encoding='utf-8') as fp: # for line in fp: # print(line) # # text1 = "hello world" # text2 = "nihaoshijie" # with open('somefile.txt', 'wt'...
import time from multiprocessing import Process, Queue, Manager def producer(queue): queue.put(2) time.sleep(2) def consumer(queue): time.sleep(2) data = queue.get() print(f"{data}") if __name__=="__main__": # queue = Queue(maxsize=10) # p_producer = Process(target=producer, args=(queue,...
""" 闭包 """ def count(): fs = [] for i in range(1, 3): def f(): return i*i fs.append(f) return fs f1, f2 = count() print(f1()) # print(f2())
def parse_fasta(filename): """takes a file name with extension in the same directory as this file and returns a dict of name/seq pairs from a fasta doc""" with open("./"+filename,"r") as f: lines = f.readlines() fasta = {} for line in lines: if line[0] == ">": name = line.split(">")[1].strip() else: try...
def mario_number(level): if level == 1: return 1 elif level % 10 == 0: return 0 else: return mario_number(level//10) + mario_number(level//10//10)
# main.py, Please execute this script to run the Pokedex. import requests import json import os from texttable import Texttable import tkinter as tk from PIL import Image, ImageTk import matplotlib.pyplot as plt # Function performs the API request for information for the specified pokemon. def fetch_JSON(pokemon): ...
19. Write a program to find maximum between two numbers. SOL: num1=int(input("Enter first number:")) num2=int(input("Enter second number:")) if num1>num2: print(num1,"Num 1 is great") elif num1==num2: print(num2,"Equal") else: print(num2,"Num 2 is great")
9. Write a program to enter temperature in Fahrenheit and convert to Celsius SOL: t=int(input("Temperature in Farenheit:")) c=(t*2)*1/10 print("Temperature in C:",c,'C')
12. Write a program to enter any number and calculate its square root. SOL: import math as m num=int(input("Enter any number:")) result=int(m.sqrt(num)) print("Square root is:",result)
21. Write a program to check whether a number is negative, positive or zero. SOL: num=input("Enter any number:") if num=='0': print(num,"is ZERO") elif '-' in num: print("Negative Number") else: print("Positive Number")
4. Write a program to enter length and breadth of a rectangle and find its perimeter. SOL: num1=int(input("First Number:")) num2=int(input("Second Number:")) per=2*(num1+num2) print("Perimeter of rectangle: ",per)
1. Write a program to perform input/output of all basic data types. SOL: integer=int(input('Integer input:')) float_num=float(input("Float input:")) string=input("String input:") print(integer," ",float_num," ",string)
14. Write a program to enter base and height of a triangle and find its area. SOL: b=int(input("Enter Base:")) h=int(input("Enter Height:")) area=(h*b)*0.5 print("Area of triangle:",area)
27.Write a program to input any character and check whether it is alphabet, digit or special character. SOL: alpha=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] digit=['0','1','2','3','4','5','6','7','9','8'] sp=['!',"@",'#','$','%','^','&','*','(',')','~'] i...
67. 机器人的运动轨迹 class Solution: def judge(self, threshold, i, j): if sum(map(int,str(i)+str(j))) <= threshold: return True else: return False def findgrid(self, threshold, rows, cols, matrix, i, j): count = 0 if i<rows and j<cols and i>=0 and j>=0 and self.j...
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ max_len = 0 final_right = 0 final_left = 0 for i in range(len(s)): left = i-1 # odd right = i+1 while left >= 0 and right < len(s) and ...
from data import types class TrieNode: def __init__(self, value=None, end=False): self.value = value #maps a letter to a node containing that letter self.children = {} #a node is marked with True if it represents the end of a word even if it is not the end of a branch self.end = end ...
#! /usr/bin/env python """Solution to the AoC problem""" import os def part1(_input): """Part 1 solution implementation""" counter = {2: 0, 3: 0} for id in _input.split(): letters_count = ''.join([str(id.count(x)) for x in set(id)]) counter[2] += 1 if letters_count.count("2") else 0 ...
#!python import click import re import json import itertools @click.command() @click.option('--file', default='day13/input.txt', help='Input file path') def run(file): row_re = re.compile(r'([a-zA-Z]+) would (gain|lose) ([0-9]+) happiness units by sitting next to ([a-zA-Z]+).*') happiness = {} with click....
x = float(input('Number: ')) i = 0 while round(x, 16) != 1.6180339887498950: x = 1 + 1/x i = i + 1 print(f'{i} iteration: x = {x}')
given_list = [10, 15, 3, 7] target = 17 given_list.sort() def check(given_list): a = 0 k = len(given_list) - 1 while(a < k): if given_list[a] + given_list[k] == target: return True elif given_list[a] + given_list[k] > target: k -= 1 elif given_list[a] + give...
"""Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в нижн...
# coding=utf-8 # 根据给定的年月日以数字形式打印出日期 # raw_input: 不管用户输入什么类型,都转换成字符串 # input: 合法的python表达式(自带类型) months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] # 以1~31的数字作为结尾的列表 endings = ['st', 'nd',...
def letter_numbers(arguments): """ 不同参数类型,列表和整数 :param arguments: :return: """ if not arguments: return [] digits = [] if type(arguments) is list: for i in arguments: digits.append(str(i)) elif type(arguments) is int: digits = list(str(arguments))...
from problem1 import magic def magic_list(num): magic_list = [] magic_range = range(2, num + 1) for i in magic_range: if magic(i): magic_list.append(i) print(magic_list) return magic_list #### For testing, call the function #### magic_list(100)
def dht_hash(text, seed=0, maximum=2**10): """ FNV-1a Hash Function. """ fnv_prime = 16777619 offset_basis = 2166136261 h = offset_basis + seed for char in text: h = h ^ ord(char) h = h * fnv_prime return h % maximum def contains(begin, end, node): """Check node is containe...
# Part 1 def total_orbits(right, left): # check no element in right is there multiple times for r in right: if right.count(r) != 1: print(r) # each element in right has one direct orbit direct_orbits = len(right) # find indirect orbits step_lst = [] for i in range(len...
""" Write a function named right_justify that takes a string named s as a parameter and prints the string with enough space so that the last letter of the string is in column 70 of the display. right_justify('allen') allen """ def right_justify(col...
mass = float(input('Mass:')) velocity = float(input('Velocity:')) print("\nThe object's momentum is", (mass * velocity))
#WaitForHost def wait_for_host(): from random import randint segundos=0 while (segundos==0): segundos=randint(1,10) print(segundos) return segundos if __name__ == '__main__': print('Funcao wait_for_host(): me executou pelo terminal') else: print('Funcao wait_for_host(): me ex...
R=float(input()) area=(4/3.0)*3.14159*R*R*R print('VOLUME = %.3f'%area)
def flipit(y): str = "" for x in y: str = x + str return str y = "Hello how are you" print (y) print (flipit(y))
"""A simple implementation of a dynamic array""" import ctypes class DynamicArray: def __init__(self): self._len = 0 self.capacity = 1 self.A = self._make_array(self.capacity) def __len__(self): return self._len def __getitem__(self, k): return self.A[k] def a...
# -*- coding: utf-8 -*- with open('first.txt', 'r') as file: nucleo_1= file.read() with open('second.txt', 'r') as file: nucleo_2 = file.read().replace('\n', '') print("lenght1" , len(nucleo_1)) print("lenght2" , len(nucleo_2)) def remove_from_bigger(nucleo_1, nucleo_2): if len(nucleo_1)>len(nuc...
def list_all_factor(x): factors = [] for i in range(1, int(x/2)+1): if x % i == 0: factors.append(i) return factors num = input("number to find factors: ") print(list_all_factor(int(num)))
"""Nested List and more.""" nested_list = [["A", "B", "C"], ["X", "Y", "Z"]] print(nested_list[0][1]) target = {'list_a': ['a1', 'a2', 'a3'], 'list_b': [ 'b1', 'b2'], 'dict_c': {'c1': ['c1-1', 'c2-2'], 'c2': 'c2-1'}} # try to access a1 print(target['list_a'][0]) # try to access b1 print(target['list_b'][1]) # tr...
# -*- coding: utf-8 -*- """ Created on Sat Nov 3 13:56:31 2019 @author: Shashwat Kathuria """ # Lazy Select Algorithm # Importing required library import random N = None def main(): global N # Reading input file of 1-N numbers each distinct and appears once exactly inputFile = open("LazySelectInput.txt"...
# -*- coding: utf-8 -*- """ Created on Sat Nov 18 20:56:13 2019 @author: Shashwat Kathuria """ # Chocolate Partition Problem PTAS Algorithm # PTAS = Polynomial Time Approximation Scheme # Importing required libraries from itertools import combinations import time def main(): # Opening input file inputFile ...
# -*- coding: utf-8 -*- """ Created on Thu Jul 5 15:22:57 2018 @author: Shashwat Kathuria """ # DIJKSTRA'S ALGORITHM # This program is for a directed graph edges = [] startVertex = 1 noOfVertices = 200 # Initiaizing conquered territory with start vertex, which is vertex number 1 visitedVertices = ...
# -*- coding: utf-8 -*- """ Created on Thu Oct 5 19:29:57 2017 @author: wilson """ '''LOOPS''' people=['john','wilson','peter','james'] #for Loop for i in people: print('Current person: '+i) '''Iterate by seq index''' for i in range(len(people)): print('current person: '+ people[i]) '''Iterate usi...
""" A unittest for Transformer class """ import unittest from Transformer import Transformer class TestTransformer(unittest.TestCase): def setUp(self): pass def testSpecialRuleOne(self): t1 = Transformer('Bluestreak, A, 7,4,4,4,4,4,4,4') t2 = Transformer('Predaking, D, 10, 5, 0, 8, 7, 9, 9, 8') t1.battle(t2...
import pygame from pygame.locals import * class textInput(): def __init__(self, screen): self.text = "" self.screen = screen self.color = (255, 255, 255) self.size = (20, 650, 1000, 235) self.info = pygame.font.SysFont("monospace", 50) ...
################################################################################ ## ## JUEGO DE AJEDREZ ## ## Autor: Eduardo Molina ## ## Este programa va a imitar un videojuego de ajedrez ## Tablero -> casillas 64 -> cordenadas y sus estados de ocupación ## Piezas->estado->valor->cordenadas->movimiento/comer/morir->ti...
from creative_ai.utils.print_helpers import ppGramJson class BigramModel(): def __init__(self): """ Requires: nothing Modifies: self (this instance of the NGramModel object) Effects: This is the NGramModel constructor. It sets up an empty dictionary as a...
""" //--------------------------------------------------------------- // File: visualAnalysisFunctions.py // Purpose: Holds functions used for graphical analysis // Programming Language: Python // Author: Basit Balogun // Version: 1.0 //--------------------------------------------------------------- """ import pandas ...
# update the fucntions to count number of number(whole, decimal and fractions) # in article.txt # use regex to match numbers and fractions import re def count_numbers(text): """ counts whole number and decimals i.e -ve and +ve whole numbers decimals TODO update doc strings """ pass #TODO u...
import string, sys, random import mathFunctions, detectEnglish # Get all the ASCII characters. SYMBOLS = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" def ask_for_choice(): """ Get the user's option: - 'b' to try all of the possible combinati...
def read(str_file_path): ''' Get all content from text file path :param str_file_path: text file path :return: content from text file path ''' file = open(str_file_path, 'r') text = file.read() file.close() return text def write(str_file_path, content): ''' Write content dat...
# -*- coding: utf-8 -*- INDEX1 = "index1.txt" INDEX2 = "index2.txt" index1 = set() index2 = set() print "reading index1" with open(INDEX1) as f: for line in f: index1.add(line.strip()) print "reading index1 done" print "reading index2" with open(INDEX2) as f: for line in f: index2.add(line.s...
''' n = int(input("Digite um número: ")) for x in range(0, n+1): print(x) print("Fim") ''' ''' inicio = int(input("Digite um número: ")) final = int(input("Digite um número: ")) passo = int(input("Digite um número: ")) for x in range(inicio, final+1, passo): print(x) print("Fim") ''' s = 0 for x in range(0, 4):...
lista = [] while True: continuar = str(input("Quer continuar ? S ou N ")).upper() if continuar == "S": lista.append(int(input("Digite um número: "))) else: if continuar == "N": break par = [] impar = [] for x in range(0, len(lista)): if lista[x] % 2 == 0: par.append(...
''' sexo = "M" while sexo == "M": sexo = str(input("Informe seu sexo M ou F: ")).upper().strip() if sexo == "M": print("Você é Homem") break elif sexo == "F": print("Você é mulher") break else: sexo = "M" ''' #Correção. sexo = str(input("Informe seu sexo: [M/F] "...
#Fazer uma lista ''' numeros = list(range(4, 11)) print(numeros) nomes = ["Rogi", "Thiago", "Maria", "Carlos"] print(nomes) ''' #------------------------------------------------- #Alterar a ordem da lista: numeros2 = ["2", "4", "1", "3", "5"] print(numeros2) print("_" * 50) #A função sort() ordena a lista de números em...
numero = int(input("Digite um número inteiro: ")) print("#" * 20) print("Bases de conversão") print("1 - para binário") print("2 - para octal") print("3 - para hexadecimal") print("#" * 20) base = int(input("Escolha a base de conversão: ")) if base == 1: print("Escolheu a base 1") elif base == 2: print("Escolh...
def fatorial(n, show=False): ''' Calcula o fatorial de um numero. Uso: fatorial(numero, show=True) Param n: e o numero que vc quer descobrir o fatorial. Param show: (opcional) Mostrar ou nao a conta. return: O valor do Fatorial de um número n. ''' f = 1 for c in range(n, 0, -1): ...
numero = int(input("Digite um número: ")) total = 0 for x in range(1, numero + 1): if numero % x == 0: print("\033[33m", end=' ') total += 1 else: print("\033[34m", end=' ') print('{} '.format(x), end=' ') print("\n\033[mO número {} foi divisivel {} vezes".format(numero, total)) if total == ...
def get_valid_contiguous_set(numbers, total): for length in range(2, len(numbers)+1): for offset in range(len(numbers)-length+1): contiguous_set = numbers[offset:offset+length] if sum(contiguous_set) == total: return contiguous_set with open("input.txt", "r") as file: numbers = list(map(int, file.read()....
#!/usr/bin/python3 #-*-coding: utf-8-*- from . import lista import re from sys import argv as argv def zapisz(inputstr=""): if __name__ == "__main__": if(len(argv) < 2): return string = argv[1] else: string = inputstr arr = re.findall('\d', string) for d in arr: ...
# Write some code to complete each task. # Task 1: Make a variable that contains the value 9, and print it # Task 2: Make two variables and check whether they are the same # Task 3: Check whether the two previous variables are NOT the same # Task 4: Print all the numbers from 0 to (and including) 10, without typ...