text
stringlengths
37
1.41M
import math # -------- # returns the perpendicular distance from point to Line(linaA, lineB) # def perpendicularDistance(lineA, lineB, point): t = lineB[0] - lineA[0], lineB[1] - lineA[1] # Vector ab dd = math.sqrt(t[0] ** 2 + t[1] ** 2) # Length of ab t = t[0] / dd, t[1] / dd # unit vector of a...
number_input = input("Enter a number: ") # try the execution inside the try try: x = int(number_input) print(x*10) # if there is an error, it goes to except except Exception as error: print("There is an error. Please try again") # finally block is always going to be executed finally: print("finally blo...
# ask user to enter a number save it to variable x x = input('enter the first number: ') # ask user to enter a number save it to variable y y = input('enter the second number: ') # ask user to enter the operation +, -, *, / operation = input("enter +, -, *, /: ") # convert from string to integer / number x_int = int(...
options = ('pizza', 'burger') # you can access tuple by its index print(options[0]) # example of the use of tuple genders = ('male', 'female') classes = (1,2,3,4,5,6)
# ask user to enter email address email = input('Enter your email address: ') # check if the email has @, if yes print 'your email is valid', else print 'enter the correct email' if email.count('@') > 0: # if the email has . after the sign john.doe@gmail.com at_position = email.index('@') dot_position = em...
class BackNForthIterator(object): ABOVE = 0 BELOW = 1 def __init__(self, list_): self.list = list_ middle_of_list = len(self.list)//2 self.above = middle_of_list self.below = middle_of_list self.previous_iteration = None def __iter__(self): return...
# HW1 number = int(input('Введите число: ')) print(number + 2) # HW2 number = int(input('Введите число от 0 до 10: ')) while 10 < number > 0: print('Введено не верное число') number = int(input('Введите число от 0 до 10: ')) else: print(number ** 2) # HW3 #Пациент в хорошем состоянии, если ему до 30 лет и...
# card 2 attributes # rank 2-10 J K Q A # suit H C S D import random def card_generator(): #generate a number between 1 and 13 to correspond to rank card_num = (random.randint(1,13)) #randomply pair that number with a suit option suit = ['H', 'C', 'S', 'D'] random_suit = random.randint(0,3)...
# capitalize # # You are asked to ensure that the first and last names of # people begin with a capital letter in their passports. # For example, alison heck should be capitalised correctly as Alison Heck. def solve(s): s_list = s.split() s_list_cap = [] for elem in s_list: print(elem) s_list_cap.appen...
# Write a method, overlap(list1, list2), which: # Accepts two lists, list1 and list2 # Returns a list with the elements in both list1 and list2. The ordering of the returned list is not important. # Examples # overlap(['a'], []) should return [] # overlap(['a'], ['a']) should return ['a'] # overlap(['b', 'a', 'n', 'a...
list1 = [1, 2, 5, 4, 4, 3, 6] list2 = [3, 2, 9, 7, 10, 7, 8] def ret_diff(x): return x[1]-x[0] x = sorted(zip(list1,list2),key=ret_diff) for i in x: print(i)
# Product Inventory Class # manages an inventory of products. # keeps track of various products and can sum up the inventory value. class Product(object): def __init__(self, price, ID, quantity): self.price = price self.id = ID self.quantity = quantity class Inventory(object): ...
#Use a list comprehension to create a new list first_names #containing just the first names in names in lowercase. names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"] first_names = [name.split()[0].lower() for name in names] #for name in names: #name.split()[0].islower # print(...
""" This module contains functions for reading CSV files containing pressure and volume data. """ import numpy def read_csv(input_file, delimiter=",", x="p", sigma_x="sigma_p", y="v", sigma_y="sigma_v"): """ Reads a CSV file with x and y data and standard deviation columns. Parameters ...
import turtle import random #people list will store all the people objects people =[] #launch window and set up GUI wn = turtle.Screen() wn.bgcolor("black") wn.title("Simulator") #initialize patient0 patient0 = turtle.Turtle() #method will set up the amount of people objects specified by user def setPe...
#1. def Biggle(lis): for x in range(0,len(lis)): if lis[x]>0: lis[x]="big" return lis #2. def CountPositives(lis): count=0 for x in range(0,len(lis)): if lis[x]>0: count+=1 lis[len(lis)-1]=count return lis #3. def SumTotal(lis): sum=0 for x in rang...
#import game modules import sys, pygame from pygame.sprite import Sprite from pygame.locals import * """class that defines and characterises projectile objects within the game""" class EnemyProjectile(Sprite): #initialises projectile object upon invocation def __init__(self, spawnCoords): py...
items = [('product-1', 12), ("product-2", 10), ('product-3', 8)] price = [item[1] for item in items] # print(price) fil = [item for item in items if item[1] >= 10] print(fil) #list comprehension is a great feature
class Point: default_color = 'Red' # it's a class level attribute def __init__(self, x, y): # these are instant level attributes self.x = x self.y = y def drawing(self): print(f'Point ({self.x}, {self.y})') # if we change class level attribute value,it is changed for all...
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p1 = Point(x=1, y=2) p2 = Point(x=1, y=2) print(p1.x) print(id(p1)) print(id(p2)) print(p1 == p2)
class Point: def __init__(self, x, y): self.x = x self.y = y #a decorator for defining a class method, it's a way to extend the # behaviour of a method or function @classmethod def zero(cls): return cls(0,0) # this is an instant level method def drawing(self): ...
letters = ['a', 'b', 'c', 'd'] letters.append('e') # append at the last letters.insert(0, '-') # insert at any index letters.pop() # remove last item letters.pop(0) # remove at a given index letters.remove('b') # remove by searching an item del letters[0:2] # delete a range of object letters.clear() # clear all...
operand1 = 95 operand2 = 64.5 print operand1, "+", operand2, "=", operand1 + operand2 print operand1, "-", operand2, "=", operand1 - operand2 print operand1, "*", operand2, "=", operand1 * operand2 print operand1, "/", operand2, "=", operand1 / operand2 print operand1, "%", operand2, "=", operand1 % operand2 #I solv...
# def add(num1, num2): # return num1 + num2 # # 1+1 # 2 # 2+2 # 4 # 2-2 # 0 class Calculator(): def __init__(self, expression): print("Starting calculator.. ") self.expression = expression self.operator = self.define_operator() # function -- split with '+' def split_by_plus...
nilai = 90 if(nilai > 85): print("Grade A") elif(nilai == 70): print("Grade B") elif(nilai == 60): print("Grade C") elif(nilai == 50): print("Grade D") else: print("Tidak Lulus")
string = "Number Guessing Game" string2 = "Guess a number (1-9)" print(string) print(string2) number = 9 guess = input("Enter Your guess:-") if(guess < 9): print("You Lose") elif(guess == number): print("YOU WIN")
import socket import time # start of the application if __name__ == '__main__': # checks if the server is connected to a client isConnected = False # contains the socket data mySocket = None # checks if the Server is currently running isRunning = True while isRunning == True: w...
from M0227_Basic_Calculator_II import Solution as Basic_Calculator class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ return Basic_Calculator().calculate(s) print(7, Solution().calculate("3+2*2")) print(1, Solution().calculate("3/2")) print(5...
from typing import List class Solution: def findCircleNum(self, M: List[List[int]]) -> int: if not M or not M[0]: return 0 from collections import deque result, n = 0, len(M) for i in range(n): if M[i][i]: result += 1 queue = deque() ...
class DequeNode: def __init__(self, k = 0, x = 0): self.key = k self.val = x self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.cap = capacity self.cnt = 0 self.head = None self.tail = None self.pool...
from utils import TreeNode from typing import List from M0102_Binary_Tree_Level_Order_Traversal import travel_level class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] return [[node.val for node in (nodes if level % 2 else reversed(nodes))] for leve...
class Solution: def minDistance(self, word1: str, word2: str) -> int: if not word1 or not word2: if not word1 and not word2: return 0 else: return len(word1) if word1 else len(word2) n1, n2 = len(word1), len(word2) memo = [[0] * (n2 + 1) for _ in range(n1 + 1)] ...
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ sign = 1 if x >=0 else -1 x, y = x if sign > 0 else -x, 0 while x > 0: y = y * 10 + x % 10 x //= 10 y *= sign return 0 if y < -2**31 or y > 2...
class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and n & (-n) == n def isPowerOfTwo2(self, n: int) -> bool: return n > 0 and n & (n - 1) == 0 test = Solution().isPowerOfTwo print(True, test(1)) print(True, test(16)) print(False, test(218)) # Given an integer, write a fun...
from utils import TreeNode class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 from collections import deque queue, cur_level, max_width = deque(), 0, 0 start_index, last_index = 0, 0 queue.append((1, 0, root)) while queue: ...
from sys import argv as arguments ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if len(arguments) != 3: print("2 arguments required!") exit() from_filename = arguments[1] to_filename = arguments[2] print("imput " +from_filename) print("output: " + to_filename) from_file = open(from_filename, 'r', encoding='utf8') ...
import tempfile import os class File(object): def __init__(self, path): self.path = path self.file = open(os.curdir + path, 'a+') self.file.write('file opened!') def write(self, text): self.file.write(text) def __add__(self, other): data = self.get_d...
from random import randrange def genTen(): for _ in range(10): grade = 'A' score = randrange(60,101) if 80 < score <= 90: grade = 'B' elif 70 < score <= 80: grade = 'C' elif score <= 70: grade = 'D' print("Score: {}; Your grade is ...
#Find and Replace """ In this string: words = "It's thanksgiving day. It's my birthday,too!" print the position of the first instance of the word "day". Then create a new string where the word "day" is replaced with the word "month". """ words = "It's thanksgiving day. It's my birthday,too!" print(words.find('day')) ...
# this code is not mine; taken from http://interactivepython.org/runestone/static/pythonds/SortSearch/TheMergeSort.html def mergeSort(L): print("Splitting ",L) if len(L)>1: mid = len(L)//2 lefthalf = L[:mid] righthalf = L[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 ''' while i < len(...
#!/usr/bin/env python3 class CoupleValue: """CoupleValue class. This class implements a couple value used in argument object. attr: criterion_name: value: """ def __init__(self, criterion_name, value): """Creates a new couple value. """ self.__criterion_na...
# -*- coding: utf-8 -*- # @Author : JoinApper # @data : 2019/5/13 """ 栈的实现 """ from Node import Node from Empty import Empty class LinkedStack(object): def __init__(self): """ 创造一个空栈 """ self._head = None self._size = 0 self.iter_pointer = None def __len__...
# -*- coding: utf-8 -*- # @Author : JoinApper # @data : 2019/5/13 """ 队列的实现 """ from Node import Node from Empty import Empty class LinkedQueue(object): def __init__(self): """ 创建一个空队列 """ self._head = None self._tail = None self._size = 0 self.iter_po...
import time import numpy as np import simpleaudio as sa # This function generates the audio tone by creating a 650hz SIN wave def tone(duration, frequency=650, sampling_rate=44100): """ Generates a simple audio wave object from a specified frequency and duration. """ samples = np.sin(2*np.pi*np.arang...
#练习6.1 导演为剧本选主角 def out(actor): print("%s开始参演这个剧本"%actor) actor=input("导演选定的主角是:") out(actor) #练习 6.2 模拟美团外卖商家的套餐 package={"考神套餐":"13元","单人套餐":"9.9元","情侣套餐":"20元"} def printTest(**para): for key,value in para.items(): print('{:s}{:s}'.format(key,value)) printTest(**package) #练习6.3 根据生日判断星座 Horoscope...
# so the least product of 2 3 digit numbers is 10,000 and the largest is 998,001 import math def largestPalindrome(): for n in range(998001, 10000, -1): if str(n) == str(n)[::-1] and Factors(n) == True: return n def Factors(x): factors = [] for num in range(2, int(math.sqrt(x)) + 1): ...
def part_one(input): return sum([contains_only_unique_elements(line) for line in input.split('\n')]) def contains_only_unique_elements(line): words = line.split() return len(words) == len(set(words)) def part_two(input): return sum([not contains_anagrams(line) for line in input.split('\n')]) def c...
# -*- coding: utf-8 -*- """ Date: 28/08/2015 author: peyoromn """ def decimal_to_binary(decimal): bstring = "" while decimal > 0: remainder = decimal % 2 decimal = decimal / 2 bstring = str(remainder) + bstring return bstring def main(): decimal = input("En...
#! -*- coding: utf-8 -*- import random import time from threading import Thread class SleepyThread(Thread): def __init__(self, number, sleep_max): Thread.__init__(self, name="Thread "+str(number)) self._sleep_interval = random.randint(1, sleep_max) def run(self): p...
#! -*- coding: utf-8 -*- """ Program: filesys.py Author: Ken Provides a menu-driven tool for navigating a file system and gathering information on files. """ import os import os.path QUIT = '7' COMMANDS = ('1', '2', '3', '4', '5', '6', '7') MENU = """1 List the current directory 2 Move up 3 M...
# -*- coding: utf-8 -*- """ Created on Mon Mar 21 19:14:16 2016 @author: peyo """ ## # Remove the outliers from a data set. # def remove_outliers(data, num_outliers): retval = sorted(data) for i in range(num_outliers): retval.pop(0) return retval def ...
#! -*- coding: utf-8 -*- # Class Employee with static method - pag 322 class Employee(object): number_employees = 0 max_employee = 10 @staticmethod def is_crowded(): return Employee.number_employees > Employee.max_employee # create static method #is_crowded = staticme...
#! -*- coding: utf-8 -*- # aproximación de la raíz cuadrada de un número def main(): """Aproximación de la raíz cuadrada de un número""" # Número del cual queremos conocer su raíz cuadrada objetivo = int(input("Escoge un entero: ")) # Margen de error en la respuesta |respuesta^2 - objeti...
# -*- coding: utf-8 -*- """ Input: Three arguments. A grid as a tuple of tuples with integers (1/0), a row number and column number for a cell as integers. Output: How many neighbouring cells have chips as an integer. Example: count_neighbours(((1, 0, 0, 1, 0), (0, 1, 0, 0, 0), ...
# -*- coding: utf-8 -*- # Converting temperatura from Celsius to Farenheit from __future__ import division def main(): C = 21 F = (9/5)*C + 32 print "{} ºC -> {} ºF ".format(C, F) if __name__ == "__main__": main()
"""ascii table letters mapped to numbers""" LOWER = 33 UPPER = 127 def main(): users_char = input("Enter a character: ") print("Tha ASCII code for {} is {}".format(users_char, ord(users_char))) users_num = get_number(LOWER, UPPER) print("The character for {} is {}".format(users_num, chr(users_num))) ...
"""Intermediate exercise with lists of numbers""" def main(): numbers = [] count = 1 number = get_number(count) while number > 0: count += 1 numbers.append(number) number = get_number(count) print("The first number is: {}".format(numbers[0])) print("The last number is:...
""" CP1404/CP5632 Practical (Prac_08) Let's Drive Program (From Scratch) """ from prac_08.taxi import Taxi from prac_08.silver_service_taxi import SilverServiceTaxi MENU = """q)uit, c)hoose taxi, d)rive""" def main(): taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2), SilverServiceTaxi...
import math ABS_TOL = 0.0001 def display_menu(): print(); print() print('(1) Show the even numbers from x to y') print('(2) Show the odd numbers from x to y') print('(3) Show the squares from x to y') print('(4) Exit the Program') print() def main(): display_menu() response = input() ...
nombre = '' nombres = [] i = 1 while 1: nombre = input("Entrez le nombre numero {0} : ".format(i)) if nombre.isdigit(): if int(nombre) == 0: break nombres.append(int(nombre)) i += 1 plus_grand = nombres[0] for i in nombres: if i > plus_grand: plus_grand = i pr...
import numpy as np """ CONSTRUIR O MELHOR POLINOMIO P2(X) QUE SE AJUSTE AOS DADOS PELO MÉTODO DOS MINIMOS QUADRADOS """ def poli(xData,yData,m): a = np.zeros((m+1,m+1)) b = np.zeros((m+1,1)) s = np.zeros(2*m+1) for i in range(len(xData)): temp = yData[i] for j in range(m+1): ...
#-*- coding:utf-8 -*- import os def menu(): os.system('cls') print("¿Qué figura deseas hacer?") print("Rectángulo --presiona 1") print("Un triángulo --presiona 2") optionMenu = raw_input("Selecciona la opción que desees >> ") if int(optionMenu) == 1: rbase= raw_input("Medida de la bas...
from random import* print("\n\n******** Menu ********") print("Bienvenue dans le jeu des allumettes!") print("Instructions: choisissez un nombre d'allumette puis decidez du nombre (entre 1 et 3) a enlever.\n A son tour, l'autre joueur fera de meme et ainsi de suite jusqu'a ce qu'il n'y ait plus d'allumett...
from PyPDF2 import PdfFileReader, PdfFileWriter print(''' Welcome to the password protector for pdf •••by Harinath''' ) pdfwriter=PdfFileWriter() a=input("Enter pdf location :") name= input("Enter pdf name without extension : ") pdf= PdfFileReader(a+name+".pdf") for pagenum...
" 1 Sum all divisors of an integer" def sum_of_divisors(n): m = 0 for x in range( 1, n + 1): if n % x == 0: m = m + x return m " 2 Check if integer is prime" def is_prime(n): return sum_of_divisors(n) == (n + 1) " 3 Check if a number has a prime number of divisors" def prime_numb...
print("MASUKKAN LUAS LINGKARAN DENGAN JARI-JARI") print("========================================") II = 22/7 r = float(input("Masukkan jari-jari lingkaran: ")) luas = II*(r*r) print("Luas lingkaran dengan jari-jari {} adalah {:.2f} cm\u00b2".format(r, luas))
# Question 10 # items = 5 # Optional input method: int(input("How many items are there? ")) # priceList = [] for prices in range(items): prices = int((input("What is the price of the item? "))[:-1]) priceList.append(prices) print("The total price is", str(sum(priceList))) print("The average pric...
import sys import math def isPrime(number): if number == 1: return False elif number < 4: return True elif number % 2 == 0: return False elif number < 9: return True elif number % 3 == 0: return False else: r = round(math.sqrt(num...
#QuickSort #1. choose any element to the pivotList #2. divide all the other elements into 2 partitions, > pivot and < pivot #3. use recursion to sort both partitions #4. finally join the two sorted lists with the pivot def quickSort(alist): less = [] pivotList = [] more = [] if len(alist) <= 1: ...
# define two variables x = "Python Class" y = "ABC world of knowing" print("Welcome to "+ x+" from "+ y) # instead we can use % operator print("Welcome to %s from %s" %(x, y)) print("Welcome to %s from %s" %("Python Class", y)) # Now let's use format method which more efficient print("Welcome to {} from {}".format(x...
# list.append(x) -- Add an item to the end of list # list.insert(i, x) -- Insert an item at a given position # list.remove(x) ---Remove the first item from the list whose value is equal to x # list.pop([i]) ---Remove the item at the given position in the list, and return it. If no index is specified, a.pop() remove...
# LIBRARY from random import randint # VARIABLE # Berisi angka secara random dari 0 - 100 sebanyak 100 angka #arr = [randint(1,100) for i in range(0,100)] def sort_numbers(s): for i in range(1, len(s)): val = s[i] j = i - 1 while (j >= 0) and (s[j] > val): s[j+1] = s[j] ...
#!/usr/bin/python saori= raw_input("ingrese caracter: ") def caracter(saori): if ((saori == "a") or (saori == "e") or (saori == "i") or (saori == "o") or (saori == "u")): return True else: return "false" caracter (saori) print (caracter(saori))
import random def verify_sort(a): for i in range(1, len(a)): if (a[i-1] > a[i]): raise Exception("Sort is invalid at {0} position ({1} > {2})".format(i, a[i-1], a[i])) def generate_random_array(length): return [int(1000 * random.random()) for _ in range(length)]
""" The UnionFind data structure provides an efficient way to respond to queries regarding the connectivity between a set of elements. Connectivity queries and the linkage of the elements is provided through two operations: - Find(p) - returns an integer that indicates the connected component in which p belongs ...
""" A minimum priority queue which allows clients to associate an integer with each key. """ class IndexedPriorityQueue: def __init__(self, maxItems): self.maxItems = maxItems self.N = 0 # the binary heap, contains indexes self.heap = [None for _ in range(maxItems)] # map...
""" Regular expression can be modelled by non-deterministic finite state automata (NFAs). As there are potentially multiple transitions from each state of the automaton, the next state cannot be computed deterministically . Instead all the possible transitions must be examined and considered at the same time. The NFA ...
category = int(input('원하는 음료는 1.커피 2.주스')) if category == 1: menu = int(input('번호 선택? 1. 아메리카노 2. 카페라테 3. 카푸치노')) if menu ==1: print('1.아메리카노 선택') elif menu ==2: print('2.카페라테 선택') elif menu ==3: print('3.카푸치노 선택') else: menu = int(input('번호 선택? 1. 키위주스 2. 토마토주스 3...
print('查看什么三角形') print('请输入三角形的第一条边长') a=input() a=int(a) print('请输入三角形的第二条边长') b=input() b=int(b) print('请输入三角形的第三条边长') c=input() c=int(c) if a+b>c or a+c>b or b+c>a: if a==b and b==c : print('这是一个全等三角形') elif a==b or b==c or c==a : print('这是一个等腰三角形') elif a*a+b*b==c*c or a*a+c*c==b*b or b*...
# ********************************************************** # Assignment: Project 16: Password Generator # # Description: Write a password generator in Python. Be # creative with how you generate passwords - strong passwords # have a mix of lowercase letters, uppercase letters, numbers, # and symbols. The passwords ...
import math import time def gear_ratio (level1, level2): #Accepts lists as arguements. Lists correspond to series of Pitch Diameters #12, 18 - Idler, 36 #12, 13, 13, 20 # Thumb: 20, 20 gear_ratio1 = level1[2] / level1[0] gear_ratio2 = level2[3] / level2[0] total_gear_ratio = gear_ratio1 * gear_...
# ********************************************************** # Assignment: Project 15: Reverse Word Order # # Description: Write a program (using functions!) that asks # the user for a long string containing multiple words. # Print back to the user the same string, except with # the words in backwards order. # # Auth...
# ********************************************************** # Assignment: Project 18: Cows and Bulls # # Description: Write a password generator in Python. Be # creative with how you generate passwords - strong passwords # have a mix of lowercase letters, uppercase letters, numbers, # and symbols. The passwords shou...
# ********************************************************** # Assignment: Project 12: List Ends # Description: # # Author: Aditya Sharma # # Date Start: (2018/08/17) # Date Completed: (2018/08/17) # # Completion time: 5:45 hours # # Honor Code: I pledge that this program represents my own # program code. I received...
#!/usr/bin/env python3 class Node: def __init__(self, word = None): self.children = {}; self.word = word class MultiwayTrie: def __init__(self): self.root = Node(); self.size = 0; self.iter_s = [self.root] def __len__(self): return self.size def __iter__(self): return se...
""" Find a package in the Python standard library for dealing with JSON. Import the library module and inspect the attributes of the module. Use the help function to learn more about how to use the module. Serialize a dictionary mapping 'name' to your name and 'age' to your age, to a JSON string. Deserialize the JSON...
""" Write a function to write a comma-separated value (CSV) file. It should accept a filename and a list of tuples as parameters. The tuples should have a name, address, and age. The file should create a header row followed by a row for each tuple. If the following list of tuples was passed in: [('George', '4312 Abbey...
import cmath a=float(input("Enter first side of triangle: ")) b=float(input("Enter second side of triangle: ")) c=float(input("Enter third side of triangle: ")) s=(a+b+c)/2; Area=cmath.sqrt(s*(s-a)*(s-b)*(s-c)) print(Area)
import numpy as np import matplotlib.pyplot as plt def computeCost(X, y, theta): m = y.size J = 0.0 h = X.dot(theta) J = np.sum(np.square(h-y))/(2*m) return J def gradientDescent(X, y, theta, alpha, iterations): m = y.size J_history = np.zeros((iterations, 1)) for iter in range(iter...
n = input("¿Como te llamas:? ") print(len(n), "letras") #OK Otra forma mas fea a = 0 for i in n: a = a + 1 print(str(a) + " letras")
##OutputSymbols #def output_symbols(): hours = int(input("hours: ")) total = 21 * hours print("£{0}".format(total))
##Function ?Improvement Exercise ##Times-table Tester import random print("Times-table tester") print() #Getting the times tables to be tested on def get_questions(): timesTable = input("Which times-table do you want to be tested on? ") timesTable = int(timesTable) return timesTable #It th...
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import Counter import math # Compute the mean. def findMean(n, arr): sumNum = 0 for i in arr: sumNum += i mean = sumNum/n return mean #compute the median def findMedian(n, arr): arr.sort() ...
# coding=UTF-8 # 创建文件,并写入文件 import urllib # # f = open("t.txt", "w") # f.write("写入t.txt") # f.close() # # # 读取文件 # f = open("t.txt", "r") # str = f.read() # print str # # # python 异常处理 # try: # x = int(input("Please enter a number: ")) # except (NameError, ValueError) as err: # print("Oops! That was no valid ...
from graphics import * from math import sqrt from random import random from time import clock import sys #Global variables ''' Dictionaries sharing the same key, to make them easily serviceable. ''' #B pls ACTIVE = {"REFLECT":False,"SPEED":False,"DOUBLE-POINTS":False,"MAGNET":False,"REVERSE":False} TIMER_DEFAULTS =...
print('hello world') x = 5 y = 3 if x < y: print(f"'x' is the winner: {x}") else: print(f"'y' is the winner: {y}")
import numpy as np import matplotlib.pyplot as plt Notes = ''' nth order Taylor method (n = 2, 3, 4, 5): Function Name: Taylor Inputs: y0: Initial condition h = step size a: starting Time b: ending Time plot: Binary input Default plot = 0: No plo...
#Ejercicio 8 num = (int(input('Ingrese numero '))) if num >= 0: if str(num) == str(num)[::-1]: print('%i es capicua' % num) else: print('%i no es capicua' % num)
#Ejercicio 16 Realizar un programa que cuente los numeros pares entre el 1 y un numero ingresado por el usuario num = int(input('Intruzca un numero y se le dira cuales son y cuantos numeros pares son los que hay entre 1 y el numero ingresado ')) print (f'Numero ingresado: {num}') def numPar (lista): pares =...
""" Graphical version of battleship game @author: Eetu Karvonen Game uses 'pyglet' -library to draw game window and to handle mouse clicks Main game logic is in 'on_mouse_press()' -function. Global variable 'state' holds the state of the game. 'game.py' -library handles boards """ import pyglet import random impo...