text
stringlengths
37
1.41M
import datetime int1 = input("What is your current age?") int2 = input("At what age do you want to retire?") age = int(int1) retirement = int(int2) year = str(datetime.datetime.now().year) current_year = int(year) retirement_year = retirement - age year_of_retirement = current_year + retirement_year print("You hav...
def is_anagram(): word1 = [] word2 = [] print("Enter two words and I'll tell you if they are anagrams:\n") string1 = input("Enter the first word: \n") string2 = input("Enter the second word:\n") # if (string1 == string2): # print("You have entered the same word trice. Try again.") # elif (sorte...
#!/usr/bin/python3 def func(): t = int(input()) while t: t -= 1 input() a = set(list(map(int, input().split()))) input() b = set(list(map(int, input().split()))) print("False") if a-b else print("True") if __name__ == '__main__': func()
class Fractal(object): def __init__(self, epsilon=0): pass def __str__(self): pass @staticmethod def CALCULATE(pos, max_iterations): x,y = pos iteration = 0 Z = complex(0, 0) C = complex(float(x),float(y)) while abs(Z) < 2.0 and iteration < ma...
#generating a fibonacci seq from typing import Any, Union fib = 1 pfib = 0 ppfib = 0 count = 1 while len(str(fib)) < 1000: count += 1 print(fib) ppfib = pfib pfib = fib fib = pfib + ppfib print(count)
import math def is_prime(n): # function for if a num is prime if n <= 1: return False max_div = math.floor(math.sqrt(n)) for i in range(2, 1 + max_div): if n % i == 0: return False return True count = 0 run = True while run: for i in range(0,100000000,1): i...
def find_anagrams(dictionary): sorted_string_to_anagram = collections.defaultdict(list) for s in dictionary: sorted_string_to_anagram[''.join(sorted(s))].append(s) return [group for group in sorted_string_to_anagram.values() if len(group) >= 2]
import streamlit as st import requests import json import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from wordcloud import WordCloud, STOPWORDS import numpy as np import modules as md githublink = '[GitHub Repo](https://github.com/himanshu004/World-Football-Leagues-Dashboard)' st.sidebar.write(...
#Option 4: PyParagraph for Homework 3 #In this challenge, you get to play the role of chief linguist at a local learning academy. # As chief linguist, you are responsible for assessing the complexity of various passages # of writing, ranging from the sophomoric Twilight novel to the nauseatingly high-minded # research...
# # Задача 1.Найти площадь и периметр прямоугольного треугольника по двум заданным катетам. # import math # # a = input("Длина первого катета: ") # b = input("Длина второго катета: ") # # a = float(a) # b = float(b) # # c = math.sqrt(a**2 + b**2) # # s = (a*b)/2 # p = a + b + c # # # print("Площадь треугольника:" + str...
list1 = [1,2,3] list2 = [] #list2 = [[i for i in [list1]] for i in range(4)] # OR for i in range(4): for i in [list1]: list2.append([i]) print() print(list2)
names = ['John', 'Paul', 'george', 'Ringo', 'suhu', 'jay', 'kav'] for name in names: if name not in ['John']: names.remove(name) print(names) ages = [2018 - year for year in years_of_birth] print(ages)
import string import random # upper = input ("Uppercase (y/n)" : ) # lower = input ("Lowercase (y/n)" : ) # number = input("Include Numbers (y/n)" : ) # specialchars = = input ("Include Special Charactors (y/n)" : ) def randompassword(): chars=string.ascii_uppercase + string.ascii_lowercase + string.digits #+ stri...
# Write a Python program to copy the first 2 chars of the givne string # If the chars are less then 2 then return the whole string with n copies def substring_copy(str, n): flenth = 2 if flenth > len(str): flenth = len(str) substr = str[:flenth] result = "" for i in range(n): resul...
# =============>This is a Normal mathematical tasks<========== x = 7 x = 7 // 3 # rounds the number = 2 ans class int #x = 7 / 3 # gives the floating number = 2.33333335 ans class float #x = 7 % 3 # gives the reminder = 1 ans class int #print("x is {}" .format(x)) #print(type(x)) # ================>This is how to ...
# calculate number of days between two days [2014,7,2][2014-7-11] from datetime import date # To Fo with function ''' def days_between(x, y): delta = 0 f_date = x l_date = y delta = y - x return(delta.days) f_date = (2014, 7, 2) l_date = (2014, 7, 11) print(days_between(f_date, l_date)) print(day...
# Write a function that list's all the none duplicate members # (list the members minus the deplicates). # This is the normal way def dedupe_v1(x): y = [] for i in x: if i not in y: y.append(i) return y # This is usig the (set) method def dedupe_v2(x): return list(set(x)) a =...
# For loop Chapter 6 using Tuple Tuple is () list is [] Dictionary is {} animals = ('bear', 'bunny', 'dog', 'cat', 'velociraptor') for pet in animals: print(pet) for pet in range(len(animals)): print(pet)
#! /usr/bin/env python3 ''' This is function It calls the print function the format and the python version ("This is python version {}".format(platform.python_version())) from in side the message function and the message function is called from the main function. Finally the main function is call (at the bottom line) w...
# use codinbat.com print(''' Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive). ''') def missing_char(char, n): front = char[:...
# Get the volume of sphere with radius 6 # So many ways of programming for this task # check each one of them from math import pi ''' def volume_sphere(x): # x = 6.0 result = ((4.0/3.0) * pi * (x ** 3)) # return result print(result) r = 6.0 # print(volume_sphere(r)) volume_sphere(r) ''' # OR write ...
# Guessing number import random number = random.randint(1, 9) guess = 0 count = 0 while guess != number and guess != 'exit': guess = input('Guess a number between 1 to 9: ') if guess == 'exit': break count += 1 guess = int(guess) if guess > 9 or guess < 1: print( f' You...
string = "Hello world 123456" numbers = [i for i in string if i.isdigit()] print(numbers)
# Reverse order def reverse_v1(x): y = x.split() result = [] for word in y: #word.split() result.insert(0, word) return " ".join(result) a = 'My name is suhumar' print(reverse_v1(a))
python = 'I am PYTHON' print(python[0:4]) # prints space" I am" print(python[1:4]) # prints space" am" #print(python[2:4]) # prints without space "am" print(python[1:]) # prints space" am PYTHON" print(python[:]) # prints "I am PYTHON" print(python[1:100]) # prints space" am PYTHON" print(python[-1]) # prints "N" Last ...
# names = ['John', 'Paul', 'george', 'Ringo', 'suhu', 'jay', 'kav'] names = ['John', 'Paul', 'george', 'Ringo', 'suhu', 'jay', 'kav'] names_to_remove = [] for name in names: if name in ['John', 'george']: #if name not in ['John', 'Paul']: names_to_remove.append(name) for name in names_to_remove: nam...
# Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32 # Type "help", "copyright", "credits" or "license()" for more information. # >>> # @elapsed_time def big_sum(): num_list = [] for num in (range(0, 10000)): num_list.append(num) print(f'Big sum: {su...
''' yesterday.txt 파일을 읽어서 YESTERDAY라는 단어가 몇번 나왔는지 yesterday_lyric.upper().count('YESTERDAY') Yesterday라는 단어가 몇번 나왔는지 yesterday_lyric.count('Yesterday') yesterday라는 단어가 몇번 나왔는지 ''' f=open('yesterday.txt','r') yesterday_lyric = f.read() print('YESTERDAY는 ',yesterday_lyric.upper().count('yesterday'),'번 나왔습니다') #==print('...
""" Description: Third data structure in python: sets Sets are neither ordered nor indexed. """ #Create a set myset1 = {"me", "you", "him"} #Notice the alphabetic order print("set: ", myset1) #As they are not ordered, can't be accessed #print('The first one is: ', myset1[0]) #Elemnts cannot be changed (discoment th...
""" Description: Third data structure in python: sets Sets are neither ordered nor indexed. """ #Create a dictionary mydictionary1 = { "personal": "I", "possesive": "mine", "adverbial": "me"} print("dictionary: ", mydictionary1) #As they are not ordered, can't be accessed print('Value "persional": ', mydi...
# importing the modules import dropbox; # creating the class class fileUpload: def __init__(self, key, file_to, file_from): self.key = key; self.file_to = file_to; self.file_from = file_from; # initializng the dropbox dbx = dropbox.Dropbox(self.key); # uploading th...
from itertools import count from math import sqrt class Node: number = count() def __init__(self, start_node, coordinates, parent, target_node): self.idnr = next(Node.number) self.x, self.y = coordinates self.parent = parent self.g = abs(start_node.x - self. x) + abs(star...
stus=[{"name":"zs","age":22},{"name":"laowang","age":33}] #a = [22,2,3,27,34,1,78] #a.sort(reverse = True) #a.reverse() #print(a) stus.sort(key=lambda x:x["name"])#按名字排序 print(stus)
def print_menu(): print("="*30) print("学生管理系统".center(22)) print("输入1:表示添加学生") print("输入2:查找学生") print("输入3:修改学生") print("输入4:删除学生") print("输入5:查看所有学生") print("输入6:退出") def add_studetn(): name = input("请输入学生的姓名:") age = input("请输入学生的年龄:") qq = input("请输入学生的qq:") stu = {} stu["name"]=name stu["age"]=age s...
for i in "abcefg": print(i) else: print("没有内容") for i in range(1,10): print(i)
import urllib.request from urllib.parse import urlencode import json def getStockData(symbol): url="https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=%s&apikey=9J1RZLTW23BXC0KX"%(symbol) connection = urllib.request.urlopen(url) responseString = connection.read().decode() ...
from random import * from player import * from enemies import * squad = int(input("How many people are you playing with? (up to 10) ")) risk = int(input("How risky are you from 1 to 10? ")) house = int(input("What house number do you choose? (up to __) ")) player = Players(8, 2, squad, risk) print(player) player.kno...
from random import * class Squad: def __init__(self): # self.no_of_players = no_of_players print("Squad goals") class Players(Squad): def __init__(self, squad=2, points=0, knowledge=5, speed=2, risk_level=5): super().__init__() self.squad = squad self.points = points ...
from tkinter import* root = Tk() equal = "" # want the text to update this helps do that equation = StringVar() #when equation updates with StringVar, update the calcualtion calculation = Label(root, textvariable=equation) calculation.grid(columnspan=5) equation.set("Enter your equation:") def buttonPress(num): ...
class Rectangle: def __init__(self, p, p1): self.__p = p self.__p1 = p1 def calculateHigh(self): if self.__p.y - self.__p1.y < 0: return -(self.__p.y - self.__p1.y < 0) return self.__p.y - self.__p1.y < 0 def calculateWidth(self): if self.__p.__x - self...
import matplotlib.pyplot as plt import numpy as np # 用这样 3x3 的 2D-array 来表示点的颜色,每一个点就是一个pixel(像素) a = np.array([0.313660827978, 0.365348418405, 0.423733120134, 0.365348418405, 0.439599930621, 0.525083754405, 0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3) # 关于interpolation的值 ...
import numpy as np from sklearn import datasets from sklearn.cross_validation import train_test_split # 选择邻近的点,模拟出数据的值 from sklearn.neighbors import KNeighborsClassifier # 加载鸢尾属植物 数据集 iris = datasets.load_iris() iris_x = iris.data iris_y = iris.target print(iris_x[:2, :]); # 分类,表示有几类 print(iris_y) # test_size表示测试比例占...
''' Created on 2018年10月10日 @author: Administrator ''' # class Animal(object): # def __init__(self,name): # self.name=name # def eat(self): # print("吃的很开心") # class Cat(Animal): # def __init__(self, name,age): # Animal.__init__(self, name) # self.age=age # def run(self): ...
''' Created on 2018年10月10日 @author: Administrator ''' class Person(object): name="zhangsan" # def __init__(self, name,age): # self.name=name # self.age=age @classmethod def test(cls): print("类方法") def test2(self): print("test2") @staticmethod def test3(): ...
#------------------------------------------------------------------------------ # Autores: Leonardo Felix, Gisela Miranda Difini, Karolina Pacheco, Tiago Costa #------------------------------------------------------------------------------ from numpy import random import random as rand def NUMBER_OF_TRIES(): retur...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Apr 2 18:41:45 2017 @author: saurabh """ import Tkinter as tk print tk "Toplevel widget of Tk which represents mostly the main window of an application. " #root = tk.Tk() #label = tk.Label(master = root, text = "Enter something") #entry = tk.Entry(mas...
'''''' from EMP.emp import Employee class Leader_2(Employee): def __init__(self, name, sex, date, cell, address): super(Leader_2, self) . __init__(name, sex, date, cell, address) self.salary = 50000 self.post = 3000 self.lunch = 1800 def total_salary(self, hour): try...
# Use the file name mbox-short.txt as the file name fname = raw_input("Enter file name: ") if len(fname) == 0: fname = "romeo.txt" fh = open(fname) lst = list() for line in fh: line_list = line.split() for word in line_list: if word not in lst: lst.append(word) lst.sort() print lst
def legginomi(): try: f = open("../files/anagrafici.csv", "w") input_string = "s" while input_string == "s": stringa = "" stringa += input("Nome? ") + ";" stringa += input("Cognome? ") + ";" stringa += input("Data? ") + ";" stringa ...
def seleziona_con_for(lista): divisori = [] for i in lista: if i%2==0: if i%3 ==0: divisori.append(i) return divisori def filtro(n): return n %2 == 0 and n % 3 == 0 def seleziona_con_filter(lista): return list(filter(filtro, lista)) if __name__ == '__main__'...
#Choose Level of the game def choose_level(): prompt = "Please choose a difficulty (Easy, Medium, or Hard): " difficulty = raw_input(prompt) level = difficulty.lower() choices = ['easy', 'medium', 'hard'] #The user's options for difficulty #Making sure the user inputs the right difficulty while not level in c...
# add(a, b) should return a+b # e.g. add(1, 2) returns 3 def add(a, b): if a == 1 and b == 2: return 3 else: result = a + b result = mult(a, 2) result = div(a, 2) return int(result) # mult(a, b) should return a * b # e.g. mult(2, 3) returns 6 def mult(a, b): a = ternary_confumble(-a * -1, a, ...
def chain_mult (arr): length = len(arr) max_mults = [[0 for x in range(length)] for x in range(length)] #set to 0 for multiplying one matrix for i in range(1, length): max_mults[i][i] = 0 for idx in range(2, length): for i in range(1, length-idx+1): ...
# -*- coding: utf-8 -*- import numpy as np def createarray(): """create array use numpy function""" print(np.zeros(10,dtype=int)) print(np.ones((3,2), dtype=float)) print(np.full((3,5),10,dtype=float)) #np.random.seek(0) x2 = np.random.randint(10,size=(3,4)) print(x2.shape)#3*4 print(x2...
# -*- coding: utf-8 -*- """ Created on Fri Mar 29 16:45:21 2019 @author: Administrator Bubble sort 冒泡排序算法实现 Bubble_Sort_simpleX,几种不同交换值的方式 选择排序算法 selectSort 插入排序算法 InsertionSort 希尔排序算法 shellsort 合并排序 megresort 快速排序 quicksort """ class BS: """冒泡排序""" def __init__(self, ls): ...
""" Regex check for phone numbers Regex format for US/CA Number \d{3}-\d{3}-\d{4} """ import re # raw string representation which does not escape characters phone_regex = re.compile(r'\d{3}-\d{3}-\d{4}') print(phone_regex) """ - MO indicates match object - .search() method looks for a matching result...
from collections import ChainMap a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'} for key in a_dict: print(f"{key} -> {a_dict[key]}") # Reverse keys and values to create new dictionary new_dict = {} for key, value in a_dict.items(): new_dict[value] = key print(new_dict) # Filtering nw_dict = {'on...
""" data_plot.py 作用:将XXX.csv中的数据进行可视化呈现,选取某一列的数据。 """ import csv import numpy as np import matplotlib.pyplot as plt # 最初的数据先slice出来到test_data_1.csv中,然后到test_data_3.csv中看一下趋势 filename = 'test_data_3.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) temperatures = [] for ro...
number= int(input("Enter a number: ")) if(number>1): for i in range(2,number): if (number%i)==0: print(number,"is not a prime number") print(i,"times",number//i,"is",number) break else: print(number,"is a prime number") else: print(number,"is not a prime number")
# Faça um programa que calcule o mostre a média aritmética de N notas. qt_notas = int(input('Digite a quantidade de notas que você deseja digitar\n')) soma = 0 for n in range(qt_notas): nota = float(input('Digite a nota:\n')) soma += nota media = soma / qt_notas print('A média das notas digitadas foi de:', med...
#ejemplo de map a = ['a','b','c'] print(a) resultado = list(map( lambda x : x.upper() , a )) print(resultado) pass
#exercise basket = ["Banana", "Apples", "Oranges", "Blueberries"]; basket.remove("Banana") basket.pop(2) basket.append("Kiwi") basket.insert(0, "Apples") Apples = 0 for i in basket: if i == "Apples": Apples += 1 print(f"There are {Apples} apples in the basket.") basket = [] print(basket) #exercise1 my_fav_numbe...
explanation = "I believe that the first time you type python it saves your current location as a default for when you use python in future." print("Hello world\n" * 4 + "I love python\n" * 4) x = int(input("Give me a number to calculate.")) a = int(str(x) + str(x)) b = int(str(x) + str(x) + str(x)) c = int(str(x) + st...
""" CP1404/CP5632 Practical State names in a dictionary File needs reformatting """ # TODO: Reformat this file so the dictionary code follows PEP 8 convention colourCodes = {"blue1": "#0000ff", "black": "#000000","cyan1": "#00ffff","gray41": "#696969","goldenrod1": "#ffc125","magenta": "#ff00ff","pink": "#ffc0cb","red...
""" Find out all the possible substrings of a string....... substring is a sequence of characters within another string for example : String : abc Possible Substrings : "a" , "b" , "c" , "ab" , "bc" , "abc" """ S = input() Ans = [] leng = len(S) k = 1 while k <= leng: for s in range(leng): ...
class Fiction(Book): def __init__(self, CatalogueNo, Title, Author, Format, Classification, Genre): '''inherit Book class with additional attribute, Genre''' Book.__init__(self, CatalogueNo, Title, Author, Format, Classification) self.Genre = Genre def __str__(self): return ("{0} | {1} | {2}...
from selenium import webdriver from selenium.webdriver.common.by import By keyword = input("Enter the item you want to search: ") sort = input('Sorting By: ' 'Enter "r" for ratings, ' '"c" for cheapest, ' '"h" for expensive, ' '"s" for standard: ').lower() number_of...
import math a = float(input("Digite o valor de a: ")) if (a == 0 ): print("A equação não é do 2 grau.") else: b = float(input("Digite o valor de b: ")) c = float(input("Digite o valor de c: ")) delta = (b ** 2) - 4 * a * c if delta < 0: print("Não tem raizes") elif delta == 0 : ...
#Faça um Programa que leia 4 notas, mostre as notas e a média na tela. notas = [] for i in range(4): notas.append(float(input(f'Digite {i+1}ª nota: '))) soma = 0 for i in (notas): soma = soma + i print(i) print(f'A média é {soma/len(notas)}')
segundos = int(input()) ##Calcular a quantidade de horas horas = segundos // 3600 ##Calcular a quantidade de minutos temporestante = segundos - (horas * 3600) minutos = temporestante // 60 ##Calcular a quantidade de segundos segundos = temporestante % 60 print('{}:{}:{}'.format(horas,minutos,segundos))
#Um funcionário de uma empresa recebe aumento salarial anualmente: Sabe-se que: #Esse funcionário foi contratado em 1995, com salário inicial de R$ 1.000,00; #Em 1996 recebeu aumento de 1,5% sobre seu salário inicial; #A partir de 1997 (inclusive), os aumentos salariais sempre correspondem ao dobro do percentual do ano...
#Você foi contratado para desenvolver um programa que leia o resultado da enquete e informe ao final o resultado da mesma. O programa deverá ler os valores até ser informado o valor 0, que encerra a entrada dos dados. Não deverão ser aceitos valores além dos válidos para o programa (0 a 6). Os valores referentes a cada...
import math a=int(input("Digite o valor de a: ")) b=int(input("Digite o valor de b: ")) c=int(input("Digite o valor de c: ")) delta = b**2 - 4 * a * c if delta < 0: print('Impossivel Calcular') else: x1 = (-b + math.sqrt(delta))/(2 * a) x2 = (-b - math.sqrt(delta))/(2 * a) if delta == 0: print(...
import re def check_username(name): phone_pattern = re.compile("^1[345678]\d{9}$") is_phone = phone_pattern.match(name) if is_phone: print("是手机号") return True else: email_pattern = re.compile("^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$") is_email = email_...
""" insertion_sort.py This module implements insertion sort on an unsorted list and returns a sorted list. Insertion Sort Overview: ------------------------ Uses insertion of elements in to the list to sort the list. Pre: an unsorted list[0,...,n] of integers. Post: returns a sorted list...
""" rabinkarp_search.py This module implements Rabin-Karp search on a given string. Rabin-Karp Search Overview: ------------------------ Search for a substring in a given string, by comparing hash values of the strings. Pre: two strings, one to search in and one to search for. Post: retu...
import random class Game(object): def __init__(self): player1 = Player(self, "Mr. Miyamoto", True) player2 = Player(self, "Tom", False) self.players = [player1, player2] self.current_player = 0 self.winner = None self.setup() def clone(self): g = Game() ...
from bs4 import Beautifulsoup import requests example_webpage = ''' <html> <head> <title>Example Webpage</title> </head> <body> <div class="wrapper"> <p>Content</p> </div> </body> </html> ''' class Webpage: def __init__ ( self, url=None, html=None ): self.url = url if url else None ...
import random import sys def show_rules(): print(""" RULES OF THE GAME If you guess the number correctly ~~~ for every guess you used and pass out a ~~~ for each remaining guess you have left. Guess the number on first try, everyone but you drinks 2x your max guesses. Guess the number correctly and it's a 3 or ...
#The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, #but it also has a rather interesting sub-string divisibility property. #Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: #d2d3d4=406 is divisible by 2 #d...
# -------------- import numpy as np import pandas as pd import matplotlib.pyplot as plt # code starts here #loading data df = pd.read_csv(path) #calculating probability of fico credit score is grater that 700 p_a = len(df.fico[df.fico>700])/len(df.fico) print(p_a) #calculating probability of perpose is debt_consolat...
def nth_row_pascal(n): """ :param: - n - index (0 based) return - list() representing nth row of Pascal's triangle """ if n == 0: return [1] current_row = [1] # first row for i in range(1, n+1): previous_row = current_row current_row = [1] # add default first...
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self, init_list=None): self.head = None if init_list: for value in init_list: self.append(value) def append(self, value): if self.he...
##################################### Ejercicio 2.1 '''A continuación hemos creado unas variables "tres","tresconseis" y "hola" con unos valores almacenados en ellas. usando la función type debereis almacenar el tipo de datos que corresponde en las variables que creareis vosotros "typeTres", "typeTresConSeis" y "type...
# Uses python3 # Good job! (Max time used: 0.03/5.00, max memory used: 9613312/536870912.) import sys def is_greater_or_equal(n,m): return n + m > m + n def largest_number(a): a = sorted(a, reverse=True) res = "" while len(a) > 0: maxDigit = '0' for digit in a: if is_great...
class Bag(float): def valid(self): return self <= 500 def cost(self): if self.valid(): return 0 if self <= 25 else (1500 * self if self <= 300 else 2500 * self) class AirPlaneCargo(tuple): def __init__(self, bags: iter): self.__bags = bags self.__length = len(b...
def main(): rows = int(input("Number of rows: ")) for current_row in range(0, rows+1): if current_row % 2: continue print(int((rows-current_row) / 2)*" " + "@"*current_row + int((rows-current_row) / 2)*" ") if __name__ == '__main__': main()
def main(): time_ = float(input("Time: ")) speed = float(input("Speed: ")) acceleration = float(input("Acceleration: ")) distance = speed * time_ + ((acceleration * (time_**2)) / 2) print(distance) if __name__ == '__main__': main()
def main(): smaller = 0 bigger = 0 while True: try: number = float(input("Number: ")) if number > 100: bigger += 1 elif number < 100: smaller += 1 except ValueError: break print("Smaller: ", smaller) prin...
def main(): n = int(input("Numero: ")) m = int(input("Numero: ")) sum_ = 0 if n < m: if n < 0: n = 0 for number in range(n, m+1): sum_ += number print(sum_) if __name__ == '__main__': main()
def main(): distance = float(input("Distance: ")) days = int(input("Days: ")) if distance > 1000 and days > 7: discount = 0.85 else: discount = 1 result = distance * 5000 * discount if result < 100000: result = 100000 print(result) if __name__ == '__main__': mai...
# Based on https://www.youtube.com/watch?v=YQc2ysYubYc # Transform the integer part of the number def decimal_integer_to_binary(number): number = int(number) result = "" while number != 0: division = number % 2 if division: result += "1" else: result += "0" ...
# Based on https://www.youtube.com/watch?v=YQc2ysYubYc # Transform the integer binary part of the number def binary_to_decimal_integer(number): if "." in number: number = number.split(".")[0] result = 0 for index, bit in enumerate(number[::-1]): if bit == "1": result += 2**inde...
ref = {"A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15} def hex_to_decimal_integer(number): if "." in number: number = number.split('.')[0] result = 0 for index, multiplier in enumerate(range(len(number) - 1, -1, -1)): value = number[index] if value in ref.keys(): ...
import random from random import random import numpy as np def weighted_choice(objects, weights): """ returns randomly an element from the sequence of 'objects', the likelihood of the objects is weighted according to the sequence of 'weights', i.e. percentages.""" weights = np.array(weights...
#Looping Problem 8 for n in range(11): for c in range(n): print (c, end=" ") print ()
class Cat(): def __init__(self): self.name = "" self.color = "" self.weight = 0 cat = Cat() cat.name = "Spot" cat.color = "black" cat.weight = 16 class Monster(): def __init__(self): self.name = "" self.health = 0 def decrease_health(self, amount): ...
#looping problem 2 for n in range(10): print ("*", end=" ") print () for n in range(5): print ("*", end=" ") print () for n in range(20): print ("*", end=" ")
def inputs(): a=int(input("Enter first no.")) b=int(input("Enter first no.")) return a,b a,b=inputs() if(a>b): print("{0} is greater than {1}".format(a,b)) elif(b>a): print("{0} is greater than {1}".format(b,a)) else: print("They are equal") ...
#!/usr/bin/env python3 # this example is about re-writing URLs. It assumes we are moving a series # of web sites formt eh domain oldplace.com to the domain newplace.org and # need to update a document containing a list of URLs. import re urls = \ '''The report is <a href = https://docs.oldplace.com/chris/report> here...