text
stringlengths
37
1.41M
# 변수명 규칙 # - 문자, 숫자, (_) 가능. 단, 숫자로 시작할 수 없음 # - 대/소문자 구별. # - 예약어 사용 불가능 ######################### ## 수치형: int,Long,float, complex ## ######################### a = 123456789 print(a)# 123456789 print(type(a)) #<class 'int'> ## 연산자(+,-,*,/,//,%) a = 3 +4 print(a) b = 7 - 10 print(b) c = 7 * -3 print(c) d = 30 //...
# 한 함수안에 여러개의 ruturn 배치 가능 def my_arg1(arg): if arg < 0 : return arg * -1 else: return arg # 주의 필요 def my_arg2(arg): if arg < 0: return arg * -1 else: return result = my_arg2(-1) print(result) result = my_arg2(0) print(result) # return을 실행하지 못하고 함수가 종료되면 ...
def hello(): return "hello world" def factorize(value): powers = [] for i in range(2, value): while value % i == 0: powers.append(str(i)) value /= i return '*'.join(powers) def is_prime(value): import math for i in range(2, int(math.sqrt(value))): if v...
n = int(input('Enter any value: ')) i = 2 nn = 1 while i <= n: i *= 2 nn += 1 print(nn - 1, i // 2)
a = int(input("Students in Class 1: ")) # Class 1 b = int(input("Students in Class 2: ")) # Class 2 c = int(input("Students in Class 3: ")) # Class 3 print("Need to buy desks:", a // 2 + b // 2 + c // 2 + a % 2 + b % 2 + c % 2)
class Stack(): def __init__(self): self.items = [] def is_Empty(self): '''判空''' return self.items == [] def push(self,item): '''入栈''' self.items.append(item) def pop(self): '''出栈''' return self.items.pop() def peek(self): '''返回栈顶元素''...
#Program that searches for a tweet matching #the term given and prints out the username and their tweet from twython import TwythonStreamer from auth import ( consumer_key, consumer_secret, access_token, access_token_secret) #on_success code runs when a matching tweet is found class myStrea...
alphabet = [ letter for letter in range(ord('a'), ord('z') + 1) ] def transform(letter, key): ord_letter = ord(letter) first_letter = alphabet[0] if (ord_letter in alphabet): transleted = ( (ord_letter + self.key - first_letter) % len(alphabet) )+first_letter return chr(transleted)...
print("W h a t s y o u r n a m e??", end=' ') name = input() print("H o w o l d a r e y o u ??", end=' ') age = int(input()) print("W h a t s y o u r h e i g h t ??", end=' ') height = int(input()) print("W h a t s y o u r w e i g h t ??", end=' ') weight = int(input()) print(f"S o , y o u r n a m e i s...
from sys import argv """ script, first, second, third = argv print("My first script is: " + script) print("My first variable is: " + first) print("My second variable is: " + second) print("My third variable is: " + third) """ """ script, first, second = argv print("My first script is: " + script) print("My first vari...
# поключаем из модуля sys компонент для получения значений из входящей строки from sys import argv # получаем первым значением название нашей программи, вторым - название файла для чтения script, filename = argv # открываем файл для чтения txt = open(filename, "r") # Выводим строку с названием файла print(f"Inside t...
from tkinter import * class Application: def __init__(self, master=None): self.widget1 = Frame(master) self.widget1.pack() self.msg = Label(self.widget1, text="Primeiro widget") self.msg["font"] = ("Calibri", "9", "italic") self.msg.pack () self.sair = Button(self.wi...
lista = [] totalValores = 20 for i in range(totalValores): lista.append(int(input(f"Entre com o numero {i} :-> "))) semRepetidos = set(lista) print("=================================================") print(lista) print(semRepetidos) print("=================================================") print("EOP ")
from functools import reduce def somar (x, y ): return x + y lista = [1,3,5,7,9 , 11, 13 ] soma = reduce (somar , lista) print(soma)
velMS = float(input("Entre com a Velocidade em M/S :-> ")) velKMH = velMS * 3.6 print(f"E a velocidade em M/S é :-> {velKMH:.2f}")
import math valorA = int(input("entre com Valor A :-> ")) valorB = int(input("entre com Valor B :-> ")) valorC = int(input("entre com Valor C :-> ")) delta = (valorB ** 2) - (4 * valorA * valorB) if delta < 0: print("Não existe raiz para os valores selecionados ") else: if delta == 0: print("Existe ...
lista = [] totalNotas = 10 qtdNeg = 0 somaPositivo = 0 for i in range(totalNotas): lista.append(int(input(f"Entre com o numero {i} :-> "))) for num in lista: if num > 0: somaPositivo += num elif num <= 0 : qtdNeg += 1 print("=================================================") print(lis...
""" Média Aritmética Ponderada A média aritmética ponderada é calculada multiplicando cada valor do conjunto de dados pelo seu peso. Depois, encontra-se a soma desses valores que será dividida pela soma dos pesos. """ def calculaMedia (nota1, nota2, nota3, metodo): media = 0 if metodo.upper() == 'A': m...
numero = quadrado = cubo = raiz = 0 while True: numero = int(input("Entre com o 1 numero :-> ")) if numero <= 0: break quadrado = numero ** 2 cubo = numero ** 3 raiz = numero ** (1 / 2) print(f"Quadrado :-> {quadrado}") print(f"Cubo :-> {cubo}") print(f"raix :-> {raiz}...
""" criando a sua propria versão de Lupe ==================================================================================================================== for num in [1,2,3,4,5,6]: print(num) for letra in 'Geek University': print(letra) ======================================================================...
def e_primo(num): if num < 2: return False for i in range(2, num): if num % i == 0: return False return True final = inicio = soma = 0 while inicio <= 0: inicio = int(input("Entre com o 1 numero :-> ")) while final <= inicio: final = int(input("Entre com o 2 numero :-> ")) c...
peso = float(input("Entre com o PESO da pessoa :-> ")) altura = float(input("Entre com a altura da pessoa :-> ")) imc = peso / (altura**2) mensagem = "" if imc <= 18.5: mensagem = "Abaixo de O Peso " elif 18.6 <= imc <= 24.9 : mensagem = "Saudável" elif 25 <= imc <= 29.9: mensagem = "Peso em Excesso" eli...
contador = 1 valor1 = int(input("Entre com o 1 numero :-> ")) while contador <= valor1: if valor1%contador == 0: print(f" E o numero {valor1} é divisivel por {contador}") contador += 1
""" Módulo Collections - Named Tuple * São tuplas diferenciadas onde eespecificamos um nome para a mesma e também parametros ==================================================================================================================== review tupla = (1,2,3) print(tupla) print(tupla[0]) ===================...
import random matrizUm = [] matrizDois = [] matrizTres = [] linhaAtualUm = [] linhaAtualDois = [] linhaAtualTres = [] linhas = 4 colunas = 4 print("=================================================") print(f'Preenche todos os valores para a matriz A e Matriz B [{linhas},{colunas}]') for i in range(linhas): for j ...
lista = [] totalValores = 8 valorX = 0 valorY = 0 for i in range(totalValores): lista.append(int(input(f"Entre com o numero {i} :-> "))) print("=================================================") print(lista) print("=================================================") valorX = int(input(f"Entre com a Posicao X :-...
""" Crie uma classe Agenda que pode armazenar 10 pessoas e seja capaz de realizar as seguintes operações: * void armazenaPessoa(String nome, int idade, float altura); (OK) * void removePessoa(String nome); ...
totalNumeros = 10 vetorInicial = [] print("**********************") for i in range(totalNumeros): vetorInicial.append(int(input(f"Entre com o numero {i} inteiro para o Vetor :-> "))) print("=================================================") print("Vetor Inicial ") print("========================================...
tempCelcius = float(input("Entre com a Temperatura em ºc :-> ")) tempKelvim = tempCelcius + 273.15 print(f"E a temperatura éem Kelvim é :-> {tempKelvim:.2f}")
baseMaior = float(input("entre com a base Maior:-> ")) baseMenor = float(input("entre com a Base Menor :-> ")) altura = float(input("entre com a Altura :-> ")) if baseMenor > 0 and baseMaior > 0 and altura > 0: area = ((baseMenor + baseMaior)* altura)/2 print("E o valor da área do Trapezio :-> " + str(area))
velKMH = float(input("Entre com a Velocidade em KM/H :-> ")) velMilhas = velKMH / 1.6 print(f"E a velocidade em Milhas/hora :-> {velMilhas:.2f}")
# -*- coding: cp1252 -*- nomeArquivo = input(f'Entre com o nome de O Arquivo :-> ') try: with open(nomeArquivo, 'r') as arquivo: linhas = arquivo.read() novo = linhas.replace('a', '*').replace('A', '*').replace('a', '*').replace('E', '*').replace('e', '*').replace( 'I', '*').replace('i'...
resist1 = resist2 = resistencia = 0 while True: resist1 = int(input("Entre com o valor do Resistor 1 :-> ")) resist2 = int(input("Entre com o valor do Resistor 2 :-> ")) if resist1==0 or resist2 ==0: break resistencia =(resist1*resist2) / (resist1 + resist2) print(f"E o valor da resistencia...
vetorUm = [] vetorDois = [] vetorIntersec = [] totalNumeros = 6 for n in range(totalNumeros): print("**********************") numero = 0 while numero <= 0: numero = int( input(f"Entre com o numero {n + 1} inteiro e maior que Zero para o Vetor 01 :-> ")) vetorUm.append(numero) numero = 0...
totalNumeros = 15 matrizFinal = [] linhaAtual = [] linhas = 4 colunas = 4 contaMaio10 = 0 print("**********************") for i in range(linhas): for j in range(colunas): valor = int(input(f'Entre com elemento [{i}][{j}] :=-> ')) linhaAtual.append(valor) if valor > 10 : contaMaio...
import random matrizFinal = [] linhaAtual = [] linhas = 4 colunas = 4 maior = 0 posXmaior = 0 posYmaior = 0 print("**********************") for i in range(linhas): for j in range(colunas): # valor = int(input(f'Entre com elemento [{i}][{j}] :=-> ')) valor = random.randint(0,1000) print(f'En...
""" 44 - Leia um número positivo do usuário, então, calcule e imprima a sequência Fibonacci até o primeiro número superior ao número lido. Exemplo: se o usuário informou o número 30, a sequência a ser impressa será: 0 1 1 2 3 5 8 13 21 34 """ soma = 0 num_atual = 0 num_anterior = 1 sequencia = [0, 1] numer...
base = int(input("Entre com a Base :-> ")) loga = int(input("Entre com o LOgaritmando :-> ")) if base > 1 and loga > 0: novo=loga log1=0 while novo != 1: novo = novo / base log1 = log1 + 1 print (f"o LOG de {loga} na base {base} é :-> {log1} ") else: print("A base tem quie ser ma...
""" funções com parametro de entrada * Funções que recebem dados para ser processados dentro da mesma * Funções podem ter N parametros de entarda. podemos receber tantos parametros quanto necessários, separados por " , " Se a gente pensar em qualquer programa, geralmente temos entrada -> processamento -> s...
custoFabrica = float(input("Entre com o custo de Fabrica do Veiculo :-> ")) distribuidor = 0 impostos = 0 if custoFabrica <= 12000: distribuidor = 5 impostos = 0 elif 12001 <= custoFabrica <= 25000: distribuidor = 10 impostos = 15 elif custoFabrica > 25000: distribuidor = 15 impostos = 20 va...
class Elevador: pessoas = 0 andar_atual = 0 def __init__(self, andares, capacidade): self.__andares = andares self.__capacidade = capacidade def entra(self): if Elevador.pessoas < self.__capacidade: Elevador.pessoas += 1 return f'Entrou uma pessoa no ele...
vetor1 = [] vetor2 = [] vetor3 = [] for n in range(1, 11): n1 = int(input(f'Informe o valor {n} do primeiro vetor: ')) vetor1.append(n1) # posição par do vetor 3 vetor3.append(n1) n2 = int(input(f'Informe o valor {n} do primeiro vetor: ')) vetor2.append(n2) # Posição ímpar do vetor 3 ...
lista = [] listaPar = [] totalValores = 10 totalPares = 0 for i in range(totalValores): lista.append(int(input(f"Entre com o numero {i} :-> "))) if lista[i] %2 == 0 : listaPar.append(lista[i]) totalPares += 1 print("=================================================") print(f"A quantidade de ...
""" Progamação Orientada à Objetas - POO - Classes: nada mais são do que modelos dos objetos do mundo real sendo representados computacoinalmentes Imagine que vc queira criar um sistyema automatizado para controle de lampadas de um ambiente classes podem contar: - Atributos -> representam as caracteristicas do Ob...
numBase = 0 counter = 0 atual = 0 proximo = 1 temp = 0 while numBase <= 0: numBase = int(input("Entre com o 1 numero :-> ")) while True : print(atual) temp = atual + proximo atual = proximo proximo = temp counter += 1 if atual > numBase: break print("===================================...
def validarHora(hora): horaSeparada = hora.split(":") if 0 <= int(horaSeparada[0]) < 24 and 0 <= int(horaSeparada[0]) < 60: return True else: return False Entrada = input("Entre com a hora de entrada no formado HH24:MM :-> ") Saida = input("Entre com a hora de saida no formado HH24:MM :-> ...
tempFhr = float(input("Entre com a Temperatura em ºf :-> ")) tempCelcius = 5 * ( ( tempFhr -32 )/9 ) print(f"E a temperatura éem Celcius é :-> {tempCelcius:.2f}")
def triangulo_vertical(altura=6): cont_espaco = 0 base = 2 * altura + 1 # Como sabemos que o triângulo sempre aumentará em 2, o número de # asteriscos da linha seguinte, defini o incremento do for # no valor 2 for i in range(1, base, 2): # Fórmula para determinar a quantidade de espaços...
class Solution: def __init__(self): self.count = 0 ''' 这个问题转换成一个一位数组,查看 p + q == x + y or p - q == x - y In this problem, whenever a location (x, y) is occupied, any other locations (p, q ) where p + q == x + y or p - q == x - y would be invalid. We can use this information to keep trac...
class QuickSelect: def __init__(self, A): self.A = A def quickSelect(self, start, end, k): ''' QuickSelect的核心是partition方法 每次partition之后,要判断pivot的位置 ''' i, j = start, end while True: pivot = self.partition(i, j) if pivot == k - 1: ...
class Node: def __init__(self, number): self.edges = [] self.number = number class Edge: def __init__(self, node, cost): self.node = node self.cost = cost class Test: def getShortestCostNode(self, root): ''' stack: 用来保存节点的边 visited: 用来保存该节点是否visited ...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode 这里注意[1,1,2,2]这种情况 """ if not head...
class MovingAverage: def __init__(self, size): import Queue self.size = size self.q = Queue.Queue() self.sum = 0 def next(self, val): if self.q.qsize() < self.size: self.q.put(val) self.sum += val return (self.sum * 1.0) / self.q.qsize...
class Solution: def threeSumSmaller(self, nums, target): ''' 解题思路和3SUM一样,也是先对整个数组排序,然后一个外层循环确定第一个数,然后里面使用头尾指针left和right进行夹逼, 得到三个数的和。如果这个和大于或者等于目标数,说明我们选的三个数有点大了,就把尾指针right向前一位(因为是排序的数组, 所以向前肯定会变小)。如果这个和小于目标数,那就有right - left个有效的结果。为什么呢?因为假设我们此时固定好外层的那个数, 还有头指针left指向的数不变,那把尾指针...
// Recursion Solution class Solution: def isMatch(self, s, p): if not p: return not s if p[-1] == '*': if s and (s[-1] == p[-2] or p[-2] == '.'): return self.isMatch(s, p[:-2]) or self.isMatch(s[:-1], p) else: return self.isMatch(...
#!/usr/bin/env python3 """ Parses the HTML Response from the Twitter Search page """ from sys import stderr from pyquery import PyQuery class TweetParser: """ Parses the HTML Response from the Twitter Search page """ @staticmethod def create_dict(tweet): """ Formats a PyQuery p...
# -*- coding: utf-8 -*- """ Created on Fri Aug 17 19:03:06 2018 @author: GEAR """ # python stack 实现 class Stack(): #初始化栈为空列表 def __init__(self): self.__items = [] #判断栈是否为空,返回布尔值 def is_empty(self): return self.__items == [] #返回栈顶元素 def peek(self): return self.__items[...
# -*- coding: utf-8 -*- """ Created on Fri Aug 17 19:47:20 2018 @author: GEAR """ from Queue import * def hotPotato(namelist, num): simqueue = Queue() #创建空队列 for name in namelist: simqueue.enqueue(name) #将参数全部入队列 while simqueue.size() > 1: for i in range(num): #假设队首的人拿着东西,先将其...
str="" found=0 while True: i=input("enter a friends name: ") str+=i+" " c=input("have more friends? ") if(c=="no"): break l=str.split() s=input("search which friend? ") for f in range(len(l)): if(l[f]==s): print("friend found at",f) found=1 break if(found==0): pri...
cont=1 num=0 false=0 while cont==1 : str=input("Enter a number: ") try: num=int(str) except: false=1 if num>0 and false==0: print("Number entered is:",num) elif false==1: print("not a number") cont=int(input("do you want to continue: ")) false=0 print("Program...
l=list() while True: i=input("Enter a number: ") if(i=="done"): break try: l.append(float(i)) except: print("wrong input") print("Average:",sum(l)/len(l))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: if not p or not q: return p == q return p.val == q.v...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def generateTrees(self, n: int) -> List[TreeNode]: if n == 0: return [] return self.helper(1, n) def he...
transdict={'G':'C','C':'G','T':'A','A':'U'} dna=list(raw_input("Enter the strand value : ")) #checks if the value is in list or not and if not then prints x for node in dna: if node.upper() in transdict: print transdict.get(node.upper()) else: print 'X'
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'] def count(): strings = raw_input() length = len(strings) chars = 0 for i in alpha: if(strings.count(i)%2 != 0): chars += 1 if((chars == 0) and (length%2 == 0)): print "YES" if(chars == 1)...
import sys def substringafter(string, after, offset=0): if (after.lower() in string.lower()): return string[string.lower().index(after.lower()) + len(after) + offset:] return string def substringbefore(string, before, offset=0): if (before.lower() in string.lower()): return string[:strin...
def half(entStr): evens = "" odds = "" if len(entStr) % 2 ==0: for i in range(len(entStr)/2-1, -1,-1): evens = entStr[i] + evens print evens if not (len(entStr) % 2 ==0): for i in range((len(entStr)-1)/2,-1, -1): odds = entStr[i] + odds print o...
# this funciton takes two argument # one is the picture path used to upload picture to drop on the canvas # another one is the path used to save the final picture import random def turtleImage(pictPath,savePath): # 1. create an image with random drawing # 2. use the random drawing image as the background ...
# this program is to create a pink flower using turtles of 3 subclasses def patternTurtle(filename): # what makeWorld makes isn't pictures therefore cann't be written to disk # use makeEmptyPicture here for saving later world = makeEmptyPicture(1000,1000) # first turtle draws green leaves, belongs to ...
filename = 'my_checkbook_plus.txt' #Check if file exists import os.path from os import path if not path.exists(filename): with open(filename, 'w') as f: f.write(f'0 , {transaction_time} , starting balance') # Timestamp function from datetime import datetime def transaction_time(): dateTimeObj = dat...
kata = input("masukan kata ") panjang=len(kata) satu = round(1/3 * panjang) dua = round(2/3 * panjang) print("panjang : ",panjang) for k in range(0,satu): print(kata[k],end='') print(",",end='') for k in range(satu,dua): print(kata[k],end='') print(",",end='') for k in range(dua,panjang): print(kata[k],...
def conversor(tipo_moneda, valor_dolar): quetzalez = input("¿Cuántos " + tipo_moneda + " tienes?: ") quetzalez = float(quetzalez) dolares = quetzalez / valor_dolar dolares = round(dolares, 2) dolares = str(dolares) print("Tienes $ " + dolares + " dolares") menu = """ Bienvenido al conversor de ...
num1=int(input("enter value for num1")) num2=int(input("enter value for num2")) num1+=1 num2*=2 print(num1,",",num2)
start = 2 end = 20 for i in range(start, end): for j in range(2, i): if (i % j == 0): break else: print(i)
lst=[1,2,3,4] element=int(input("enter element")) lst.sort() low=0 upp=len(lst)-1#3 while(low<upp):#0<3,1<3 total=lst[low]+lst[upp]#5,6 if(total==element):#6==6 print("pairs=",lst[low],lst[upp])#2,4 break elif(total>element): upp=upp-1 elif(total<element):#5<6 low=low+1...
#binary search # lst=[1.2,3,4,5,6] # ele=int(input("enter element")) # task=[i for i in lst if i==ele] # print(task)
f=open("cat","r") lst=[] for lines in f: line=lines.rstrip("\n") words=line.split(" ") for word in words: for char in word: lst.append(char) print(lst)
class Parent: def m1(self): print("inside parent") class Child(Parent): def m2(self): print("inside child") class subChild(Child): def m3(self): print("inside subchild") sb=subChild() sb.m3() sb.m2() sb.m1() sb2=Child() #sb2.m3()//error sb2.m2() sb2.m1() p=Parent() # p.m3() //er...
import re mob=input("enter mob no") #rule="[0-9]{10}" #rule="\d{10}" rule='(91)?\d{10}' match=re.fullmatch(rule,mob) if(match==None): print("invalid") else: print("valid")
num1=int(input("enter value for num1")) flg=0 for i in range(2,num1): if(num1%i==0): flg=1 break else: flg=0 if(flg>0): print("not prime") else: print("prime")
import datetime class Bank: def createAccount(self,acno,personname,bname,balance): self.acno=acno self.person_name=personname self.bank_name=bname self.balance=balance def deposit(self,amount): self.balance+=amount print("your",self.bank_name,"has been credited w...
lst=[10,11,12,13,14,15,16,17] search=int(input("serach element")) flg=0 for item in lst: if(item==search): flg=1 break else: flg=0 if(flg>0): print("element found") else: print("element not found") # or # # # piu=[2,4,5,8,10,1,3,5,7,9] # search=int(input("search element...
class Student: def __init__(self,rol,name,course,total): self.rol=rol self.name=name self.course=course self.total=total def printStudent(self): print("rol no=",self.rol) print("name=",self.name) print("course=",self.course) print("total=",self.to...
lst=[1,2,2,2,4,4] num=int(input("enter number")) count=0 for item in lst: if(item==num): count+=1 print(count)
# plot throughput import numpy as np import matplotlib.pyplot as plt plt.rcdefaults() n = 3 throughput = (9.73, 5.69, 3.10) hop = ('1', '2', '3') y_pos = np.arange(len(hop)) width = 0.35 fig, ax = plt.subplots() rects = ax.bar(y_pos, throughput) ax.set_ylabel('End-to-end tihroughput (Mbits/sec)') ax.set_xlabel('Num...
import datetime import calendar def findDay(date): born = datetime.datetime.strptime(date, '%d %m %Y').weekday() return (calendar.day_name[born]) date = input("Enter your date: ") print(findDay(date))
''' Algorithms - Practical No.: 1 - Rod Cuttting Problem Jaisal Shah - 002 - MSc. C.S. Date: 08/09/2021 ''' def rodCutting(rodLength, cutPrices): matrix = [[0 for i in range(rodLength + 1)] for j in range(rodLength + 1)] for i in range(1, rodLength + 1): for j in range(1, rod...
import read_file #calculate variance def calc_variance(series): return sum([(item-series.mean())**2 for item in series])/len(series) #caculating covariance def calc_covariance(x,y): x_mean=x.mean() y_mean=y.mean() return sum([(item1-x_mean)*(item2-y_mean) for item1,item2 in zip(x,y)])/len(x) #cacula...
""" intervaltree: A mutable, self-balancing interval tree for Python 2 and 3. Queries may be by point, by range overlap, or by range envelopment. Interval class Copyright 2013-2014 Chaim-Leib Halbert Modifications copyright 2014 Konstantin Tretyakov Licensed under the Apache License, Version 2.0 (the "License"); you...
import json import csv def parse_tweets(number_of_lines, file_name): print("Calculating reply relations...") network = {} # This is a dictionary where all reply relations between users will be stored. def insert_user(id_str, screen_name=None): # A function which ... if id_str not in network: ...
# modules are built-in codes from python standard library # import the random and string Modules import random import string # Utilize the string module's custom method: ".ascii_letters" print(string.ascii_letters) # Utilize the random module's custom method randint for x in range(10): print(random.randint(1, 10)...
# Nice shortcuts: # Ctrl + R = Replace # Ctrl + F = Find # Ctrl + D = Duplicate line # Ctrl + / = Comment block of lines # Statistics Training # You can find this on: HackerRank -> Challenges (Tutorials) -> 10 Days of Statistics # This is: Day 2 - Basic Probability print("---------- Task 1 ----------") # In ...
""" Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line. """ # Complete the plusMinus function below. def plusMinus(arr): pos = neg = zer = 0 tot = len(arr) for i in range(0, tot): if...
""" Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers. For example, arr[1,3,5,7,9]. Our minimum sum is 1+3+5+7=16 and our maxi...
# c05ex12.py # Future value with formatted table. def main(): print("This program calculates the future value of an investment.") print() principal = float(input("Enter the initial principal: ")) apr = float(input("Enter the annualized interest rate: ")) years = int(input("Enter the number ...
# c08ex04.py # Syracuse sequence # Note: Let me know if you find a starting value that doesn't go to 1 :-). def main(): print("This program outputs a Syracuse sequence\n") n = int(input("Enter the initial value (an int >= 1): ")) while n != 1: print(n, end=' ') if n % 2 == 0: ...
from graphics import * def main(): win = GraphWin() win.setCoords(-5,-5, 5,5) # draw the contour of the face face = Oval(Point(-5,-5), Point(5,5)) face.setOutline("black") face.setFill("beige") face.draw(win) # draw the ears rightEar = Polygon(Point(4,3), Point(3....
# c03ex04.py # Calculate distance to a lightning strike def main(): print("This program calculates the distance from a lightning strike.") print() seconds = int(input("Enter number of seconds between flash and crash: ")) feet = 1100 * seconds miles = feet / 5280.0 print() print("The li...
# c06ex11.py # Square each value in a list def squareEach(nums): for i in range(len(nums)): nums[i] = nums[i]**2 def test(): nums = list(range(10)) squareEach(nums) print(nums) test()
# average6.py def main(): fileName = input("What file are the numbers in? ") infile = open(FileName, "r") total = 0.0 n = 0 line = infile.readline().strip() while line != "": total = total + float(line) n = n + 1 line = infile.readline().strip() print("\nThe average ...