text
stringlengths
37
1.41M
# -*- coding: utf-8 -*- """ Created on Wed Feb 19 01:05:54 2020 @author: cheerag.verma """ """ """ # ============================================================================= # n = int(input()) # # row = 1 # while row<=n: # spaces = 1 # while spaces <= n-row: # print(" ",end =...
""" * * * * * * * * * * * * * * * """ n = int(input()) row = 1 while row<=n: col=1 while col<=n-row+1: print("*",end = " ") col+=1 print() row+=1
# -*- coding: utf-8 -*- """ Created on Sun Mar 8 15:35:23 2020 @author: cheerag.verma """ """ Program : Write a program to do basic string compression. For a character which is consecutively repeated more than once, replace consecutive duplicate occurrences with the count of repetitions. For e...
""" 1 22 333 4444 """ n = int(input()) row = 1 while row <= n: col=1 while col<=row: print(row,end= "") col+=1 print() row+=1
from tkinter import * import math as m tk = Tk() w = Canvas(tk, width=600, height = 600) w.pack() center_x = 300 center_y = 300 point =[ #A点 center_x, center_y - 100, #B点 center_x - int(100*m.cos(m.pi/6)), center_y + 50, #C点 center_x + int(100*m.cos(m.pi/6)), center_y + 50, #A...
import math as m class Point: def __init__(self,x1,y1,x2,y2): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 def A(self): print('A点为(%d,%d)' % (self.x1,self.y1)) def B(self): print('B点为(%d,%d)' % (self.x2,self.y2)) class Line(Point): def __init__(se...
string = list(range(100,1000)) for x in string: a = x % 10 b = ((x % 100) - (x % 10 ))/10 c = (x - (x%100))/100 if x == a**3 + b**3 + c**3: print(x)
from collections import namedtuple from typing import NamedTuple Test_car1 = namedtuple('Test_car1', ('color', 'price', 'name')) class Test_car2(NamedTuple): color: str price: int name: str test1 = Test_car1('red', 500000, 'Auto') test2 = Test_car2('black', 600000, 'BWM') print(test1, test2)
#p2_1.py import random ass = random.randint(1,10) """--- 第一个小游戏 ---""" temp=input("不妨猜一下木吉现在心里想的是哪个数字:") guess=int(temp) n=1 while True : if guess ==ass: print("啊!That's good!") print("Ass we can!!") else: if guess>ass: print("哥,大了大了~~") else: print("嘿,小了小...
from fractions import Fraction import random import re class NumCreat(object): def __init__(self, max_num): self.max_num = max_num self._interget = random.randint(0, self.max_num) self.denominator = random.randint(1, self.max_num) # 分母 self.molecule = random.randint(1, self.max_nu...
print("一个小程序") temp=input("请输入1~100之间任意一个数:") ass=int(temp) if ass>=25: print("你妹好漂亮") else: print("你大爷好丑")
#!/usr/bin/env python #Robert Feeney - @Feeney92 - C10714835@student.dit.ie #DT228B/1S #This script was crated for my MSc for Mobile Device Forensics Module. #Purpose: To hash a file or string using # - SHA-1 # - SHA-256 # - SHA-512 # - SHA-3 # Import the Necessary libraries for the s...
import time ##Hora de la computadora from threading import Thread ##Thread (hilo), para evitar el error threading.Thread import threading ##Hilos ##Metodo encargado de imprimir la cantidad de hilos que se estan ejecutando def imprimirAdios(): ##Sentencia que se va repetir durante toda la ejecucion del programa ...
from math import floor from math import log10 def isPalindrome(n): frontExponent = floor(log10(n)) backExponent = 1 front = floor((n / (10 ** frontExponent)) % 10) back = floor((n % (10 ** backExponent)) / (10 ** (backExponent - 1))) while(front == back): frontExponent -= 1 ...
def myDivision(n): prevRemainder = -1 remainder = 10 result = "" for i in range(2 * n): result += str(remainder // n) remainder = (remainder % n) * 10 if prevRemainder == remainder: return result prevRemainder = remainder return result def lon...
def isvalid(row, col, board): if 0 <= row <len(board) and 0 <= col < len(board[0]): return True else: False def checkFOund(row, col, board, word, word_index, visited, visiting): if isvalid(row,col) and not visited[row][col] and not visiting[row][col] and board[row][col - 1] == word[word_index]: visitin...
# -*- coding: utf-8 -*- """ Machine Problem 2 (Python Solution) By Group 1 of 2ECE-A Michael Jeffrey Carlos and Lei-Ann Edang Circle function accepts three input points (x,y) lying on a circle in a 2-dimensional Cartesian Plane. From this set of points, it will return the values of the center (h,k) and rad...
# 직각삼각형 # 피타고라스의 정리 활용 while True: triangle = list(map(int, input().split())) if triangle[0]==0 and triangle[1]==0 and triangle[2]==0: exit() triangle.sort() if triangle[2]**2 == triangle[0]**2 + triangle[1]**2: print("right") else: print("wrong")
# 균형잡힌 세상 import sys flag=True while flag: sentence = sys.stdin.readline().rstrip() if len(sentence) == 1 and sentence=='.': flag = False continue else: st = [] for word in sentence[:-1]: if word.isalpha() or word == ' ': continue if wo...
# program to print the given no is even or odd or not even and odd with some condition# """ in given integer if the no of even digit count is even times then print even no of odd digit count is odd times then print odd else: print not even and odd """ n=int(input()) e=0 o=0 while n>0: r=n%10 n=n//1...
#program for splitting even and odd digits and forming a num with those digits from given integer# n=int(input()) a=A=0 b=B=0 C=D=0 while n!=0: r=n%10 n=n//10 if(r%2==0): a=a+1 A=A*10+r else: b=b+1 B=B*10+r while A: r=A%10 A=A//10 C=C*10+r wh...
import math def perfectSquares(a,b): while a<=b: i=math.sqrt(a) if (i - math.floor(i)) == 0 : print(a) a+=1 u= int(input ("enter upper range : ")) l=int(input("Enter lower range : ")) perfectSquares(l,u)
"""This file contains the functions that implement the 2048-AI""" import game_simulator import random import queue class Player2048: def __init__(self, display=True, board_obj=None): """Initializes a 2048 Player that plays the game""" if board_obj: self.b = board_obj else: self.b = game_simulator.Board2...
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ s_ptr,p_ptr, last_s_ptr, last_p_ptr=0,0, -1,-1 while s_ptr<len(s): if p_ptr<len(p) and (s[s_ptr]==p[p_ptr] or p[p_ptr]=='?'): p_ptr+=1 ...
# Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def eraseOverlapIntervals(self, intervals): """ :type intervals: List[Interval] :rtype: int """ def overlapped(inte...
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ table=[0] * n if n<=2: return n table[0]=1 table[1]=2 for i in range(2,n): table[i]=table[i-1]+table[i-2] return table[n-1]
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ row_rule=[ [False for i in range(9)] for j in range(9)] column_rule=[ [False for i in range(9)] for j in rang...
#!/usr/local/bin/python3 age = 17 if age >= 18: print('Insert String') print('Insert String?') else: print('Sorry, you are not 18.') print('Come back when you are 18!')
# pip install translate from translate import Translator lang = Translator(from_lang="English", to_lang="Hindi") words = input("Write your text here, to convert it to Hindi: ") result = lang.translate(words) print(result)
import turtle turtle.shape('turtle') for i in range(1, 5): turtle.forward(90) turtle.left(90) turtle.mainloop()
import turtle turtle.shape('turtle') distance = 8 while True: turtle.forward(distance) turtle.left(90) distance += 2 turtle.mainloop()
# plot dog photos from the dogs vs cats dataset from matplotlib import pyplot from matplotlib.image import imread # define location of dataset folder = 'dogs-vs-cats/train/' # plot first few images of dogs for i in range(9): # define subplot pyplot.subplot(330 + 1 + i) # define filename filename = folder + 'dog.'...
from keras.datasets import mnist from matplotlib import pyplot as plt # load the mnist dataset (X_train, Y_train), (X_test, Y_test) = mnist.load_data() # Plotting the first four images as grayscale plt.subplot(221) plt.imshow(X_train[0], cmap=plt.get_cmap('gray')) plt.subplot(222) plt.imshow(X_train[1], cmap=plt.get...
# Feature selection is a process where you automatically # select those features in your data that contribute most # to the prediction variable or output in which you are interested. from pandas import read_csv from numpy import set_printoptions from sklearn.feature_selection import SelectKBest, f_classif, RFE from ...
# Data cleaning from os import read from pandas import read_csv from numpy import unique from urllib.request import urlopen from numpy import loadtxt # define the location of the dataset path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/oil-spill.csv' # load the dataset data = loadtxt(urlopen(path),...
# Machine learning algorithms like Linear Regression and Gaussian # Naive Bayes assume the numerical variables have a Gaussian probability distribution. # Your data may not have a Gaussian distribution and instead may have # a Gaussian-like distribution (e.g. nearly Gaussian but with outliers # or a skew) or a tota...
# Feature importance refers to a class of techniques for assigning scores # to input features to a predictive model that indicates the relative # importance of each feature when making a prediction. # We will create test dataset with 5 important and 5 unimportant features # Dataset would be created both for classif...
from typing import List """ [0, 1, 2, 2, 3, 0, 4, 2] swap_index = 7 i = 2 """ class Solution: def removeElement(self, nums: List[int], val: int) -> int: swap_index = len(nums) - 1 i = 0 while i < swap_index + 1: if nums[i] == val: nums[i], nums[swap_index] = n...
from typing import List class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: answer = [] for i in range(len(nums) - 1): target = -nums[i] numbers_set = set() for j in range(i+1, len(nums)): value = target - nums[j] ...
import random import math suits = {0:'\u2663',1:'\u2666',2:'\u2764',3:'\u2660'} ranks = {0:'2', 1:'3', 2:'4', 3:'5', 4:'6', 5:'7', 6:'8', 7:'9', 8:'10', 9:'J', 10:'Q', 11:'K', 12:'A'} def points(card_list): """Returns sum of all point values of cards in a list""" point_total = [ x.points() for x in card_list] ...
#!/usr/bin/env python3 def check_password(policy: str, password: str) -> bool: (count, letter) = policy.strip().split() (x, y) = count.split("-") # policy is password[x] == letter XOR password[y] == letter # python is 0 based so need to subtract 1 idx1, idx2 = int(x) - 1, int(y) - 1 # remove ...
def is_float(s: str) -> bool: try: float(s) return True except ValueError: return False def what_week_is_it() -> int: week = input("What NFL week number is it? ") try: week = int(week) except ValueError: raise Exception("NFL week number must be an integer") ...
import math from typing import Text para = "\My Drive\n\nVersion = v.1.1.1" #d1 = {} #d1 ["ID"] = "Name" #Enter Your Name Here or Id Which You want to use to Login. """ Add users with one comand """ #d1.update({"4585" : "Rishabh"}) #d1["Arnav"] = "Member" #p = "Enter Your ID : " #r = d1[input(p)] r = "Sir" p...
#Match all the phone numbers listed with a regular expression. import re text="555.123.4565,+1-(800)-545-2468,2-(800)-545-2468, 3-800-545-2468, 555-123-3456, 555 222 3342, (234) 234 2442, (234)-234-2342, 1234567890, 123.456.7890, 123.4567, 123-4567, 1234567900, 12345678900" p=re.findall(r'\+?\d?\-?\(?\d{...
# String Exercise 1 ''' # q3) Create a program that outputs the inputted string backwards. user_input = input('Enter a word: ') print(user_input[::-1]) # [::-1] slicing helps us to reverse a string # Create a program such that it determines if there are more vowels than consonants in the given inputted strin...
def count_upper_case(message): count = 0 for c in message: if c.isupper(): count += 1 return count assert count_upper_case("") == 0 "Empty string" assert count_upper_case("a") == 0 "It is not an capital letter" assert count_upper_case("A") == 1 "One upper case"
''' Created on 23/01/2020 @author: Marvin Senjaliya ''' ''' Problem statement: Write a program to draw a scatter plot for a given dataset and show datalabels on hover https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv ''' import plotly.express as ply import pandas as pd dataFrame=pd.read_csv(...
''' Created on 23/01/2020 @author:Marvin Senjaliya ''' ''' Problem statement: Write a Python program to draw a scatter plot for three different groups camparing weights and heights ''' from matplotlib import pyplot as plt import numpy as np weight1=np.random.randint(1,60,20) weight2=np.random.randint(1,60,20) weight3=...
''' Created on 23/01/2020 @author: Marvin Senjaliya ''' ''' problem statement: Write a Python programming to create a pie chart with a title of the popularity of programming Languages. Sample data: Programming languages: Java, Python, PHP, JavaScript, C#, C++ Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7 ''' from matplotli...
""" Created on 1/23/2020 @author:Marvin Senjaliya """ """ problem statement: Write a Python program to draw a line using given axis values with suitable label in the x axis , y axis and a title """ from matplotlib import pyplot as plt x=[1,2,3] y=[5,6,1] plt.xlabel('x-axis') plt.ylabel('y-axis') plt.title('line') pl...
""" Created on:1/21/2020 @author:Marvin Senjaliya """ """ problem statement: 5. Write a Python program to create a 2d array with 1 on the border and 0 inside. Expected Output: Original array: [[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]] 1 on the border and 0 insi...
""" Created on:1/21/2020 @author : Marvin Senjaliya """ """ problem statement: Write a Python program to append values to the end of an array. Expected Output: Original array: [10, 20, 30] After append values to the end of the array: [10 20 30 40 50 60 70 80 90] """ import numpy as np a=[10 ,20, 30] a=np.append(a,...
""" Created on:1/22/2020 @author:Marvin Senjaliya """ """ problem statement: Write a Python program to get the powers of an array values element-wise. Note: First array elements raised to powers from second array Expected Output: Original array [0 1 2 3 4 5 6] First array elements raised to powers from secon...
""" Created on:1/21/2020 @author:Marvin Senjaliya """ """ Create a 3x3 matrix with values ranging from 2 to 10. Expected Output: [[ 2 3 4] [ 5 6 7] [ 8 9 10]] """ import numpy as np a=np.arange(2,11).reshape(3,3) print(a)
a = 1 num = int(input("Enter a number \n")) for i in range(1 , num+1 , 1): a *= i print(a)
import persistencia as per arquivo = "pizza.pickle" pizza = per.carregar_dados(arquivo) def cadastro_pizza(pizzas): pizza.append(pizzas) per.salvar(pizza, arquivo) def listar_pizza(): lista_pizza = per.carregar_dados(arquivo) i = 1 for nome, valor in lista_pizza: print(i) ...
import turtle def draw(t, length, n): if n == 0: return angle = 50 t.fd(length * n) t.lt(angle) draw(t, length, n-1) t.rt(2*angle) draw(t, length, n-1) t.lt(angle) t.bk(length*n) if __name__ == '__main__': t = turtle.Turtle() draw(t, 10, 6) turtle.mainloop()
import sys prices = [7,1,5,3,6,4] def maxProfit(prices): profit = 0 minPrice = sys.maxsize for value in prices: minPrice = min(value, minPrice) profit = max(profit, value - minPrice) return profit print(maxProfit(prices))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 15 19:57:04 2020 @author: ldeniz """ #import de las librerías import math import random print("\n\n********** EJERCICIO 01 **********") #utilizo la función valor absoluto y devuelvo el restulado def p1(va): va = abs(va) return va #ej...
from tools import list_minisat2list_our_sat def sat_preprocessing(num_variables, clausulas, asig): # variable flag para detectar cambio cambio = True # comienza el preprocesado while(cambio): # si la variable termina a False, termina el preprocessing cambio = False # contado...
from collections import Counter def check_criteria(number: int) -> bool: numberlist = [i for i in str(number)] #is 6 digit is_sixdigit = len(numberlist) == 6 notwithlargergroup = 2 in Counter(numberlist).values() adjacent = False nondecreasing = True ldig = numberlist[0] for rdig in...
# 45*3=555, 56+9=77, 56/6=4 def faultycalculator(): num1=int(input('enter the first number: ')) num2=int(input('enter the second number: ')) op=input('enter the operator: ') if num1 == 56 and num2 == 9 and op == '+': print(77) elif op=='+': print(num1 + num2) elif num1 == 43 and num2 == 3 and o...
''' num=eval(input("Enter your Number: ")) result=num+10 print(f"your result is : {result}") ''' def get_result(value): # parameter/positional arguments result=value+10 print(f"your result is : {result}") return None def main(): num=eval(input("Enter your Number: ")) get_result(num) # Arguments ...
''' import os req_path=input("Enter path to change the working dir : ") print("The current working dir is: ",os.getcwd()) try: os.chdir(req_path) print(" Now your new working dir is: ",os.getcwd()) except FileNotFoundError: print("Give path is not valid path. so can't change the working directory") except ...
''' fo=open(req_file,'r') csv_reader=csv.reader(fo,delimeter="|") for each in csv_reader: print(each) fo.close() ''' ''' csv_writer.writerow(['S_No','Name','Age']) csv_writer.writerow([1,"suryatheja",28]) csv_writer.writerow([2,'Chandrsmitha',25]) ''' ''' import csv req_file="demo.csv" fo=open(req_file,'w',newlin...
import re my_str="This is python language and it consists Python2 and python3 versions" #my_pat=r'python' my_pat=r"\bpython[23]?\b" #print(re.split(my_pat,my_str,maxsplit=2,flags=re.I)) #print(re.sub(my_pat,"shell",my_str,count=2,flags=re.I)) print(re.subn(my_pat,"shell",my_str,flags=re.I))
import pandas as pd import numpy as np CSV_PATH = 'datasets/PastHires.csv' df = pd.read_csv(CSV_PATH) print(df.head(8))#if no int is passed to head it will print first 5 rows other wise int rows it prints from first print(df.tail(4))#if no int is passed to tail it will print last 5 rows other wise int rows it prints f...
# -*- coding: UTF-8 -*- from Tkinter import * root = Tk() # root = Tk(className='标题') # 构件默认是在主窗口中居中按照一列排序 w = Label(root, text="Red", bg="red", fg="white") w.pack() w = Label(root, text="Green", bg="green", fg="black") w.pack() w = Label(root, text="Blue", bg="blue", fg="white") w.pack() w = Label(root, text="添加了...
from unittest import TestCase from model.position import Position from command.position_command import LeftPositionCommand from model.robot import Robot class RobotTest(TestCase): def test_position_of_robot(self): """ Sets initial position for robot """ robot = Robot(initial_posi...
def get_bullcow(guess, rand_num): # This function uses a loop to count the number of bulls first # It then counts the number of cows. But the bulls are double- # counted in the cows which are removed from the final cow count # It then prints the number of cows and bulls Bull = 0 Cow = 0 for i in r...
''' Utilitario traccar funções: .. Analisa Logs e retorna conforme função selecionada .. precisa do arquivo log.log com os logs de saída do Traccar no mesmo diretório para análise ''' import AnalisaLogs while True: print(f'Escolha a opção abaixo:.. ') print(f'1 - Posições enviadas, Top-10') print(f'2 - Co...
'''user = 2 primary colors error if input is not prmary colors ''' def color_mixing(): while True: kid1 = str(input('Primary color 1: ')) kid2 = str(input('Primary color 2: ')) if kid1 == 'red' and kid2 == 'blue': print(f" {kid1} + {kid2} = Purpl...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: node = head num = m - n + 1 #m 번째까지 이동 for i in...
# -*- coding: utf-8 -*- """ Created on Tue Nov 6 09:20:40 2018 @author: Nik """ import numpy as np tuple1 = (1,2,3,4) tuple2 = (5,6,7,8) print(f'tupel 1 is {tuple1} and tuple2 is {tuple2}') g = lambda x,y,z:list(np.arange(x,y,z)) for i in g(1,10,0.1): print(round(i,1)) class Parrot: # class attribute ...
#! python3 # backup_zip-solidifying.py - Copies an entire folder and its contents into # a ZIP file whose filename increments. import zipfile import os # Create function. def create_zipfile(folder): # Create zipfile name. number = 1 while True: zip_name = os.path.basename(folder) + '_' + str(number)...
#! python3 '''debugging_coin_toss.py - Simple coin toss game, the player has\ two guesses(simple game). The program has several bugs.\ Find bugs that keep the program from working correctly.''' # Import essential modules. import random import logging logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s,...
#! python3 # zip-solidifying.py - Copies an entire folder and its contents into # a ZIP file whose filename increments. # Import essential modules. import os import zipfile # Create function. def backup_folder(folder): # Set abspath to variable. abspath = os.path.abspath(folder) # Create zipfile name with whi...
grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ...
# imports print(""" |******************| | Desafio057 | |******************| """) print("Válidador de Sexo") print() sexo = 0 while sexo == 0 or (sexo != "F" and sexo != "M"): sexo = input("Digite seu sexo (M ou F): ").upper() if sexo == "M": sexo = "Masculino" else: sexo = "Feminino" print() pri...
print("|*****************|") print("| Desafio06 |") print("|*****************|") print("") print("Dobro, Triplo e Raiz Quadrada") num = float(input("Digite um número: ")) print("O número digitado foi {} \nSeu dobro é {} \nSeu triplo é {} \nSua raiz quadrada é {}".format(num, num*2, num*3, num**(1/2)))
print("|*****************|") print("| Desafio08 |") print("|*****************|") print("") print("Metro para centimetro e milimetro") metro = float(input("Digite um valor em metros: ")) cm = metro*100 mm = cm*10 print("Você inseriu {} metros \n{} m = {} cm = {} mm".format(metro, metro, cm, mm))
print("|*****************|") print("| Desafio04 |") print("|*****************|") print("") print("Tipo e testes de tipo") algo = input("Digite algo: ") print("Seu tipo é {}".format(type(algo))) print("É numérico? {}".format(algo.isnumeric())) print("É decimal? {}".format(algo.isdecimal())) print("É alfabético? ...
# imports print(""" |******************| | Desafio053 | |******************| """) print("A frase é um palíndromo?") frase = str(input("Digite uma frase: ")) original = frase frase = frase.upper() frase = frase.split() frase = "".join(frase) frase_reverse = "" # Gera frase invertida for i in range(len(frase)-1...
print("|*****************|") print("| Desafio09 |") print("|*****************|") print("") print("Tabuada") num = int(input("Digite um número inteiro: ")) count = 0 while count <= 10: print("{} x {} = {}".format(num, count, num*count)) count += 1
print("\033[31m|***************************|") print("| Arvore de Natal |") print("| Obs: Tamanho precisa ser |") print("| maior que 2 |") print("|***************************|") tamanho = 1 while tamanho < 3: tamanho = int(input("Qual a altura da sua arvore? \033[m")) print("\033[32m") co...
# imports print(""" |*****************| | Desafio27 | |*****************| """) print("Separador de Nomes") nome = input("Digite seu nome completo: ") nome = nome.split() print(""" Nome completo: {} Primeiro nome: {} Ultimo nome : {} """.format(" ".join(nome), nome[0], nome[len(nome) - 1]))
# imports from math import cos, sin, tan, radians print("|*****************|") print("| Desafio18 |") print("|*****************|") print("") print("Calculadora de Seno, Cosseno e Tangente") angulo = float(input("Digite o valor de um ângulo: ")) rad = radians(angulo) sen = sin(rad) cos = cos(rad) tan = tan(rad)...
num = [0, 6, 3, 8, 5, 4] # Adicionar novo item num.append(8) print(num) # Adicionar novo item em um indice específico num.insert(5, 12) print(num) # Retirar valor pelo indice num.pop(0) print(num) # Ordenar lista num.sort() print(num) # Cópia de Lista a = [10, 20, 30, 40] b = a # Ligação b = a[:] # Cópia # Ordenar l...
# imports print(""" |******************| | Desafio105 | |******************| """) print("Notas dos Alunos - Analise") print() # Funções def notas(* notas, sit=False): """ -> Função que analisa as notas e situações de vários alunos. :param notas: Uma ou mais notas dos alunos (aceitando várias) :...
print("|*****************|") print("| Desafio15 |") print("|*****************|") print("") print("Aluguel de Carros") print(); dias = float(input("Quantos dias o carro foi alugado? ")) kms = float(input("Quantos quilometros foram percorridos? ")) valor = (60*dias) + (kms*0.15) print("O total a pagar é de R$ {:...
nome = input("Qual é seu nome? ") print("Boas vindas "+nome+"!")
print("|*****************|") print("| Desafio14 |") print("|*****************|") print("") print("Converter ºC para ºF") print(); ce = float(input("Digite a temperatura em ºC: ")) fa = ((ce*9)/5) + 32 print("A temperatura de {}ºC corresponde a {}ºF".format(ce, fa))
# imports from random import randint print("JO-KEN-PÔ!") while True: print(""" ========== Qual você deseja jogar? ========== _ _ _| |_ _| | | | | |_ | | | _ _ _ _ | | | | | | | |_ _ _|...
# imports print(""" |*****************| | Desafio33 | |*****************| """) print("Qual é o maior?") nums = [] while len(nums) < 3: count = len(nums) nums.append(float(input("Digite o {}º número: ".format(len(nums) + 1)))) nums.sort(reverse=True) print() print("Maior número: {}".format(nums[0])) p...
import time x=time.time() for i in range(0,200): print('*', end='') y=time.time() print() print("{} seconds consumed".format(y-x)) x_1=time.time() s='' for i in range(0, 200): s+='*' print(s) y_1=time.time() print() print("{} seconds consumed".format(y_1-x_1))
print("Input dan.") a=int(input()) print("**********",a,"dan**********",sep='') for x in range(1, 10): print(a,"*",x,"=",a*x,sep='') print("************************") input()
a=1 #별의 개수 b=int((9-a)/2) while a<=9: for x in range(b): print(" ", end="") for x in range(a): print("*",end="") for x in range(b): print(" ", end="") print() a+=2 b=int((9-a)/2) input()
print(" moving of \"Tura\"") print("Please print x1") while True: try: x1=int(input()) break except: print("Please enter number") print("Please print y1") while True: try: y1 = int(input()) break except: print("Please enter number") print("P...
# Problem Set 2, hangman.py # Name: # Collaborators: # Time spent: # Hangman Game # ----------------------------------- # Helper code # You don't need to understand this helper code, # but you will have to know how to use the functions # (so be sure to read the docstrings!) import random WORDLIST_FILENAME = "words.t...
"""Module with Button class for Minesweeper.""" import os import pygame class Button: """Class to represent a button.""" def __init__(self, minesweeper): """Initialize button attributes.""" self.screen = minesweeper.screen self.screen_rect = self.screen.get_rect() self.sett...