text
stringlengths
37
1.41M
# Feature Category : sourcing_channel, residence_area_type import pandas as pd from sklearn import preprocessing def categorize(df): ''' This method takes panda.dataframe having single category column as its data as param. It then does apply sklearn.preprocessing.LabelEncoder() on the category column a...
#No argument def func1(): print("I am a function") func1() #prints the value print(func1()) #prints the value through func1() and then python constant NONE as func1() does not retun a value #With argument def func2(a): return("The cube of the given value is " + str(a**3)) func2(4) print(func2(4)) #multipl...
# WAP # 1 # 12 # 123 # 1234 # 12345 #example to print in same line or to avoid new line after each print. print(value, end="") print("geeks", end =" ") print("geeksforgeeks") def function1(): for i in range(1,6): for j in range(1,i+1): print(j, end =" ") print() function1() print() ...
#read line by line #upper to change all the content to upper case fhand = open('test.txt') inp = fhand.read() print(inp.upper())
import random import config as cfg class Deck: def __init__(self): self.cards = self.init_deck() self.remaining_cards = len(self.cards) def init_deck(self): cards = [] for colour in range(cfg.NUM_COLOURS): for value in range(cfg.NUM_VALUES): for i i...
import math from numbers import Number class Point: """this class create point you cant insert only int by defult is (0,0)""" __counter = 0 def __init__(self, x=0.0, y=0.0): if isinstance(x, Number) and isinstance(y, Number): self.x = float(x) self.y = float(y) els...
from numbers import Number class Point: """this class create point you cant insert only int by defult is (0,0)""" def __init__(self, x=0.0, y=0.0): """ Exercises 1 build constructor""" if isinstance(x, Number) and isinstance(y, Number): self.__x = float(x) self.__y = f...
from math import * def divide(x, y): if y < 1: raise(Exception("The second argument must be larger than 1")) if x == 0: (q, r) = (0, 0) return (q, r) (q, r) = divide(floor(x/2), y) q = 2*q r = 2*r if x%2 == 1: r += 1 if r >= y: r = r - y q += ...
""" Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ ...
def main(): x = ["a","b","c"] y = ["1","2","3"] for a in x: for b in y: print(a,b) main()
def main(): print("range upto end num:") for x in range(10): #0-->5 print(x) print("range function with starting and ending:") for x in range(2,10): #2-->9 print(x) print("range function with jump:") for x in range(2,30,3): #2-->30 with 3 increment print(x) main()
""" HW2.py a cryptanalytic toolkit in Python to analyze the statistical properties of files Usage: cipher.py COMMAND [OPTIONS] [ARGS]... Commands: dist Calculate frequency distributions of symbols... Help for each command is avaible: HW2.py COMMAND -h Example...
#!/usr/bin/env python # encoding: utf-8 """ euler_10.py """ def primes_lt(n): primes = [2] numbers = range(n+2) next_prime = 2 while True: print next_prime counter = next_prime + next_prime while counter <= n: numbers[counter] = -1 counter += next_prime num = next_prime + 1 whil...
""" Section class is an abstract class. Local axis of the section is as follows: x-axis is the longitudinal axis that is directed from the start node to the end node of the element y-axis is directed upward the section z-axis is directed to the left Properties(abstract methods): properties are overridden by the inh...
def inInside(matrix, i, j): if(i<0 or j<0 or i>len(matrix)-1 or j>len(matrix[0])-1): return False return True def getsum(matrix, i, j): sum = 0 for x in range(-1,2): for y in range(-1, 2): if(x!=y or x!=0 or y!=0): if(inInside(matrix, i+x, j+y) and ...
def alternatingSums(a): b = [0,0] for x in range(len(a)): if ((x+1)%2 == 1): b[0] += a[x] else: b[1] += a[x] return b
def select_a_friend(): item_number=0 for friend in friends: print '%d. %s aged %d with rating %.2f is online' % (item_number + 1, friend['name'], friend['age'],friend['rating']) item_number = item_number+1 friend_choice = raw_input("Choose from your friends") friend_choice_position =...
from math import * def f(x): return x * sin(x) def integral(f, a, b): n = 10000 dx = (b-a) / n y = 0 for k in range(1, n): y = y + f(a + k * dx) y = y + (f(a) + f(b)) / 2 return dx * y a = 0 b = 2 * 3.14 print(integral(f, a, b)) # def f2(x): # return x * x - 2 # # def deriva...
#!/usr/bin/env python3 import math import os import random import re import sys if __name__ == '__main__': N = int(input()) if N >= 2 and N <=5 and N % 2 == 0: print('Not Weird') elif N % 2 != 0: print('Weird') elif N >= 6 and N <= 20 and N % 2 == 0: print('Weird') elif ...
__author__ = 'achandelkar' def NeutralizeList(L1): i = 0 L2 = [] while (i < len(L1)): if type(L1[i]) != list: L2.append(L1[i]) else: ExtendList(L2,L1[i]) i+=1 return L2 def ExtendList(L2,L3): j = 0 while (j < len(L3)): i...
__author__ = 'achandelkar' ''' def ReplaceFirstCharOccurences(S1,ReplaceBy): return S1[0] + S1[1:].replace(S1[0],ReplaceBy) ''' def ReplaceFirstCharOccurences(S1,ReplaceBy): S2 = S1[0] ch = S1[0] i = 1 while i < len(S1): if S1[i] == ch: S2+=ReplaceBy els...
__author__ = 'achandelkar' #!C:\Python34\python.exe print("Its fun", __name__) def SumOfEvenOdd(lb , ub): sum_even = 0 sum_odd = 0 while lb <= ub: if lb % 2 == 0: sum_even += lb else: sum_odd += lb lb +=1 return sum_even,sum_odd if __name__ ...
import os def humanize_filename(filename): filename = os.path.splitext(filename)[0] replace_map = { '-': ' ', '_': ' ', '.': ' ' } for search, replace in replace_map.iteritems(): filename = filename.replace(search, replace) return filename
""" Simple Game Lab We will be writing our first simple game in this lab! We will write a simple game where the objective of the player is to evade the boss. Do the following: 1) Create a player and boss Sprite using "tank.png" and "boss.png". Initialize player on the left side of the screen and boss on the right s...
""" Pick Up Coins Lab Do the following: 1) The player Sprite along with some other variables have already been created for you. 2) In setup(), inititalize a SpriteList. Use a for loop to initialize coins at random positions on the screen. Use the imported random module and random.randrange(n) generates a random int...
guess = input("Guess number: ") secret = input("Secret number: ") # Makes each digit into a string; puts them in a list secret_digit_list = list(str(secret)) guess_digit_list = list(str(guess)) # Compares the digits of `secret` and `guess !!! NOT WORKING !!! for n,(a,b) in enumerate(zip(guess_digit_list,secret_digit...
#input the total number of inputs n = int(input("Number of inputs: ")) #a: total number of positive even numbers a=0 while not n<=0: x = int(input("Enter Number: ")) if x%2 == 0 : a = a+1 n=n-1 print("Positive even numbers:",a)
for i in range(0,4): print(i) for move in range(0,4): print(move) for i in range(1,5): print(i) for kitty in range(0,1+2): print(kitty) for Supercalifragilisticexpialidocious in range(0,1): print(Supercalifragilisticexpialidocious) for i in range(11,0,-2): print(" "*int((12-i)/2) + "*"*i, ...
code = {"A":"=.===", "B":"===.=.=.=", "C":"===.=.===.=", "D":"===.=.=", "E":"=", "F":"=.=.===.=", "G":"===.===.=", "H":"=.=.=.=", "I":"=.=", "J":"=.===.===.===", "K":"===.=.===", "L":"=.===.=.=", "M":"===.===", "N":"...
def passThroughDoor(string): for i in range(0,len(string)): if i == (len(string)-1): return False if string[i] == string[(i+1)]: return True print(passThroughDoor("ballon")) print(passThroughDoor("color")) print(passThroughDoor("wendall")) print(passThroughDoor("gary ...
def sumListWhile(aList): counter = 0 result = 0 while counter < len(aList): result = result + aList[counter] counter = counter + 1 return result def multiplyListFor(aList): result = 1 for i in aList: result = result * i return result def factorialWhileLoop(n): if ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 10 19:10:00 2017 @author: Dustin """ balance = 42 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 def calcMMP (mr, b): return mr*b def calcUB (b, mmp): return b - mmp def updateB(r, ub): return ub + (r * ub) for x in range(12): ...
class InstansiKesehatan: def __init__(self, id, nama, alamat, kontak): self._id = id self._nama = nama self._alamat = alamat self._kontak = kontak def setNamaInstansi(self, x): self._nama = x def setAlamatInstansi(self, x): self._alamat = x def setKontakInstansi(self, x):...
# List to Dictionary Exercise # Given a person variable: # person = [["name", "Jared"], ["job", "Musician"], ["city", "Bern"]] # Create a dictionary called `answer`, that makes each first item # in each list a key and the second item a corresponding value. # Output should look like this: # {'name': 'Jared', 'job': 'Mu...
# Given the string 'amazing', create a variable called answer, # which is a list containing all the letters from 'amazing' # but not the vowels (a, e, i, o, and u) answer = [letter for letter in 'amazing' if letter not in [ 'a', 'e', 'i', 'o', 'u']] print(answer) # Alternate solution answer2 = [letter for letter ...
# State Abbreviations # Given two lists `['CA', 'NJ', 'RI']` and # `['California', 'New Jersey', 'Rhode Island']` create a # dictionary that looks liek this: # {'CA': 'California', 'NJ': 'New Jersey', 'RI': 'Rhode Island'} # and save it to a variable called *answer* list1 = ['CA', 'NJ', 'RI'] list2 = ['California', 'N...
##################################################################################### # It is compulsory that for usage of '+' operator -> both parameter should be str # For usage of '*' operator , one parameter should be int and other should be str ######################################################################...
# Mutable : Changes can be made # Immutable : Non changeable behaviour # Once we create an Object , we cannot perform any changes in that Object. # If we are trying to perform any changes with those changes , a new Object will be created # Example : Immutable # Case 1 : x=10 y=10 print(x) print(y) print("Address o...
import numpy as np import matplotlib.pyplot as plt from PIL import Image import h5py def load_dataset(): """ The dataset is taken from Coursera The dataset contains: train_catvnoncat.h5 and test_catvnoncat.h5 -> a training set of m_train images labeled as cat (y=1) or non-cat (...
# short lecture on backpropagation by Geoffrey Hinton: # https://www.youtube.com/watch?v=H47Y7pAssTI import matplotlib.pyplot as plt import numpy as np import sys sys.path.insert(0, "../..") sys.path.insert(0, "..") import PyRat as pr def run(): #generate n samples of random 2d data from each class #such tha...
import numpy as np class logistic: #constructor def __init__(self, n_units, n_inputs): print 'Initializing logistic layer with ' + str(n_units) + ' units and ' + str(n_inputs) + ' inputs per unit ' self.n_outputs = n_units self.n_inputs = n_inputs self.w = (np.random.rand(s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Esta script prepara las mustras leidas del csv, para su posterior tratamiento. ''' import csv def load_regions(path): '''Load regions of csv.''' with open(path, 'r') as csv_file: csv_reader = csv.DictReader(csv_file) next(csv_reader) loc...
from termcolor import colored #colored(string, color) class Game(): def __init__(self): self.board = [[], [], [], [], [], [], [], [], [], [colored('+', 'red')]] self.main() def main(self): self.placePieces() self.display() def placePieces(self): uniDict = {'WHITE' ...
#!/usr/bin/env python # coding: utf-8 # In[4]: from Tkinter import * from math import * from sys import argv import numpy as np import matplotlib.pyplot as plt pi = np.pi #inital conditions def drawCircle(canvas, x, y, rad, fill): # color circle according to phase # draw a circle of given ra...
#List 有序可動列表 grades=[12,60,45,70,90] print(grades) print(grades[1:4]) grades[0]=55 print(grades) grades=grades+[25,59] print(grades) print(len(grades)) grades[1:4]=[] print(grades) #巢狀列表 data=[[3,4,5],[6,7,8]] print(data) print(data[0][:2]) data[0][0:2]=[5,5,5] print(data)
#set 集合 s1={3,4,5} print(10 not in s1) s2={4,5,6,7} r1=s1&s2 #交集 r2=s1|s2 #聯集 r3=s1-s2 #差集 r4=s1^s2 #反交集 print(r1,"\n",r2,"\n",r3,"\n",r4) s=set("Hello") print(s) print("H" in s)
def avg(*ns): sum=0 for n in ns: sum=sum+n print(sum/len(ns)) avg(3,4,5) avg(99,56,78,85)
import numpy as np import matplotlib.pyplot as plt def step_function(x): y = x > 0 # Bool로 출력 return y.astype(np.int64) # y의 자료형을 int로 바꾸기 def sigmoid(x): return 1 / (1+np.exp(-x)) x = np.arange(-5, 5, 0.1) y = step_function(x) plt.plot(x, y) plt.ylim(-0.1, 1.1) # y축 범위 지정 x1 = n...
#Ejercicio #43 # Programa que lea N valores y que cuente cuantos de ellos son positivos y cuantos # son negativos (0 es condici'on de fin de lectura) # Audny D. Correa Ceballos (Equipo 'about:blank') #ENTRADAS #Es el n'umero de valores que el usuario ingresa rangoDeValores = int(input()) #Inicializar en 0 nu...
#Autores: Programa realizado por Equipo2_CodePain #Version 1.0 #Programa que calcula el MCD de dos números enteros mediante el algoritmo de Euclides #Entrada: Dos números enteros aNum y bNum aNum=-1 bNum=-1 res=1 save=0 while aNum<0 or bNum<0: #Comprueba que sean numeros positivos aNum=int(input()) bNum=int(i...
# Ejercicio 7 # Escribir el programa para un programa que reciba un numero positivo, si este numero es mayor a 1000 se le sumara un 5%, si el numero es mayor a 3000 se le sumara otro 10% adicional y si el numero es mayor a 5000 se le sumara otro 5% adicional. # Autor: Jorge Reyes (Equipo 'about:blank') # Dato de entra...
#Autor: Deyberth Carrillo #Entrada: El numero del cual se desean conocer los factoriales #Salida: Los factoriales del numero ingresado #Se solicita el numero a evaluar print("Ingrese el numero del cual desea saber sus factoriales:") numero=int(input()) factores=str(1) posibleFactor=0 #Se evaluan los factores ...
file=open("/ago-dic-2020/practicas/PrimerParcial/triangulo.txt", "r") print(file.read()) def tipo(a, b, c): if a==b and a==c: return 'Equilatero' elif a!=b and a!=c: return 'Escaleno' elif a==0 or b==0 or c==0: return 'No es triangulo' else: return 'Isóceles' p...
current_users=['jaden', 'yonatan', 'jose', 'raul', 'kio'] new_users=['KIO', 'marcos', 'jose','jonathan', 'estefanio'] new_userss=[x.lower() for x in new_users] for new_user in new_userss: if new_user in current_users: print(f"{new_user} already been taken") else: print(f"welcome {new_user}")
#alien_0={'color': 'green', 'points': 5} #print(alien_0['color']) #print(alien_0['points']) #new_points=alien_0['points'] #print(f"You just earned {new_points} Points!") #print(alien_0) #alien_0['x_position']=25 #alien_0['y_position']=5 #print(alien_0) #alien_0={} #alien_0['color']='green' #alien_0['points']=25 #print(...
# pantry.py import ast, collections class Pantry: def __init__(self, name, email, address, food_and_amt_needed): self.name = name self.email = email self.address = address self.food_and_amt_needed = food_and_amt_needed def get_pantries(): restaurant_dicts = [] with open("pantry_data.txt", "r") as res_data...
from __future__ import division # Get a and b 's the Maximum common divisor def Max_Common_Divisor(a, b): while b != 0: c = a % b a = b b = c return a # a is max common divisor # Get a and b's the least common multiple def Min_Common_Multiple(a, b): return a * b / a # Fraction...
month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def DetermineDateOfYear(date): # To Determine the days of month IntOfMonth = int(date[4:6]) for i in range(IntOfMonth - 1): DaysOfMonth = (i + 1) * month[i] # To Determine Leap year IntOfYear = int(date[0:4]) if ((IntOfYear % 4 ==...
for number in range(-100, 10000): a = (number + 100) ** 0.5 b = (number + 268) ** 0.5 #if (a % 1 == 0) and (b % 1 == 0): #if (not a % 1) and (not b % 1): if a.is_integer() == True and b.is_integer() == True: print number
def splitStr(s): return [ch for ch in s] def buildGrid(lines, level): grid = {} for y, line in enumerate(lines): for x, ch in enumerate(splitStr(line)): pos = (x, y, level) grid[pos] = ch return grid def adjacent(pos): x, y, level = pos return [(x - 1, y, level), (x...
from functools import reduce import itertools import intcode def readNumbers(name): with open(name) as f: for line in f.readlines(): return list(map(lambda x: int(x), line.split(","))) # Directions: # 0 - up # 1 - right # 2 - down # 3 - left def rotate(currentDirection, turnDirection): del...
from random import randint import prompt def even_description(): print('Answer \'yes\' if the number is even, otherwise answer \'no\'.') def even_logic(): number = randint(1, 99) even = not bool(number % 2) if even: correct_answer = 'yes' else: correct_answer = 'no' print('Qu...
# -*- coding: utf-8 -*- """ Created on Sun Jan 26 15:37:49 2020 @author: ibrahim """ #Pythonda veri saklamak için oluşturdugumuz alanlara değişken denir. x = 5 y = 10 z=x+y # 15 k print(x) # 5 print(y) # 10 print(z) # 15 print(k) # NameError: name 'k' is not defined. #String bir değişken oluştururken tek ve...
# 1) Declare two variables, a string and an integer # named "fullName" and "age". Set them equal to your name and age. fullName = "Scott Anderson" age = 51 # 2) Declare an empty array called "myArray". # Add the variables from #1 (fullName and age) to the empty array using the push method. # Print to the console. my...
def longVowel(aWord): longVowel = list(aWord) returnWord = longVowel for i in range (0,(len(aWord))): if (longVowel[i] == 'A' or longVowel[i] == 'a'): if (longVowel[i].upper() == longVowel[i+1].upper()): # Magic happens here....insert 3 vowels returnWord...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by Z Lei on 01/01/2018. class StackUnderflow(ValueError): pass class SStack(object): """顺序表栈""" def __init__(self): self._elem = [] def is_empty(self): return self._elem == [] def top(self): if self._elem == []: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by Z Lei on 17/08/2017. def quicksort(array): if len(array) < 2: return array else: jizhun = array[0] less = [i for i in array[1:] if i <= jizhun] more = [i for i in array[1:] if i > jizhun] return quicksort(less)...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by Z Lei on 28/12/2017. def list_sort(lst): """ 插入排序 :param lst: :return: """ for i in range(1, len(lst)): value = lst[i] j = i while value < lst[j - 1] and j > 0: lst[j] = lst[j - 1] j = j ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by Z Lei on 17/08/2017. input = [2, 4, 6] def dedai(input): if len(input) == 1: return input[0] elif len(input) == 0: return 0 else: return input[0] + dedai(input=input[1:]) print 12 == dedai(input) def count_len(input):...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @DateTime : # @Author : Z LEI class ProtectAndHideX(object): def __init__(self, x): assert isinstance(x, int), 'x must be an integer' self.__x = ~x def get_x(self): return ~self.__x x = property(get_x) inst = ProtectAndHideX(3333...
''' 함수만들기 def add(a,b): c = a+b print(c) add(3, 2) def add(a,b): c = a + b return c x = add(3, 2) print(x) def add(a, b): c = a + b d = a - b return c, d print(add(3,2)) ''' def isPrime(x): for i in range(2, x): if x % i == 0: return False return True ...
# 최솟값 구하기 arr = [5, 3, 7, 9, 2, 5, 2, 6] # 가장작은 숫자가 저장될 변수 지정 arrMin = float('inf') # 파이썬에서 가장 큰값으로 저장하여 초기화 for i in range(len(arr)): if arr[i] < arrMin: arrMin = arr[i] print(arrMin)
smallestValue = None for i in [1, 5, 6, 7, 10, 15, 16]: if smallestValue is None: smallestValue = i elif smallestValue > i : smallestValue = i print("Smallest Value:", smallestValue)
first = 0 print("first thing: ", first) for i in [1, 4, 5, 9, 12] : first = i + first print("Sum: ", first)
# Write a program to prompt the user for hours and rate per hour using input to compute gross pay. # Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for # all hours worked above 40 hours. # Put the logic to do the computation of pay in a function called computepay() and use # th...
#!/usr/bin/python3 """ | Purpose: To Give a frequency count of the titles and give information to help decide on a cutoff. | | History: Created on November 21, 2018 by Greg Colledge | """ import sys import operator import statistics as stats #-----READ IN DATA----- titleFreq = {} with open(sys.argv[1],'r') as data...
altura=float(input('A altura da parede é :')) largura=float(input('A largura da parede é :')) area=altura*altura print('A area da parede é {} e voce vai precisar de {} litros de tinta'.format(area,(area)/2))
frase = str(input('Digite uma frase : ')).strip().lower() a='a' print('A letra "A" aparece nessa string {} vezes, pela primeira vez na posiçao {} na a ultima {}'.format(frase.count(a), frase.find(a)+1,frase.rfind(a)+1))
nome=str(input('Digite seu nome completo : ')) masc=nome.upper() mins=nome.lower() sep=nome.split() print('''Nome com maiusculas: {} Nome com tudo minusculo {} O nome tem {} letras e O primeiro nome, {}, tem {} letras'''.format(masc,mins,len(''.join(sep)),sep[0], len(sep[0]))) '''Na 1ª resoluçao do guanabara, achei ...
"""from math import floor,trunc num = float(input('Digite um numero real')) print('O numero é {} e a sua parte inteira é {}'.format(num, floor(num))) #podemos usar o trunc(num)""" num = float(input('Digite um valor : ')) print('O valor é {} e a sua parte inteira é {} '.format(num, int(num)))
frase = ' Curso em Video Python ' print(frase.capitalize(), frase.lower().title(), frase.lower().title().replace('Em', 'em')) print('Curso ' in frase, frase.find('Curso')) print(frase.split()) separado=frase.split() print(separado," ".join(separado))
from random import randint itens = ('pedra', 'papel', 'tesoura') print('''escolha e digite 0 para pedra 1 para papel 2 para tesoura Qualquer outro digito encerra o programa''') while True: escolha = int(input('escolha : ')) pc = randint(0, 2) if pc == 0 and escolha == 1: print('{:=^40}'.format(' ...
import pygame as pg import math pg.init() black = (0, 0, 0) yellow = (255, 255, 0) grey = (127, 127, 127) width = 1200 height = 600 screen = pg.display.set_mode((width, height)) pg.display.set_caption("game of life") grid = [] length = 10 class grid_cell: def __init__(self, x, y, cell_length): self.x = x sel...
class SparseList(list): def __setitem__(self, index, value): missing = index - len(self) + 1 if missing > 0: self.extend([None] * missing) list.__setitem__(self, index, value) def insert(self, index, value): self[index] = value return self def __getitem_...
#rock paper scissor game import random player_wins=0 computer_wins=0 winner=3 while player_wins<winner and computer_wins<winner: print(f"\nPlayer score:{player_wins} Computer score:{computer_wins}") print(" ...rock...") print("...paper...") print("...scissors...") choice= input("(E...
from core.Config import alphabet, C_list class HillTrigraph_Cipher: """ Name: {cyan}The Hill-Trigraph Cipher{reset} Description: {cyan}An encryption and decryption technique that use 3x3 integer matrices as keys.{reset} Possibility: {cyan}5,429,503,678,976{reset} Author: {yellow}@...
valor = float(input("Informe o valor da casa: R$")) sal = float(input("Informe seu salário: R$")) anos = int(input("Informe em quantos anos vai querer pagar: ")) prestacao = valor/(anos*12) excede = sal * 0.30 if prestacao > excede: print("\nEmpréstimo negado, salário muito baixo para prestação do imóvel. \nSalá...
s =0 c =0 for i in range (1, 501, 2): # print(i, end = " ") if i % 3 == 0: c = c + 1 s = s +i print("O valor total dos {} valores é: {}".format(c,s))
n= float(input("Quantos reais você pretende converter para dólares?")) print("A sua conversão para dólares é igual à: US${:.2f}".format(n/3.27))
s=0 c=0 for i in range (0, 6): n = int(input("Informe o n°: ")) if n % 2 == 0: c = c +1 s = s + n if s > 0: print("A soma dos {} números pares foi {}.".format(c, s)) else: print("Não houveram números pares!")
n1= float(input("Qual a altura da parede em metros? ")) n2= float(input("Qual a largura da parede em metros? ")) a= n1*n2 q= a/2 print("A quantidade de tinta em litros necessária pra pintar a parede é igual à: {}".format(q))
days = int(input("Informe a quantidade de dias: ")) km = float(input("Informe a quantidade de km's rodados: ")) preco = (days *60) + (km * 0.15) print("Total: {:.2f}" .format(preco))
input('Hi, Isabella! How can I help you today?') print("I'll set everything ready as you command me to do, just wait patiently") print('My system is ready now to do whatever account you tell me to do.') n1 = int(input('Now, please, put the first number:')) n2 = int(input('Now, please, put the second one:')) print("Firs...
# coding: utf-8 # ## Question 2 # #### To run this code, ensure that the version of the following are correct: python3.6, anaconda3 import csv import numpy as np inp=[] out=[] testinp=[] testout=[] with open("train_1_5.csv", newline ='\n') as f: #read the training data reader =csv.reader(f) ...
'''------==================Задача 16 (2/10)====================------ Заданное число N записали 100 раз подряд и затем возвели в квадрат. Что получилось? >*Вводится целое неотрицательное число N не превышающее 1000.''' # str(данные); y = 100 n = int(input("Введите число:")); if(n < 0 or n > 1000): print("Введите не о...
'''------==================Задача 14 (1/10)=================------ Вводится число 0 или 1, необходимо вывести 1 или 0 соответственно. >*Число 0 или 1.''' x = int(input("Введите 0 или 1:")); if (x == 0): print(1); elif (x == 1): print(0); else: print("Введите 1 или 0!!!");
""" Esse modulo contem funcoes matematicas """ from math import exp def distancia_euclidiana(x, y, n): """ Essa funcao calcula a distancia euclidiana entre n pontos :param x: um numero ou uma lista de numeros :param y: um numero ou uma lista de numeros :param n: quantidade de pontos :return:...
from player import Player import random class Human(Player): def __init__(self): """Default constructor""" self.playerName = "Human" # ********************************************************************* # Function Name: play # Purpose: To let the human play the game of Duell # Parameters: # self, the...
""" 黄金螺旋线 - 黄金比例的定义是把一条线段分割为两部分,较短部分与较长部分长度之比等于较长部分与整体长度之比,其比值的近似值是0.618。 - 而斐波那契相邻两位数刚好符合这种黄金比例,而且前一项与后一项的比值无限接近0.618。 - 黄金螺线的画法: 在以斐波那契数为边的正方形拼成的长方形中画一个90度的扇形,连起来的弧线就是斐波那契螺旋线。 它来源于斐波那契数列(FibonacciSequence),又称黄金螺旋分割。 """ import numpy as np import turtle import random def generate_fibonacci(n): """ fi...
""" 特殊矩阵的生成:单位阵、对角阵等等 """ import numpy as np # 单位阵 std_mat = np.eye(3) print("=== standard mat ===") print(std_mat) # 偏移主对角线1个单位的伪单位矩阵 offset_std_mat = np.eye(3, k=1) print("=== offset mat ===") print(offset_std_mat) # 全填充生成矩阵 full = np.full((2,3), 10) print("=== full mat ===") print(full)