text
stringlengths
37
1.41M
a=int(input()) if a>0: if a%2==0: print('Even') else:print('Odd') else:print('Invalid')
from unittest import TestCase from mainte import Gun import sys sys.tracebacklimit = 0 one_gun = Gun(10) class Test_Gun(TestCase): def setUp(self): print(self._testMethodDoc) def tearDown(self): pass def test_lock_gun(self): """-- Test lokc gun""" msg = "The gun is unlock"...
def whatFlavors(cost, money): cash = {} for i, integ in enumerate(cost): if money - integ in cash: print(cash[money - integ], end=" ") cash[integ] = i + 1 print(cash[integ]) cash[integ] = i + 1 if __name__ == '__main__': t = int(input()) for t_itr i...
#!/bin/python3 import math import os import random import re import sys # Complete the largestRectangle function below. def largestRectangle(h): max_area = 1 for i in range(0, len(h)): left_cnt = 0 right_cnt = 0 if h[i] == 1: max_area = max(max_area, 1 * len(h)) ...
class Solution: def largestPerimeter(self, A): A.sort(reverse=True) while((len(A)>2)): if A[0] < (A[1]+A[2]): return sum(A[:3]) else: A.pop(0) return 0
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # Binaray Search Tree 성질 : inorder -> 오름차순 정렬이 됨! def getMinimumDifference(self, root: 'TreeNode') -> 'int': L: List[int...
# Decision Tree Regressor # Importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeRegressor # Importing the dataset dataset = pd.read_csv("Position_Salaries.csv") X = dataset.iloc[:, [1]].values y = dataset.iloc[:, [2]].values # Fitting t...
#!/usr/bin/python def parse_instruction(instruction_list, index_max) : accumulator = 0 current_index = 0 while 1 : try : ins, value = instruction_list[current_index].split() except AttributeError : return ['loop', accumulator] except IndexError : return ['OK', accumulator] e...
#!/usr/bin/python def checkpwd_step_one(min, max, neededLetters, pwd) : cpt = 0 for l in pwd : if l == neededLetters : cpt += 1 if min <= cpt <= max : #print("{} {} - {}".format(min, max, cpt)) return 1 else : return 0 def checkpwd_step_two(pos1, pos2, neededLetters, pwd) : ...
from FSM import * """ ISA description from https://en.wikipedia.org/wiki/Little_man_computer Implementation detail questions: - How do we deal with overflow of PC? - How do we deal with over/underflow on ADD/SUB? -> Implemented -ve flag. Set on underflow. Cleared on positive result for ...
''' This is one of the more expensive algorithms time wise, but constant base. We keep on sending maximum value to the last by comparing adjucent elements Time Complexity: O(n^2) Space Complexity: O(1) for more: https://en.wikipedia.org/wiki/Bubble_sort ''' def bubbleSort(arr): for i in range(len(arr)-1): ...
class Node: def __init__(self,data): self.data = data self.next = None class List: ###here tail_prev keeps record of the immediate ###second last element def __init__(self): self.head = None self.tail = None self.tail_prev = None self.size = 0 ###fu...
print("Is your number even or odd??") print("I will tell you !!!!") a = int(input("What number do you want to examine???")) if a % 2 == 0: print("That number is even") else: print("That is an odd number")
import sys class PythonLogic_1(object): ''' Given three ints, a b c, return True if two or more of them have the same rightmost digit. The ints are non-negative. lastDigit(23, 19, 13) -> True lastDigit(23, 19, 12) -> False lastDigit(23, 19, 3) -> True ...
#!/usr/bin/env python3 """ CS373: Quiz #7 (5 pts) <Prateek> """ """ ---------------------------------------------------------------------- 1. What is the output of the following? (4 pts) m1 f1 f2 m2 m4 m5 m6 m1 f1 m3 m5 m6 """ def f (b) : print("f1", end = " ") if b : raise Exception() prin...
#!/usr/bin/env python3 # ---------- # Project.py # ---------- print("Project.py") def project_1 (r, a) : x = [] for v in r : y = {} for w in a : if w in v : y[w] = v[w] x.append(y) return x def project_2 (r, a) : return [{w : v[w] for w in a if w i...
#!/usr/bin/env python3 """ CS373: Quiz #11 (5 pts) <Prateek> """ """ ---------------------------------------------------------------------- 1. In the paper, "A Bug and a Crash" about the Ariane 5, what was the software bug? (1 pt) the conversion of a 64-bit number to a 16-bit number """ """ ---------------...
#!/usr/bin/env python3 """ CS373: Quiz #17 (5 pts) <Prateek> """ """ ---------------------------------------------------------------------- 1. What is the output of the following? (4 pts) """ from copy import copy, deepcopy class A : def __init__ (self) : self.a = [2, [3], 4] x = A() y = copy(x) ...
for x in [y for y in xrange(0,11) if y % 2 == 0]: print x """ Boilerplate: for x in mylist: if y % 2 == 0: print x """ """ newList = [y for y in mylist if y % 2 == 0] print newList """
myword = "superword" def subtractLetter(thestring): while thestring: # NOTE TO SELF: Explain the [0:-1] syntax thestring = thestring[0:-1] yield thestring for astring in subtractLetter(myword): print astring """ Explain: range vs xrange! """
""" Napisz program, który wyświetla liczby od 1 do 100. Dla liczb podzielnych przez 3 niech program wyświetli `Fizz`; dla liczb podzielnych przez 5 niech wyświetli `Buzz`; a dla liczb podzielnych przez 15 niech wyświetli `FizzBuzz`. """ for i in range(1,101): flag = False print (f"{i}",end='') if i % 5 == ...
""" Napisz program, który prosi użytkownika (przez `input()`), żeby podał, ile kosztuje kilo ziemniaków. Niech program policzy i wyświetli, ile trzeba będzie zapłacić za pięć kilo ziemniaków. Potem napisz program, który prosi użytkownika (przez `input()`), żeby podał, ile kosztuje kilo ziemniaków i ile kilo chce kupić...
""" Napisz program obliczający średnią wartość temperatury w danym tygodniu na podstawie temperatur wprowadzonych przez użytkownika. """ import statistics a = list(map(float,input("podaj temeperatury ze wszystkich pomiarów z tyg oddzielone przecinkiem: ").strip().split(','))) print (f"średnia podanych temperatur wynos...
n1 = int(input("첫번째 숫자 입력 : ")) n2 = int(input("두번째 숫자 입력 : ")) n3 = int(input("세번째 숫자 입력 : ")) sum = n1 + n2 + n3 avg = sum / 3 print(sum, avg)
def has(a, *b): for i in b[0]: if a == i: return True return False def intersect(a, b): s = set() for i in a: if has(i, list(b)): s.add(i) return s a = {1, 2, 3} b = {2, 3, 4} print(intersect(a, b)) # {2, 3}을 출력
#entering different elements in a list list1=[] i=int(input("Enter number: ")) j=0 for j in range (0,i+1): inp=input("Enter element to be appended: ") list1.append(inp) j+=1 print (list1) #accessing elements from a tuple tup1=(1,2,3) for i in tup1: print (i) #deleting elements from a di...
init_str=input('Введите строку: ') sum_num=0 for num in init_str: if num.isdigit(): sum_num+=int(num) print('Сумма цифр в строке равна: ',sum_num)
#!/bin/python #https://www.hackerrank.com/challenges/30-binary-trees """ # Day 23: BST Level-Order Traversal # # Objective # # Today, we're going further with Binary Search Trees. Check out the Tutorial tab for learning # materials and an instructional video! # # Task # # A level-order traversal, al...
#!/bin/python #https://www.hackerrank.com/challenges/30-linked-list """ # Day 15: Linked List # # Objective # # Today we're working with Linked Lists. Check out the Tutorial tab for learning materials and # an instructional video! # # A Node class is provided for you in the editor. A Node object has an ...
""" https://leetcode.com/contest/leetcode-weekly-contest-12/problems/validate-ip-address/ # # 468. Validate IP Address # # In this problem, your job to write a function to check whether a input string is a valid IPv4 # address or IPv6 address or neither. # # IPv4 addresses are canonically represented in dot-decimal no...
#!/bin/python #https://www.hackerrank.com/challenges/30-binary-numbers """ # Day 10: Binary Numbers # # Objective # # Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video! # # Task # # Given a base-10 integer, n, convert it to binary (...
# Double-base palindromes # https://projecteuler.net/problem=36 # Checks if number is a palindrome (without string functions) def isPalindromeNumber(n): num = n rev = 0 while n > 0: rev = rev * 10 + n % 10 n //= 10 return num == rev # Converts number from base 10 to base k def baseConversion(n, k): answer = ...
# Spiral primes # https://projecteuler.net/problem=58 import math # Checks if n is prime def isPrime(n): if n < 2: return False if n == 2: return True for factor in range(2, math.ceil(math.sqrt(n)) + 1): if n % factor == 0: return False return True # Returns side length of the square spiral for which the ra...
# Circular primes # https://projecteuler.net/problem=35 import math # Sieve of Erastosthenes returning primes up to including n def sieveOfErastosthenes(n): isPrime = [True] * (n + 1) isPrime[0] = isPrime[1] = False primes = [] for value in range(n + 1): if isPrime[value]: primes.append(value) for multipl...
# Amicable numbers # https://projecteuler.net/problem=21 # Returns all divisors of n, not including n, in a list def getDivisors(n): divisors = [1] for number in range(2, n // 2 + 1): if n % number == 0: divisors.append(number) return divisors # Returns amicable numbers under n in a list def amicableNumbers(n...
import datetime import random import time import balloon def time_stamp(): today = datetime.datetime.now().strftime("%d-%m-%Y") return today def write_todo_list(things): if things == "DONE": push_me() else: today = time_stamp() f = open("TODO.txt", "a") f.write("[" +...
import torch import torchvision.transforms as transforms import torchvision.datasets as datasets from torch.utils.data import Dataset, DataLoader """ PyTorch: COmpute mean and standard deviation of dataset. Refer- https://www.youtube.com/watch?v=y6IEcEBRZks """ # Load CIFAR-10 dataset- train_dat...
import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt """ Example code to implement Fully Connected (FC) layer(s) as Convolutional layer(s) For use in 'Convolutional Implementation of Sliding Windows Object Detection' algorithm. """ # Define random input- x = torch.rand((5, 3, 14,...
''' 12) Swap Values ''' # Write a function that will swap the first and last values of any given array. # The default minimum length of the array is 2. (e.g. [1,5,10,-2] will become [-2,5,10,1]). myList = [1,5,10,-2] def swap(x): x[0], x[len(x) - 1] = x[len(x) - 1], x[0] print x swap(myList)
''' Nth-to-Last Return the element that is N-from-array's-end. ''' myList = list(range(0,1000)) # create a list with a range of 0 - 1000 def nthToLast(a,n): # define a function with 2 arguments print a[len(a) - n] # print out the result nthToLast(myList,500) # call the function and pass in the arguments ''' In ...
class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print(f'The name of the restaurant is {self.restaurant_name}.') ...
#第三个练习 - 判断是否为酒后驾车 print("为了您和他人的生命安全,严禁酒后驾驶车辆!") #提示输入每100毫升血液的酒精含量 alcohol_content = float(input("请输入每100毫升血液的酒精含量(单位mg):")) #判断含量是否超标 if alcohol_content < 20: print("您还不构成饮酒行为,可以开车,请注意安全!") elif alcohol_content < 80: print("您已经达到酒后驾车的认定标准,请勿开车!") else: print("您已经达到醉驾的认定标准,千万不能开车!") #本例...
#第十个练习 - 猜数字游戏 #生成一个随机数需要用到random import random a = random.randint(1,100) print("-------猜数字游戏-------") b = int(input("请输入1~100之间的任一个数(退出游戏请输入-1):\n")) while b != a: if b == -1: break elif b < a: b = int(input("太小,请重新输入:\n")) continue else: b = int(input("太大,请重新...
# -------------------------------------------------------------------------- # --- Systems analysis and decision support methods in Computer Science --- # -------------------------------------------------------------------------- # Assignment 4: The Final Assignment # autorzy: A. Gonczarek, J. Kaczmar, S. Zareba # ...
#run length encoding of a list from itertools import groupby def encode(li): def aux(k, g): l=len(list(g)) if l>1: return [l,k] else: return k return [aux(key,group) for key, group in groupby(li)] print(encode("aaassssssstttteeee"))
import math #prime factors and their frequency def prime(k): i=2; fac=[] while i*i<=k: if k%i: i+=1 else: k//=i fac.append(i) if k>1: fac.append(k) return sorted([fact,fac.count(fact)]for fact in set(fac)) print(prime(130)) ...
#inserting into a list def insert_at(x,li,n): return li[:n-1]+[x]+li[n-1:] print(insert_at(6,[1,2,3,4],4))
#modified encoding from itertools import groupby def encode_modified(alist): def aux(lg): if len(lg)>1: return [len(lg), lg[0]] else: return lg[0] return [aux(list(group)) for key, group in groupby(alist)] print(encode_modified("aaaabbbbcc...
NOT_CONNECTED = 0 CONNECTED = 1 class Vertex(object): def __init__(self, prop): self.prop = prop class Graph(object): def __init__(self, n): self.__n = n self.__m = 0 self.__matrix = [[NOT_CONNECTED for _ in range(n)] for _ in range(n)] self.__vertices = [Vertex(-1) ...
def str_path(p): """Return the string representation of a path if it is of class Path.""" if isinstance(p, Path): return p.strPath else: return p class Path(object): """This class represents a path in a JSON value.""" strPath = "" @staticmethod def rootPath(): """...
import datetime import numpy as np import matplotlib.pyplot as plt import matplotlib def hist(data, bins, margin=1, label='Distribution'): bins = sorted(bins) length = len(bins) intervals = np.zeros(length+1) for value in data: i = 0 while i < length and value >= bins[i]: ...
# Testing data ZOO = { 'question' : 'Does it live on land?', 'yes' : { 'question' : 'Does it live on a farm?', 'no' : 'LION', 'yes' : 'COW' }, 'no' : 'FISH' } def add_new_animal(parent_node,ans_to_change,new_animal,new_question,ans_for_new_animal): # TODO: your code her...
# Dictionaries d = {'name':'chris','age':25} e = { 'name': 'fred', 'age': 30 } d['age'] = 45 # Changing a value d['cool'] = True # Adding a mapping a = d['age'] # Looking up a value del d['cool'] # Deleting a mapping if 'cool' in d: # Check for a key print('yes') for k in d: ...
import unittest from tictactoe import TicTacToeBoard class TestTicTacToeBoard(unittest.TestCase): def test_can_make_move(self): board = TicTacToeBoard() self.assertTrue(board.get_location(0)==' ') board.make_move(0,'X') self.assertTrue(board.get_location(0)=='X') d...
import math c = 300000000 # Speed of light # c = 3e8 # Python also support scientific notation def get_moving_length(l0,v): # A moving object shrinks in the direction of travel. # This formula calculates the new length base on the # original length and the speed. d = 1 - (v*v) / (c*c) d = ma...
class Robot: def __init__(self,x,y): self.x_pos = x self.y_pos = y def _move_left_leg(self): pass def _move_right_leg(self): pass def say_hi(self): print('Beep boob beep from',self.x_pos,self.y_pos) def walk_to(self,x,y): ...
def get_number(): while True: r = input('Give me a number between 1 and 100: ') try: r = int(r) if r>=1 and r<=100: return r else: print('That is not between 1 and 100') except: print('That is not a number') ...
from collections import defaultdict import levenshtein as Lev """An Amino Acid""" class Amino: def __init__(self, tsvRow): self.tsvRow = tsvRow self.name = tsvRow["uc"] self.mass = float(tsvRow["mass"]) def __str__(self): return self.name; def __repr__(self): retu...
class Student: def __init__(self, x,y,z): self.name=x self.rollno=y self.marks=z def display(self): print("Student Name:{}\nRollno:{}\nMarks:{}".format(self.name, self.rollno, self.marks)) s1=Student("rishabh", 17, 97) s1.display() s2=Student("pandey", 88, 90) s2.display() ...
import random import string def again(): question = input("Would you like to generate another one? (Y/N): ") if question == "y" or "Y": main_func() else: print("Goodbye.") exit() def random_ascii(stringLength): characters = string.ascii_letters + string.digits + '&*-#$!^_=+@~' final = ''.join(...
#num=int(input("Enter the number:")) num=123 rev =0 while(num>0): reminder=num%10 rev=(rev*10)+reminder num=num//10 print(rev) print(r'c:\docs\navin') name='my name' print(len(name)) nums=[2,14,25,36,95] nums.pop(2) print(nums) fru=['aaaad','bdsss','cssffg'] print(fru[-1][-1]) a=10 print(id(a)) b=a print...
#greater number in two variables a=int(input("enter first number")) b=int(input("enter second number")) if(a>b): print(a,"is greater than",b) else: print(b,"is greater than",a)
#write a program to demonstrate use of relational operators x=int(input("enter first number")) y=int(input("enter second number")) print(str(x)+"<"+str(y)+"="+str(x<y)) print(str(x)+"=="+str(y)+"="+str(x==y)) print(str(x)+"!="+str(y)+"="+str(x!=y)) print(str(x)+">="+str(y)+"="+str(x>=y)) print(str(x)+"<="+str(y)...
#write a prgram to convert a floating point number into integer and vice-a-versa a=float(input("enter floating point number")) print(int(a)) b=int(input("enter integer type of number")) print(float(b))
def find_max_min(numbers): if not isinstance(numbers, list): raise ValueError('Parameter must be a list') minimum, maximum = min(numbers), max(numbers) return [len(numbers)] if minimum == maximum else [minimum, maximum]
# Example of a list, with tuples inside coordinates = [(4, 5), (6, 7), (80, 34)] print(coordinates[1]) # We cannot do this coordinates[1][1] = 10
def longestWord(text): word_split = re.findall(r"[\w']+", text) longest_word = '' for word in word_split: if len(word) > len(longest_word) and word.isalpha(): longest_word = word return longest_word
def isBeautifulString(inputString): counter = [inputString.count(i) for i in string.ascii_lowercase] return counter[::-1] == sorted(counter)
"""Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall! Example: - For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be sortByHei...
# -*- coding: utf-8 -*- """ Created on Thu Mar 29 08:00:16 2018 @author: Binish125 """ import random class ceaser: key=0 def __init__(self): self.key=random.randint(0,26) def encrypt(self,plain_text): print("\nEncryption Key:\t"+str(self.key)) cipher_list=[] plai...
# Магическое число. import random random_number = random.randint(1, 100) x = int() attempts = 0 while x != random_number: x = int(input("Enter a number: ")) if random_number > x: print("More") attempts += 1 elif random_number == x: print("Bingo, ", "attempts :",attempts ) else...
#Esta clase es la que define el reloj del juego from tkinter import * class Reloj: # Our time structure [horas, segundos, centidegundos] timer = [0, 0, 0, 0] pattern = '{0:02d}:{1:02d}:{2:02d}' # Simple status flag # False mean the timer is not running # True means the timer is running (count...
import sys def part_one(lines): offsetX = 0 offsetY = 0 width = 0 height = 0 areas = {} for line in lines: split_line = line.split(" ") offsetX = int(split_line[2].split(",")[0]) offsetY = int(split_line[2].split(",")[1].replace(":", "")) width = int(split_line[3...
s1,s2,s3=input().split() if(s2=='/'): print(int(s1)//int(s3)) else: print(int(s1)%int(s3))
import matplotlib.pyplot as plt import numpy as np import math # values v0 = float(input("Podaj predkosc poczatkowa: ")) alpha = float(input("Podaj kat rzutu: ")) alpha = math.radians(alpha) g = 9.81 v0x = v0 * math.cos(alpha) v0y = v0 * math.sin(alpha) h_max = (v0y**2)/(2*g) print("Maksymalna wysokosc na jaka wznie...
digits = { "zero": 0, "jeden": 1, "dwa": 2, "trzy": 3, "cztery": 4, "pięć": 5, "sześć": 6, "siedem": 7, "osiem": 8, "dziewięć": 9, "dziesięć": 10, "dwadzieścia": 20, "trzydzieści": 30, "czterdzieści": 40, "pięćdziesiąt": 50, "jedenaście": 11, "dwanaście": 12, "trzynaście": 13, "czternaście": 14, "piętnaście...
def encrypt(string, key): result = "" for char in string: if ord(char) < 91 and ord(char) > 64: result += chr((ord(char) + key - 65) % 26 + 65) elif ord(char) < 123 and ord(char) > 96: result += chr((ord(char) + key - 97) % 26 + 97) else: result += cha...
def same_frequency(num1, num2): """Do these nums have same frequencies of digits? >>> same_frequency(551122, 221515) True >>> same_frequency(321142, 3212215) False >>> same_frequency(1212, 2211) True """ num1_string = str(num1) num2_...
n = list(map(int, input("").split())) r = 'D' if n==sorted(n, reverse=True) else 'N' print('C' if n == sorted(n) else r)
class Solution: def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ if num1 == "0" or num2 == "0": return "0" num1 = num1[::-1] num2 = num2[::-1] str_res = [0 for _ in range(len(num1)+len(num2))] ...
# Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). # Return the running sum of nums. class Solution: def runningSum(self, nums: List[int]) -> List[int]: out = [] out.append(nums[0]) for i in range(1, len(nums)): num = nums[i] ...
############################################################################################################### # DESAFIO: 019 # TÍTULO: Sorteando uma ordem na lista # AULA: # EXERCÍCIO: O mesmo professor do desafio anterior quer sortear a ordem da apresentação de trabalhos dos alunos. # Faça um programa que leia o n...
############################################################################################################### # DESAFIO: 015 # TÍTULO: Aluguel de Carros # AULA: 07 # EXERCÍCIO: Escreve um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade # de dias pelos quais ele foi alugado. ...
#Level 1 - to read the numbers in a file called "Stocktake1.txt and add them all, then print the total total = 0 my_file = open('stocktake1.txt') for line in my_file.readlines(): total = total + int(line) print(f"The total of the numbers in the file is {total}")
''' Reading and slicing times For this exercise, we have read in the same data file using three different approaches: df1 = pd.read_csv(filename) df2 = pd.read_csv(filename, parse_dates=['Date']) df3 = pd.read_csv(filename, index_col='Date', parse_dates=True) Use the .head() and .info() methods in the IPython Shel...
''' What method should we use to read the data? The first step in our analysis is to read in the data. Upon inspection with a certain system tool, we find that the data appears to be ASCII encoded with comma delimited columns, but has no header and no column labels. Which of the following is the best method to start w...
import codecademylib3 from sklearn import preprocessing import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np # load in financial data financial_data = pd.read_csv('financial_data.csv') # code goes here print(financial_data.head()) # Seperate variables for all three columns mon...
from sys import argv script, stuff, things, that = argv name = raw_input("What is your name?") print "So your name is %r." % name print "The script is called:", script print "Your first variable is:", stuff print "Your second variable is:", things print "Your third variable is:", that
#!/usr/bin/python3 def best_score(a_dictionary): if not a_dictionary or a_dictionary == {}: return None max = list(a_dictionary.keys())[0] for i in a_dictionary: if a_dictionary[i] > a_dictionary[max]: max = i return max
#!/usr/bin/python3 if __name__ == "__main__": from sys import argv lenav = len(argv) add = 0 for i in range(lenav): if i < 1: continue add = add + int(argv[i]) print("{:d}".format(add))
import csv def create_csv(path,head): with open(path,"w+",newline="",encoding="utf8") as file: csv_file = csv.writer(file) csv_file.writerow(head) def append_csv(path,data): with open(path,"a+",newline='',encoding="utf8") as file: csv_file = csv.writer(file) csv_file.writerows(da...
#encoding: UTF-8 # Autor: Oswaldo Morales Rodriguez, A01378566 # Conociendo x e y calcular la hipotrnusa y el angulo from math import atan2, pi x=int(input("valor de x")) y=int(input("valor de y")) r=((x**2)+(y**2))**0.5 ang=atan2(y,x) z=atan2(y,x) ang=(180*z)/pi print("Hipotenusa es",r,"angulo es",ang)
from __future__ import print_function import tensorflow from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras.optimizers import RMSprop import numpy as np import matplotlib.pyplot as plt # Let's explore t...
My_info = {"Name": "Joey", "Age": 31, "State": "Kansas", "Pet": "Yogi"} #This was my first the first function I made for this problem but after reviewing the solution code, I prefer using iteritems() def Dict_Info(dict): print "Hello my name is", dict["Name"], "and I am", dict["Age"], "years old!" print "I am...
''' Create a class called Car. In the__init__(), allow the user to specify the following attributes: price, speed, fuel, mileage. If the price is greater than 10,000, set the tax to be 15%. Otherwise, set the tax to be 12%. Create six different instances of the class Car. In the class have a method called display...
class Product(object): def __init__(self, price, name, weight, brand, cost, status): self.price = price self.name = name self.weight = weight self.brand = brand self.cost = self.price * self.weight self.status = status self.status = "For Sale" def Sell(sel...
#Exercise 3 of conditional statements def computegrade(grade): while 1: try: if grade <= 0: print('Score out of range') return grade elif grade < 0.6: print('F') return grade elif grade < 0.7: ...
import sys fileName = input("Enter the file name: ") if fileName == "na na boo boo": print("NA NA BOO BOO TO YOU - You have been punk'd!") sys.exit(0) try: file = open(fileName, 'r') except: print("File cannot be opened: " + fileName) sys.exit(1) linesList = [line.strip("\n") for line in file] ...
''' DP Longest Increasing Subsequence https://practice.geeksforgeeks.org/problems/longest-increasing-subsequence/0 ''' def main(): # LISs T = int(input()) # type: int while(T>0): T-=1 n = int(input()) seq = [] subseq = [] for i in range(n): seq.append(in...
from unittest import TestCase, main from queue import Queue class QueueTest(TestCase): def test_queue_init(self): q = Queue() self.assertEqual(len(q), 0) def test_queue_enqueue(self): q = Queue() for i in range(5): q.enqueue(i) self.assertEqual(len(q), 5) ...