text
stringlengths
37
1.41M
# for i in range(1,10): # for j in range(1,10): # print(i,"*",j,"=",i*j) # a,b=eval(input("enter two number a,b")) # while b!=0: # a,b= b,(a%b) # print(a) import random import time # i=0 # correct=0 # startTime = time.time() # for i in range(5): # a=random.randint(1,100) # b=random.randint(2,100) # p...
import math class point: def __init__(self,x,y): self.x=x self.y=y def dist(self,point): # print(point.x,point.y) dist=math.sqrt((point.x-self.x)**2+(point.y-self.y)**2) return dist def nearby(self,point): d=self.dist(point) if d <=5: pri...
pas=(input("enter your password")) dig=0 for i in pas: if ord(i)>ord('0') and ord(i)<ord('9'): # print(ord(i)) dig =dig+1 # print(len(pas),pas.isalnum(),dig) if len(pas)>8 and pas.isalnum() and dig>=2: print("valid") else: print("not valid")
mins=eval(input("enter the total minutes")) totaldays=mins/60/24 years=int(totaldays/365) days=int(totaldays%365) print(mins," is approximately", years ,"years"," ",days,"days")
x1,y1,x2,y2,x3,y3=eval(input("Enter three points for a triangle:")) side1=(((x2-x1)**2+(y2-y1)**2)**0.5) side2=(((x2-x3)**2+(y2-y3)**2)**0.5) side3=(((x3-x1)**2+(y3-y1)**2)**0.5) s=(side1+side2+side3)/2 area=(s*(s-side1)*(s-side2)*(s-side3))**0.5 print("The area of the triangle is",format(area,'10.1f'))
import sys, re class PDA: def __init__(self, string, current_stack): if string == '!': self.string = "" else: self.string = string self.current_stack = current_stack def RunRule(self, rules): """ Function to run a set of rules given the ...
from turtle import Turtle POSITION = ((-100, 275), (100, 275)) with open("./scores.txt") as score: content_score: str = score.read() class Score(Turtle): def __init__(self): super().__init__() self.score = 0 self.High_score = int(content_score) self.color("white") self...
#new age = int(input("How old are you? ")) print(">>>>>>>>>age=",repr(age)) height = input(f"You're {age} nice! How tall are you? ") weight = input("How much do you weigh? ") print(f"So,you're {age} old,{height} tall and {weight} heavy. ") #before print("How old are you?",end = ' ') age = input() print(f"So you are...
import os from collections import Counter #this opens a file full of words a_file = open(r"C:\Users\joshw\PycharmProjects\pythonProject\Files for python\pythonnumbertext.txt", "r") #this creates a list then adds all the words from the file into the list and then closes the file list_of_lists = [] for line in a_...
import sys class readFile: """Module used to read from the map file""" def readInputFile(self,filename): try: filename=filename+".txt" #print "" #print "Read Input File Module:" #print "Step3.1: Reading the...
from Tkinter import * class Application (Frame): def __init__(self,master): Frame.__init__(self,master) self.grid() self.score=0 self.res=0 self.create_widgets() def create_widgets(self): self.label=Label(self,text=" **********LETS TEST YOUR GENERA...
from task import Task, NEW, DONE, REMOVE import os, platform # Verifies platform for using the right clear command if platform.system() == "Windows": CLEAR_COMMAND = "cls" else: CLEAR_COMMAND = "clear" # Constants DIGITS = "0123456789" EXIT = "exit" CLEAR_LIST = "clear" # Main class class CTodo: # CTodo ->...
phrase = input("Enter a phrase:") new_phrase = phrase.split() new_phrase.reverse() reversed = ' '.join(new_phrase) if phrase == reversed: print("It is a Palindrome") else: print("Not a Palindrome")
''' def nota_aluno(): nota1 = float(input('Nota 1: ')) nota2 = float(input('Nota 2: ')) nota3 = float(input('Nota 3: ')) soma = nota1 + nota2 + nota3 media = soma / 3 return media ''' ''' def tamanho_lista(): n = input('Digite o tamanho ') i = 0 lista = [] while...
""" Função Zip """ """ #Criando duas listas x = [1, 2, 3] y = [4, 5, 6] #Unindo as listas.Em Python retornar iterator zip(x, y) #Perceba que o zip retorna tuplas.Neste caso, uma lista de tuplas print(list(zip(x, y))) """ #Criando 2 dicionários d1 = {'a':1, 'b':2} d2 = {'c':4, 'd':5} #Zip vai unir as chaves #print(...
# dict = {chave1: valor1, chave2: valor 2} dict = {"Rafael": 36, "Jolise": 36, "Amora": 3} print(dict) print(dict["Rafael"]) # Adicionando argumento ao dicionário dict["Pedro"] = 32 print(dict) # Imprime o tamanho do dicionário print("O tamanho do dicionário é {}".format(len(dict))) # Deletando argumento do dicion...
""" Exercício 2 - Crie uam função que receba uma string como argumento e retorne a mesma string em letras maiúsculas. Faça uma chamada à função, passando como parâmetro uma string. """ def recebe_string(texto): print(texto.upper()) return recebe_string("Rumo à Analise de Dados")
#range(start,stop,step) #Imprimindo números pares entre 50 e 101 """ for i in range (50,101,2): print(i) i += 2 """ #Usando números negativos """ for i in range (0, -20, -2): print(i) """ #Percorrendo uma lista """" lista = ["Morango", "Abacaxi", "Uva", "Banana"] lista_tamanho = len(lista) for i in range...
dicionario1 = {"Rafael": 36, "Jolise": 36} print("Dicionário 1") print(dicionario1) # Cria dicionário vazio dicionario2 = {} # Atualiza os dados do dicionário 2 com dos dados do dicionário 1 dicionario2.update(dicionario1) print("Dicionário 2") print(dicionario2)
class Road: def __init__(self, length, width): self._length = length self._width = width def calc_mass(self, mass, thickness): result = self._length * self._width * mass * thickness // 1000 print(f"Необходимо {result} тонн асфальтного покрытия") try: first_road = Road(int...
class Worker: """Создание базового класса""" def __init__(self, name, surname, position, wage, bonus): self.name = name self.surname = surname self.position = position self._income = {"wage": wage, "bonus": bonus} class Position(Worker): """Дочерний класс с методами рассче...
class IncorrInput(Exception): """Ввод некорректного значения""" def __init__(self, txt): self.txt = txt class Warehouse: """Класс склад. Реализация приёма техники и перемещения в подразделения""" equip_list = {1: 'принтер', 2: 'сканер', 3: 'ксерокс'} # Словарь id: тип техники avail_store ...
def int_func(): """Проверка - ввод только маленьких латинских букв и пробелов""" w = input("Маленькими латинскими буквами введите слово или " "слова, разделенные пробелами: ") if all(97 <= ord(i) <= 122 or ord(i) == 32 for i in w): return w.title() else: return "Введены нек...
from itertools import cycle from itertools import zip_longest # Принимает в себя список и количество повторений def func(a, b): l = [] for i in cycle(a): if b <= 0: break l.append(i) b -= 1 return l l = ['spring', 'summer', 'autumn', 'winter'] n = range(100, 107) wor...
month = int(input('Введите порядковый номер месяца(от 1 до 12): ')) if 1 <= month <= 12: if 3 <= month <= 5: print('Весна') elif 6 <= month <= 8: print('Лето') elif 9 <= month <= 11: print('Осень') else: print('Зима') else: print('Такого месяца не существует')
import random player = input("Please enter Player Name:") print("Welcome to the Game", player) print(player, "I'm Thinking of a number between 1 and 100\n") print("Try to Guess the right number\n") computer_number = random.randint(1,100) count = 1 guess = int(input("Your Guess?:")) while guess != computer_number: ...
n = int(input("n = ")) for i in range(n): print(2 * i + 1)
a = int(input("a = ")) b = int(input("b = ")) if a > 0 and b > 0 and a + b > 100: print(f"a / b = {a / b}") elif a + b < 100: print(f"a * b = {a * b}")
'''Codigo para calcular a areas de um circulo''' n = 3.14159 raio = float(input()) area = n*(raio**2) print(f'A={area:.4f}')
year = (3600*24*365) lifeyears = 1000000000/year print lifeyears if lifeyears < 100: print "He will live!" else: print "He will not live"
age=28 #message="Happy"+age+"th Birthday" #print(message) #Output: #message="Happy"+age+"th Birthday" #TypeError: must be str, not int #COMMENT: WE CAN'T ADD INTEGER IN TEXT IN PYTHON #**************************USE OF str()********************* message="Happy "+str(age)+"th Birthday" print(message) ...
def encrypt(text,m,a): result = '' for i in range(len(text)): char = text[i] if char == ' ': result += ' ' elif char.isupper(): result += chr((((ord(char)-65) * m + a) % 26) + 65) else: result += chr((((ord(char)-97) * m + a) % 26) + 97) re...
import search import insert import handleUserTable import update import delete def adminUser(): while 1: print(''' 1.查询操作(单表查询、打印全表、复杂查询) 2.建立新表/删除新表(管理员用户/普通用户表) 3.插入学生数据/选课信息/管理员用户/普通用户 4.更改学生专业信息/成绩信息/用户密码 5.删除学生相关信息/管理员用户/普通用户 ''...
import random #import random is used to pick a random element from a list, in this case choosing a number between 1 and 6 def dice_roll(): #define function gives the function a unique identifier while True: #while loop allows for the code to execute a command as long as the statement is true ...
#Count Vowels - Enter a string and the program counts the number of vowels in the text. #For added complexity have it report a sum of each vowel found. a = input ("Enter the stirng: ") print ('No of a in the string:', a.count('a')) print ('No of e in the string:', a.count('e')) print ('No of i in the string:', a.coun...
name = ['a','b','c','d','e'] find = input() if find in name: print("yes") else: print("no") for i in name: if find == i: print("yes") print(name[::-1])
nums = [] for i in range(4): nums.append(int(input())) max_ = nums[0] for i in range(1,4): if max_ <= nums[i]: max_ = nums[i] print(max_) nums.append(int(input())) max_ = nums[0] for i in range(1,5): if max_ <= nums[i]: max_ = nums[i] print(max_)
# 1) Создать переменную типа String, вывести в консоль+тип данных word = ('Alesia') print('1. Переменная word=', word, 'имеет тип', type(word)) # 2) Создать переменную типа Integer, вывести в консоль+тип данных num = 2 print('2. Переменная num=', num, 'имеет тип', type(num)) # 3) Создать переменную типа Float...
max = 1 for a in range(100): for b in range(100): n = a**b s = str(n) sum = 0 for l in s: sum += int(l) if sum>max: max = sum print max
from itertools import cycle from math import factorial def isprime(n): '''check if integer n is a prime''' # 0 and 1 are not primes if n < 2: return False # 2 is the only even prime number if n == 2: return True # all other even numbers are not primes if not n ...
from bisect import bisect def isprime(n): '''check if integer n is a prime''' # 0 and 1 are not primes if n < 2: return False # 2 is the only even prime number if n == 2: return True # all other even numbers are not primes if not n & 1: return False ...
import time def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): j = target - nums[i] if (j in nums) and (nums.index(j) != i): return [i, nums.index(j)] def sum_index(nums, target=100): start = ...
class Node(object): def __init__(self, value=None, pointer=None): self.value = value self.pointer = pointer class Stack(object): def __init__(self): self.head = None def isEmpty(self): return not bool(self.head) def push(self, item): self.head = Node(item, self.h...
import numpy as np class LinearRegressor(): def __init__(self, alpha=0.1, epochs=1): self.alpha = alpha self.epochs = epochs self.costs = [] self.theta = None def _cost_function(self, y_pred, y, m): """ Gets the cost for the predicted values when contrasted wit...
import folium from streamlit_folium import folium_static import streamlit as st import numpy as np import pandas as pd from csv import reader #------------csvファイルをリストに格納--------------- with open('list.csv', 'r',encoding="utf-8") as csv_file: csv_reader = reader(csv_file) # Passing the cav_reader obje...
import sys def normalize(string, normalized=''): def read_tail(string, normalized): if string[0] == '/': return normalize(string[1:], normalized + string[0]) elif string[0] == '.': while string[0] == '.': string = string[1:] return normalize(strin...
class Person: def __init__(self, name,age): self._name=name self._age=age @property def name(self): return self._name @property def age(self): return self._age @name.setter def name(self,name): self._name=name def play(self): if sel...
import random,sys print('ROCK','PAPER','SCISSOR') print('Plzz open Your caps lock!') #these things keep track of winning,losses and tie: wins = 0 ties = 0 loss = 0 while True: #Main loop print('%s Wins , %sLoss , %sTies' %(wins,loss,ties)) while True: #Player input loop print('Enter your move: '+ '...
numbers = input().split() print(" ".join(reversed(numbers)))
# the list with classes; please, do not modify it groups = ['1A', '1B', '1C', '2A', '2B', '2C', '3A', '3B', '3C'] # your code here kindergarten = dict.fromkeys(groups) number_groups = int(input()) # number_groups = 4 counter = 0 while counter < number_groups: kids = int(input()) # kids = 10 counter += 1 ...
""" 00. Đảo ngược xâu ký tự Hãy đảo ngược xâu ký tự "stressed" (theo thứ tự từ cuối xâu đến đầu xâu ký tự). """ def reverse_string(s): return s[::-1] if __name__ == '__main__': s = "stress" print(reverse_string(s))
# # @lc app=leetcode id=234 lang=python3 # # [234] Palindrome Linked List # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: ## 快慢指针找中间节点 ## 反转后半段 ## 比较 def isPalindrom...
# # @lc app=leetcode id=9 lang=python3 # # [9] Palindrome Number # # @lc code=start ## 倒转一半进行比较 class Solution: def isPalindrome(self, x: int) -> bool: if (x < 0) or (x % 10 == 0 and x != 0): return False revertedNum = 0 while x > revertedNum: revertedNum = reverted...
# # @lc app=leetcode id=69 lang=python3 # # [69] Sqrt(x) # # @lc code=start ## 二分查找 class Solution: def mySqrt(self, x: int) -> int: low = 0 up = x while low <= up: mid = (low + up) // 2 s = mid * mid if s == x: return mid eli...
# # @lc app=leetcode id=19 lang=python3 # # [19] Remove Nth Node From End of List # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None ## 注意边界情况 class Solution: def removeNthFromEnd(self, head: ListNode, n: int) ->...
# # @lc app=leetcode id=117 lang=python3 # # [117] Populating Next Right Pointers in Each Node II # # @lc code=start """ # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left sel...
# # @lc app=leetcode id=99 lang=python3 # # [99] Recover Binary Search Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right ## Morris遍历: ## 线索二叉树:利用叶子节点中的...
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。 给定一个整数n,请返回n位的格雷码,顺序为从0开始。 测试样例: 1 返回:["0","1"] 2 ["00","01","11","10"] 3 ['000','001','011,'010','110','111','101','100'] f(1) = ["0","1"] f(2) = ["0" + "0","0" + "1"] + ["1"+"1","1"+"...
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def HasSubtree(self, pRoot1, pRoot2): # write code here result =...
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 题目描述 统计一个数字在排序数组中出现的次数。 [1,3,5,7,9],3 -> mid = 5>3 ->r=mid [1,3,5] 3=3 r=mid [1,3],1<3 l=mid+1 [1,3,5,7,9],7 -> mid=5<7 l=mid [5,7,9] 7=mid->l=mid [7,9],9>mid r=mid-1 [1,1] mid=0,r=mid=0 [1,1] mid=1,l=mid=1 找左边界:if nums[mid]>=target R=mid else L=mid+1 找右边界:if nums[...
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。 """ def swap(arr,i,j): arr[i],arr[j] = arr[j],arr[i] def GetLeastNumbers_Solution(tinput, k): """ 选择排序 :param tinput: :param k: :return: """ # write code here n = len(t...
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ Alice made some changes to a text file and she wants to know which lines are changed and compare the before and after line contents. Can you help her with this? 输入描述: The first line contains two integers m (1<=m<=1000) and n (1<=n<=1000) – the number of lines in the...
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 题目描述 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。 """ class Solution: # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): """ 方法一 遍历一次 使用字典记录数字出现的次数 :param array: :return: """ from collectio...
import random def main(): while True: min_value = random.randint(0, 150) max_value = random.randint(75, 200) if min_value < max_value: break while True: try: input_value = int(input("Input number in range {} - {}: ".format(min_value, max_value))) ...
from tkinter import * # import module tkinter def click(): name = le.get() passw = pe.get() if name == 'samat' and passw =='qwerty': wn.destroy() # destroy wn and wn1 = Tk() # create new window wn1.geometry('400x400') # change wn1 size wn1.title("Welcome " + name+...
""" META DESCRIPTION v3.0 Input file: .csv with kw1, kw2, biz name, location, ST Output: 160 chars or less of word-replaced random combo of 1st, 2nd, 3rd sentence. Length <= 160 chars """ import random import csv firstSentence = ["Interested in KW1? ", "Looking for KW1? ", "Searching for KW1? ", "Sea...
import random import numpy as np from bag import Bag from bagfacility import BagFacility from customer import Customer from kiosk import Kiosk from store import Store # Set up Bag HQ bag_hq = BagFacility() def make_humans(count): '''Create some random shoppers''' customers = [] for i in range(1, count + ...
## return values # area of a circle import math def area(radius): temp = math.pi * radius ** 2 return temp def area(radius): return math.pi * radius ** 2 # multiple return def absolute_value(x): if x < 0: return -x else: return x # wrong x가 0일때는 값이 안나옴. def...
## time class Time(object): """Represents the time of day. attributes: hour, minute, second """ time = Time() time.hour = 11 time.minute = 59 time.second = 30 time.__dict__ ## pure functions def add_time(t1, t2): sum = Time() sum.hour = t1.hour + t2.hour sum.minute = t1.m...
#!/usr/bin/python import numpy as np def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where eac...
def double(number): i = int(number) print(i ** 2) user_input = input("Enter a number: ") print(double(user_input))
#for i in range(3): # for j in range(3): # product = i * j # print(str(i) + " * " + str(j) + " = " + str(product)) for i in range(1, 11): factors = [] for j in range(1,i + 1): if i % j == 0: factors.append(j) print("The factors of " + str(i) + " are: " + str(factors)) for ...
#krb 1/17/2013 turtle exercise from tkinter import * import math import datetime import time def calcCX(width): return width / 2 def calcCY(hgt): return int(((float(hgt)/2.0) * 9.0) / 10.0) class mCanvas(Canvas): def plot(self,sx,sy,color): self.create_line(sx,sy,sx+1,sy,fill=color) def drawHat(...
num_list = [1, 2, 3, 4, 5, 6] def average_tool(collection): num_sum = 0 for num in collection: num_sum += num dividend = len(collection) average = num_sum/dividend return average print(average_tool(num_list)) from functools import reduce def average_reducer(collection): collection...
players = ['Altuve', 'Bregman', 'Correa', 'Gattis'] for player in players: print(player) players_two = { '2b': 'Altve', '3b': 'Bregman', 'ss': 'Correa', 'dh': 'Gattis' } for position, player in players_two.items(): print('Position', position) print('Player Name', player) # How to Loop Through the Characte...
""" Homework! 1) Write a Python program to get the smallest number from a list. Example: [4, 6, 18, 3, 7] Result: 3 2) Write a Python program to print a specified list after removing the 0th, 4th and 5th elements. Example: ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] Result: ['Green', 'White',...
# Create a class to hold a city location. Call the class "City". It should have # fields for name, lat and lon (representing latitude and longitude). class City(): def __init__(self, name, lat, lon): self.name = name self.lat = lat self.lon = lon def __str__(self): return f'{self.name}: ({self.lat}...
#Write a function that accepts a list of numbers as an argument use_this = [2,32,534,23,24,345,23] def smallest(list_of_numbers): smallest_number = [] for num in list_of_numbers : smallest_number.append(num) smallest_number.sort() # print(smallest_number) return smallest_number[0] print...
def modoLectura(matriz): cantidad = len(matriz) iterador = 0 color = [] trio = [] matriz_final = [] while iterador < cantidad: iterador2 = 0 while iterador2 < 3: iterador3 = 0 iterador4 = 0 iterador5 = 0 while iter...
from PIL import Image image = Image.open("cat.jpg") width = image.size[0] height = image.size[1] # weight to determine how bright to make the blacklight # number between 1 and 7 with an optimal value of 2 fx_weight = 7 for y in range(0, height): for x in range(0, width): color = image.getpixel((x, y)) ...
#!/usr/bin/python # -*- coding: utf-8 -*- #This program prints the available playlists of the specified iTunes library and compares them from libpytunes import Library import unidecode l = Library('/Volumes/Transcend/Musik/Musik Hoeren/iTunes/iTunes Library.xml') playlists=l.getPlaylistNames() plcount = 0 for pl ...
""" Consider the set of points in the unit cube that are closer to the middle than to any of the cube vertices. What is the volume of this set? Ans: 1/2""" import math def distance(p1, p2): """Returns distance between two points (tuples) in space.""" return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - ...
# Given Matrix = [1 2 3 # 4 5 6 # 7 8 9] import rotate_matrix mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] length = len(mat[0]) c = length*length row = col = 0 isRowIncr = isColIncr = True for _ in range(c): if row == length-1: print(mat[row][col]) elif col == length-1...
import matplotlib.pyplot as plt import numpy as np from config import UP, DOWN, RIGHT, LEFT, START, GOAL class gridworld: def __init__(self): self.state = START self.path = [self.state] self.shape = [10,7] self.steps = [] def reset(self): self.state = START ...
name = 'Sriram' age = 35 height = 167 weight = 62 eyes = 'black' teeth = 'white' hair = 'Black' print "Let's talk about %s." % name print "He's %d cms tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair" % (eyes, hair) print "His teeth are u...
""" Assignment 2: - You have a positive integer. - Try to find out how many digits it has. - Name the function "number_of_digits" Input: A positive Int Output: An Int. For example: > number_of_digits(10) would return 2 """ ... # tests if __name__ == '__main__': assert number_of_digits(10) == 2 assert...
""" Your goal is to write a program to check if a number is prime or not As a reminder: - Primes are a positive integer greater than 1 which has no other factors except 1 and the number itself: e.g. 2, 3, 5, 7 ... are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) ...
def count(array): result = [0] * 100 # 0 to 99 inclusive for i in array: result[i] += 1 return result if __name__ == '__main__': size = int(input()) ar = [int(input().split()[0]) for i in range(size)] counts = count(ar) sums = 0 for i in range(100): sums +=...
def median(array): size = len(array) if size & size-1 == 0: # trick for testing if number is even return int((array[size//2]+array[size//2-1])/2) else: return array[size//2] if __name__ == '__main__': _ = int(input()) array = sorted([int(i) for i in input().split()]) ...
def primes2(n): sums = 0 d = 2 while d*d <=n: while (n % d) == 0: if len(str(d)) == 1: sums += d else: sums += sum([int(o) for o in str(d)]) n //= d d += 1 if n > 1: if len(str(n...
print('='*60) p = float(input('Digite a quantidade de Km percorridos: ')) d = int(input('Quantidade de dias do aluguel: ')) #R$60 por dia e R$0,15 por Km rodado print('Você terá que pagar R$ {:.2f} pelo aluguel do carro.'.format(60*d + 0.15*p)) print('='*60)
print('Calculadora de descontos') d = float(input('Digite o desconto (em %): ')) p = float(input('Valor do produto: R$')) print('O valor final do produto com um desconto de {}% cai custar R${:.2f}.'.format(d, p-(d*p/100)))
frase = str(input('Digite uma frase: ')).upper().strip() #tam = len(frase) #print(tam) #ult = frase print('A letra A aparece {} vezes.'.format(frase.count('A'))) print('A letra A aparece primeiro na posição {} e por último na posição {}.'.format(frase.find('A')+1, frase.rfind('A')+1))
# Given a list of numbers, find two numbers that add up to the target number. import timeit class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dic = {} # Check if list is at least 2 numbers. ...
from util import check from collections import deque # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def zigzagLevelOrder(self, root: TreeNode): q=deque() ...
import os #a = input('請輸入要轉換的檔案名稱含副檔名:') #if os.path.isfile(filename): # print('找到檔案了!') #else: # print('沒有找到檔案。') def read_file(filename): #讀取檔案 chat = [] with open(filename, 'r' , encoding = 'utf-8-sig' ) as f: for line in f: chat.append(line.strip()) return chat def convert(chat):#轉換 new = [] person = ...
string = input() def check(string): countCols = 0 for i in string: if (i == ','): countCols += 1 newArr = string.split(',') hasMarital = True fullName = newArr[0] sex = newArr[1] univGroup = newArr[2] marital = newArr[3] height = int(newArr[4]) physGroup = newArr[5] if (marital != ''): hasMarital = ...
# def form_list(N, K): # res = [] # totalPersons = list(range(1,N + 1)) # currentPerson = K # while (len(totalPersons) != 1 or len(totalPersons) >= K): # res.append(currentPerson) # totalPersons.remove(currentPerson) # if (currentPerson < len(totalPersons) - K): # currentPerson += K # while (currentPers...
import unittest import leapyear class TestCase(unittest.TestCase): def test_leapyear(self): self.assertEqual(leapyear.fun(0), "Invalid Input") #should throw an error as it's out of the range of numbers def test_leapyear1(self): self.assertEqual(leapyear.fun(4), "Input is a leap year") #Return...
''' FVCproductions CS 291_2 Setember 10, 2014 ''' my_number = 7 input_number = 0 while my_number != input_number: input_number = int(raw_input("Give me a number: ")) if my_number == input_number: print "Correct!" elif my_number < input_number: print "Too big!" elif my_number > input_number: print "Too s...