text
stringlengths
37
1.41M
import numpy as np np.set_printoptions(suppress=True) # sigmoid function def nonlin(x, deriv=False): if deriv: return x * (1 - x) return 1 / (1 + np.exp(-x)) # input dataset x = np.array ([ [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1] ]) print(x.shape) # ...
from data import MENU,resources def report(): for i in resources: print(f"{i}: {resources[i]}") def check_availability(type): cof=MENU[type] ing=cof["ingredients"] flag=0 for i in ing: if(resources[i]<ing[i]): print(f"Sorry there's not enough {i}") flag=1 ...
print("Welcome to the Band Name Generator.") city=input("What's the name of the city you grew up in?\n") pet=input("What's your pet's name?\n") print("Your band name could be "+city+" "+pet)
# ask user to enter a number, store it inside variable x x = input('Enter the first number: ') # ask user to enter another number, store it inside variable y y = input('Enter the second number: ') # ask user to enter the result of multiplication of x and y result = input('Enter the result for multiplication of {0} * {1...
# this is a string "this is a string" 'this is also a string' print("Hello World".upper()) print("6" + "2") print("Hello " + "John") # this is an integer print(2 * 3) print(type(2)) print("this is a news headline".title())
first_list=dict() # Global List of First follow_list=dict() # Global List of Follow def lookup_match(word, _list): match=False for key, val_list in _list.items(): if key==word: result=val_list match=True return result return match def FIRST(word, d): first=l...
a = int(input("Masukkan bilangan A: ")) b = int(input("Masukkan bilangan B: ")) c = int(input("Masukkan bilangan C: ")) if a>b and a>c: print(a, "adalah bilangan terbesar") elif b>a and b>c: print(b, "adalah bilangan tersebar") elif c>a and c>b: print(c, "adalah bilangan terbesar")
import unittest from password import User from password import Credentials class TestUser(unittest.TestCase): ''' Test class that defines test cases for the user class. ''' def setUp(self): ''' Set up method to run before each test cases. ''' self.new_user = User("sara...
#These 2 variables store the input strings to be compared str1 = raw_input() str2 = raw_input() #These 2 variables store their lenghts respectively len1 = len(str1) len2 = len(str2) print "1st lineage: " + str1 + " Length: " +str(len1) print "2nd lineage: " + str2 + " Length: " +str(len2) count = 0 #Reason for do...
import math g = 9.8 #in m/s^2 def acceleration(v_x, v_y, C, m): a_x = -C*v_x*math.sqrt(v_x*v_x + v_y*v_y)/m a_y = -g - C*v_y*math.sqrt(v_x*v_x + v_y*v_y)/m return a_x, a_y # computes acceleration w/ gravity and drag force def update(x, y, v_x, v_y, a_x, a_y, dt): x = x + v_x*dt + 0.5*a_x*dt*dt y ...
import math z = 1 f = input("what is the first number? ") f = int(f) s = input("what is the second number? ") s = int(s) n = input("what is the third number? ") n = int(n) x = 1 while x <= math.sqrt(abs(n*f)): if n * f % x == 0: if x + n*f//x == s: print(x, "+", n*f//x) z = 1 ...
# # I. File manipulations # import os # os.rename("old.txt", "new.txt") # if the file in the working directory # # if elsewhere - provide complete path: # os.rename("/home/martin/biology/old.txt","/home/martin/biology/new.txt") # # if diff folder but same file name - the function moving file to another folder # # or...
# 3. Chapter - Reading text from a file open() my_file = open("dna.txt") # file on a hard drive # read() my_file_name = "dna.txt" file_contents = open(my_file_name) my_file_contents = my_file.read() # Exercises # 1. Splitting genomic DNA my_DNA_file = open("GenomicDNA.txt") # .txt - just a plain text, no variable...
class Student: def __init__(self): print("HELLO!! I am constructor in class Student.") class Demo: def __init__(self,a,b): self.a=a self.b=b def fun1(self): return self.a+self.b Student() o=Demo(10,22) print(o.fun1())
import math def check_num(num): if num.isdigit(): return True else: return False # TODO(everyone): 더하기, 빼기, 곱하기, 나누기 함수 정의하기 def add_function(num1, num2): if check_num(num1) and check_num(num2): result = int(num1) + int(num2) else: result = "check parameter" retur...
import pandas as pd import numpy as np x = pd.DataFrame(np.random.randn(3, 3), index=["Apple", "Banana", "Mango"], columns=["C1", "C2", "C3"]) y = pd.DataFrame(np.random.randn(3, 2), index=["Apple", "Pear", "Tomato"], columns=["C1", "R1"]) z = pd.con...
# 문자열을 입력받습니다 s = input("Enter the string : ") """ # 입력된 문자열을 공백을 기준으로 나누어서 리스트로 만든다 fruits = s.split() print(fruits) b = "-".join(fruits) print(b) c = b.count("-") print(c) """ """ # strip 함수는 공백을 제거하는 역할을 합니다 rs = s.rstrip() ls = s.lstrip() ss = s.strip() print("original=[%s], rstrip=[%s], lstrip=[%s], strip=[%s]"%...
import pandas as pd chunks = pd.read_csv("lecture9-1.csv", header=None, names=("date", "money"), chunksize=5) for it in chunks: print("----------") print(it)
caracteres = int(raw_input()) cadena = raw_input() listaCaracteresSinRepetir = list(set(list(cadena))) listaCaracteresDes = [] lenMax = 0 def validarCadena(cad): listCar = list(set(cad)) isValid = True if len(listCar) == 2: car0 = '' car1 = '' if listCar[0] == cad[0]: ...
ran1,ran2=map(int,input().split()) for ran3 in range(ran1+1,ran2): if(ran3%2!=0): print(ran3,end=" ")
import itertools solutions = {} NO_SOLUTION = "no solution" operators = ('+', '-', '*', '/') for operations in itertools.product(operators, repeat=3): solution = "4" for operation in operations: solution += " {} 4".format(operation) result = eval(solution) solutions[result] = solution testcase_c...
#!/usr/bin/env python def brute_force_search(l, value): for i in range(len(l)): if l[i] == value: return i return -1 if __name__ == "__main__": array = range(42) found = brute_force_search(array, 20)
#! /usr/bin/env python abc = "abcdefghijklmnopqrstuvwxyz" def letter(n): return abc[n-1] lanyard = "20 08 09 19 09 19 20 08 05 11 05 25 19 20 15 14 05 08 05 14 07 05" numbers = [int(i) for i in lanyard.split(' ')] letters = ''.join(letter(n) for n in numbers) print letters
#! /usr/bin/env python def condense(w): return w[0] + str(len(w)-2) + w[-1:] def expand(w): length = int(w[1:-1]) + 2 for word in get_words(length): if word.startswith(w[0]) and word.endswith(w[-1:]): print word def get_words(length, filename = '/usr/share/dict/words'): return (wor...
#產生一個隨機整數1~100(不要印出來) #讓使用者重複輸入數字去猜 #猜對的話 印出 "終於猜對了!" #猜錯的話 要告訴他 比答案大/小 import random start_num = int(input('請輸入開始數值:')) end_num = int(input('請輸入結束數值:')) r = random.randint(start_num, end_num) count = 0 while True: count += 1 # count = count + 1 num = int (input('請輸入一個隨機整數')) if num == r: print('恭喜猜...
from node import Node #from container import Container class Ship: # QUEUE # Start def __init__(self, top = None): self._top = top # Add def queue_add(self, new_data): aux = Node(new_data) if self._top == None: self._top = aux else: aux = self._...
import unittest from unittest.mock import Mock, patch from newnew import handle_favourite_drinks, customer_order #def handle_favourite_drinks(new_name, new_drink, drinks): # while new_drink not in prices: # new_drink = input(f'\nSorry we don\'t sell that here.\nPlease type a drink from the price list:{prices...
import wikipedia def main(): page_title = input("page title : ") while page_title != "": try: print(wikipedia.search(page_title)) print(wikipedia.summary(page_title)) except wikipedia.exceptions.DisambiguationError as e: print(e.options) page_title =...
import random def score_status_determination(score): """determine the grades of scores""" if score < 0 or score > 100: return "Invalid score" elif score >= 90: return "Excellent" elif score >= 50: return "Passable" else: return "Bad" def main(): """print statu...
from copy import deepcopy def f(stack,info): direction = info[0] blocks = info[-1] global cnt if direction == 'U': for i in range(blocks): # 여기를 잘 정해줘야 한다 if board[stack[-1][0]-1][stack[-1][1]] !=1: stack.append([stack[-1][0]-1,stack[-1][1]]) stack.po...
INDENT = ' ' class FuncLine(object): __doc__ = """ This file is aimed to provide basic function line as an object. Generate() is able to return a function line with indent choosen """ def __init__(self, content='', next_indent_level_change=0, indent_level=-1): __doc__ = """ ne...
""" Student code for Word Wrangler game """ import urllib2 import codeskulptor import poc_wrangler_provided as provided WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted lis...
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: # Idea: Backtracking # 1. Add one element to the current list and append that list to output list # 2. Remove that element from the current list and move to the next element # 3. Time Complexity: O(2^N) # ...
#!/usr/bin/python3 """ FIFO caching""" from base_caching import BaseCaching class FIFOCache(BaseCaching): """ Create a class FIFOCache that inherit from BaseCaching and is a caching system """ def __init__(self): super().__init__() self.data = {} self.data_in = 0 s...
#!/usr/bin/env python # -*- coding: utf-8 -*- def solve(x: int, y: int, k: int) -> int: ''' x: the num of 表 True y: the num of 裏 False k: the num of coint to be reversed ''' if k <= y: return x + k else: return x - (k - y) + y def getinput(): def getints_line(): ...
# Demo of Servo Motor Driving # Author: Craig Versek, based on example and library by Tony DiCola # # We have a mini RC servo motor available for rotational actuation applications # (e.g., driving a pendulum, opening a door) # According to Bill Earl (ref. https://learn.adafruit.com/adafruit-motor-selection-guide/rc-se...
""" Good morning! Here's your coding interview problem for today. This problem was asked by Twitter. Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. For example, given the query string de and the set of ...
# function to find words while expands forward from a position def expand(inputList, inputString): stringList = [] strLen = len(inputString) endIndex = 0 for i in range(strLen): if i < endIndex: continue for j in range(i+1, strLen+1): if (inputString[i:j]) in inp...
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. """ """ 1 ...
num1 = 2 num2 = 5 num3 = 10 if num1 > num2 and num2 < num3: print('num1 is greater!') else: print('num2 is greater!') class computer: def __init__(self, manufacturer, price, mfd): sele.manufacturer = manufacturer self.price = price self.mfd = mfd def show_price(self): ...
class Item: """simple class for item in warehouse""" def __init__(self, name, value, amount=1): self.name = name self.value = value self.amount = amount @classmethod def copyof(cls, item, amount): copy = cls(item.name, item.value) copy.amount = amount ...
# Importing the dependancies import numpy as np import pandas as pd import matplotlib.pyplot as plt # Loading the data in numerical format X = pd.read_csv('Linear Regression\python\Training Data\Linear_X_Train.csv').values y = pd.read_csv('Linear Regression\python\Training Data\Linear_Y_Train.csv').values # Standardi...
# List of tuples # Each tuple contains a test: # - the first element are the inputs, # - the second are the output, # - and the third is the message in case of an error # To test another case, add another tuple input_values = [ # Test case 1 ( ["88", "41", "96", "0"], ["","","","","...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool ...
soft = ["ch", "sh", "tz", "s", "x"] word = input() if any(word.endswith(s) for s in soft): print(word + "es") else: print(word + "s")
# python # -*- coding: def factorial(n): if n == 0 or n == 1: return 1 total = 1 for i in range(2, n + 1): total *= i print('%d'%(total)) return total if word[0] == '': Length = 0 else:
n=int(input()) f=1 for i in range(1,n+1): f=f*i print(f)
import unittest,math from sympy import * import sympy class TDD_TUTORIAL(unittest.TestCase): @classmethod def setUpClass(cls): cls.foo = 1 def test_tutorial(self): x,y=symbols('x,y') expr = cos(x) + 1 expr.subs(x, y) # Evaluating an expression at a point s=exp...
import random def roll(rolls, max_sides): total = 0 for roll in range(rolls): total += random.randint(1,max_sides) return total def threedsix(): result = roll(3,6) return result def print_scores(): print("STR: ", threedsix()) print("DEX: ", threedsix()) print("CON: ", threedsi...
import requests from bs4 import BeautifulSoup import smtplib import time URL = "https://www.amazon.ca/Samsung-RU7100-UN75RU7100FXZC-Canada-Version/dp/B07NC7N3G6/ref=sr_1_3?keywords=samsung+tv&qid=1577636170&refinements=p_n_size_browse-bin%3A17304154011&rnid=3236496011&s=electronics&sr=1-3" headers = {"User-Agent": 'M...
# add values to list aList=[] for number in range(1,11): aList.append(number) print("The value of aListis:", aList) # access list values by iteration print("\nAccessing values by iteration:") for item in aList: print(item, end=" ") print() # access list values by index print("\nAccessing valu...
a=eval(input("dati un nr")) b=eval(input("dati un nr")) for nr in range(a,b+1): #inclusiv b if nr%2!=0: print(nr,end=" ,")
# Browse the complete list of string methods at: # https://docs.python.org/3/library/stdtypes.html#string-methods # and try them out here first_name = 'donda' last_name = 'sasmita' # print Donda Sasmita print(first_name.capitalize() + " " + last_name.capitalize())
class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: # if grid is effectively empty, then there are no paths. if not grid or not grid[0]: return 0 path_length, answer = 0, 0 # to see when we reach end square if valid path by comparing to path length ...
class Solution: def integerReplacement(self, n: int) -> int: # intuitively want to make any n converge to 2^n because for shortest path # use binary representation # whenever n is even, then just divide by 2 # whenever n is odd, then increment whenever next neighbor is 1 # de...
#!usr/bin/env python import string import keyword alphas = string.ascii_letters + '_' nums = string.digits print('Welcome to Identifier Checker v1.1') myInput = input('Indentifier to test is: ') while len(myInput) == 0: myInput = input('''No identifier is entered. Please enter an identifier: ''') if myInput in k...
#!/usr/bin/env python import os ls = os.linesep fname = input('Enter filename: ') try: fobj = open(fname, 'r') fobj.close() print('%s already exists.' % fname) except IOError: all = [] print("\nEnter lines('.' by itself to quit).\n") # loop until user terminate input while True: entry = input('>>') if entr...
#You live 4 miles from thr university. #the bus drives at 25 mph but spends 2 minutes at the each of the 10 stops on the way . #how long will the bus journey take ? #alternativelyt , you could run to university. #you jog first time at 7mph ; then run the next two at 15 mph ; before jogging the last at 7 mph again . #w...
# OrderedDict() remembers the order of key addition and returns them in the same # order from an iterator from collections import OrderedDict from pprint import pprint quotes = OrderedDict([ ('Moe', 'A wise guy, huh?'), ('Larry', 'Ow!'), ('Curly', 'Nyuk nyuk!'), ]) for stooge in quotes: print(stooge) ...
class Person(): # it is not necessary to have an __init__ method in every class definition; # it's used to do anything that's needed to distinguish this object from # others created from the same class # the first parameter must be self def __init__(self, name): self.name = name class Email...
def doNothing(): pass # indicate that the function is empty intentionally def makeSound(): print('quack') def agree(): return True def echo(anything): return anything + ' ' + anything # default argument values are calculated when the function is defined # not when it is run def menu(wine, entree, de...
char_a_code = 65 char_z_code = 90 def encrypt_or_decrypt(text, shift, is_action_equal_to_encrypt = True): # Permet d'utiliser une seule fonction pour le chifrement et dechifrement if(not is_action_equal_to_encrypt): shift *= (-1) result_text = "" text = text.upper() for character in text: ...
import pygame, sys from pygame.locals import * from Paddle import * from SimpleBall import * from Scorer import * from random import randint import numpy as np ### Credit to Will Baumbach for the code that ### ### formed the starting point of this game ### ### https://github.com/WillBaumbach/Pong-Pyth...
p1 = "" p2 = "" while True: p1 = input("Player 1 enter your play: ") p2 = input("Player 2 enter your play: ") if p1 == "Rock" and p2 == "Scissors": print("Player 1 wins!") break elif p1 == "Scissors" and p2 == "Paper": print("Player 1 wins!") break elif p1 == "Paper"...
''' ME674 Soft Computing in Engineering Programming Assignment 1 Predicting Strength of High-Performance Concrete Using Artificial Neural Network Name = Mayank Pathania Roll No. = 204103314 Specialization = Machine Design Artificial Neural Network with Single hidden layer B...
""" This code implements a genetic algorithm for solving the multidimensional knapsack problem """ import random from collections import namedtuple from random import choices from random import random from utils import * from data import * def solution(): number_items = 6 number_knapsacks = 10 benefits = ...
# Working with the range() function # creating a list of numbers using the list() function with range() to provide the values # range() argument options: # single value range(4) output is 0,1,2,3 # start and end value range(1,5) output is 1,2,3,4. Think of a loop where the last value changed the result to False and e...
# Write a program that reads a file and prints the letters # in decreasing order of frequency. Your program should convert all the input # to lower case and only count the letters a-z. Your program should not count # spaces, digits, punctuation, or anything other than the letters a-z. # Find text samples from several d...
# Revise a previous program as follows: # Read and parse the “From” lines and pull out the addresses from the line. # Count the number of messages from each person using a dictionary. # # After all the data has been read, print the person with the most commits by # creating a list of (count, email) tuples from the dict...
# # **Using BeautifulSoup # import urllib.request, urllib.parse, urllib.error # from bs4 import BeautifulSoup # import ssl # # # Ignore SSL certification error # ctx = ssl.create_default_context() # ctx.check_hostname = False # ctx.verify_mode = ssl.CERT_NONE # # url = input('Enter - ') # html = urllib.request.urlopen(...
import math print (math) import random for i in range(10): x = random.randint(5, 10) print (x) random.randint(5, 10) t = [1, 2, 3] random.choice(t) def print_lyrics(): print("I'm a lumberjack, and I'm okay.") print("I sleep all night and I work all day.") print_lyrics() def repeat_lyrics(): ...
shrs = input('Enter hours: ') try: fvalhrs = float(shrs) srte = input('Enter rate: ') fvalrte = float(srte) except: print ('Error, please enter numeric input') quit() # converting string input to float fhrs = float(shrs) frte = float(srte) # computing pay for hours worked reg = fhrs * frte otp = ( ...
# Write a program to read through the mail box data and when you find line that starts with “From”, # you will split the line into words using the split function. # We are interested in who sent the message, which is the second word on the From line. # # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # You wil...
def rotate(array_list,length_n): x = array_list[length_n-1] for i in range(length_n-1,0,-1): array_list[i] = array_list[i-1] array_list[0] = x array_list= [1, 3, 5, 2, 6, 2] length_n = len(array_list) print ("Given array_list is") for i in range(0, length_n): print (array_list[i]...
# Solves the 8-puzzle using BFS # BFS provides an optimal solution # The algorithm works by traversing nodes in order of their depth or level (how many moves have been applied) # This ensures an optimal solution because of the level order traveral, we will never check deeper until all nodes # of a current level have be...
# By submitting this assignment, I agree to the following: # "Aggies do not lie, cheat, or steal, or tolerate those who do." # "I have not given or received any unauthorized aid on this assignment." # Name: Elayne Elphingstone # Section: 572 # Assignment: Lab1b, Act 2 # Date: September 9t...
#translator def translate(phrase): translation = "" for letter in phrase: if letter in "AEIOUaeiou": translation = translation + "g" else: translation = translation + letter return translation print(translate(input("Enter a phrase: "))) #will ask for input and chan...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 21 21:48:55 2019 Author: Dustin Burnham Lesson 3 Assignment Description: In this script I will generate arrays that contain both numeric outliers values of the incorrect type. The goal will be to clean these arrays for these outlier values by remov...
# -*- coding: utf-8 -*- import re class Retriever: def __init__(self, filename): self.alphabet = u'abcdefghijklmnopqrstuvwxyzåäö' self.lang_words = self.__read_vocabulary(filename) def __read_vocabulary(self, filename): """Returns language vocabulary from a file. The file sho...
# Sorting: Bubble Sort # https://www.hackerrank.com/challenges/ctci-bubble-sort/problem n = int(input().strip()) a = list(map(int, input().strip().split(' '))) count = 0 for i in range(n): for j in range(i+1, n): if a[i] > a[j]: a[i], a[j] = a[j], a[i]; count += 1 print('Array is sorted in %d swaps.\nFirst...
class Stack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def pop(self): return self.data.pop() def peek(self): return self.data[len(self.data) - 1] if __name__ == '__main__': s = Stack() s.push(1) s.push(2) s.push(3)...
from sys import maxsize # ============================================= # Note: Try to solve this task in O(n) time using O(1) additional space, where n is the number of elements in the list, # since this is what you'll be asked to do during an interview. # # Given a singly linked list of integers l and an integer k, ...
# Problem Set 4B # Name: Pat # Collaborators: # Time Spent: x:xx import string ### HELPER CODE ### def load_words(file_name): ''' file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters. Dep...
def get_available_letters(letters_guessed): ''' letters_guessed: list (of letters), which letters have been guessed so far returns: string (of letters), comprised of letters that represents which letters have not yet been guessed. ''' # FILL IN YOUR CODE HERE AND DELETE "pass" #make list o...
# This file gets the status of the device based on the status byte which is one of the bytes received by the computer with 'I' command def DeviceStatus(status): device_status=[] for i in range(8): # Because maximum 8 possible combinations possible. Read the Ricochet document for 'modes'. Nothing to do wit...
import smallestrangeheap import smallestrange list1 = [4, 10, 15, 24, 26] list2 = [0, 9, 12, 20] list3 = [5, 18, 22, 30] listOfLists = [list1, list2, list3] # http://www.careercup.com/question?id=16759664 # are the input lists always in sorted order? (for this test, let's assume yes) # upper or lower bound for in...
import forca; import adivinha_numero; print("*******************") print("Escolha o seu jogo!") print("*******************") print("(1) Forca (2) Adivinhacao") jogo_escolhido = int(input("Qual o jogo? ")) if( jogo_escolhido == 1 ): forca.jogar() elif( jogo_escolhido == 2 ): adivinha_numero.jogar() else: ...
def char_isalnum(string): for c in string: if c.isalnum(): return True return False def char_isalpha(string): for c in string: if c.isalpha(): return True return False def char_isdigit(string): for c in string: if c.isdigit(): return Tr...
# Create a class to hold a city location. Call the class "City". It should have # fields for name, latitude, and longitude. # TODO class City: def __init__(self, name, latitude, longitude): self.name = name self.latitude = latitude self.longitude = longitude def __repr__(self): ...
""" This module contains the low level text UI elements for the package textui. This module contains the functions that actually handle user input. Each function is configured so that the user input occurs within a while True loop. Input checking is done on the user input and the loop will not exit if an invalid value...
print("Witaj w programie, który wskazuje czy podana przez Ciebie liczba jest liczbą pierwszą") print('\n') print('Poniżej znajduję się krótkie menu, ktore pozwala Ci się poruszać po tym programie') print('\n') print('Napisz 1 aby podać liczbę') print('Napisz 2 aby zakończyć działanie programu') while(True): ...
import math import Swap import os os.system('cls') def Area(a, b, c, d): if d == 0: p = (a + b + c)/2 return math.sqrt(p * (p-a) * (p-b) * (p-c)) def AreaX(a, b, c, d): sides = [a, b, c, d] for i in range(len(sides)): if sides[i] == 0: sides.remove(sid...
print("Calculos para un cuadrado") lado=int(input("Ingrese el lado de un cuadrado")) area=lado*4 perimetro=lado**2 diagonal=lado*(2**(1/2)) print("El area del cuadrado es : " + str(area)) print("El perimetro del cuadrado es : " + str(perimetro)) print("La diagonal del cuadrado es : " + str(diagonal))
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-24 Last_modify: 2016-03-24 ****************************************** ''' ''' There are a total of n courses you have to...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-05-10 Last_modify: 2016-05-10 ****************************************** ''' ''' According to the Wikipedia's article: "The...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-05-07 Last_modify: 2016-05-07 ****************************************** ''' ''' Write a program to find the n-th ugly numb...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-01-21 Last_modify: 2016-01-21 ****************************************** ''' ''' Given n pairs of parentheses, write a func...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-05 Last_modify: 2016-03-05 ****************************************** ''' ''' Given a binary tree, determine if it is a ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-27 Last_modify: 2016-03-27 ****************************************** ''' ''' Find all possible combinations of k number...