text
stringlengths
37
1.41M
import pygame import sys import time import itertools from pygame import sprite from pygame.locals import * from floors import * # from features import * # from traversal import * from interface import * """ This is the main module, where the primary body of the program is executed. """ """ <<<<[HELPER FUNCTIONS]>>>...
def swap(array, i, j): x = array[i] array[i] = array[j] array[j] = x return array def insertion_sort(array): print "input: " + str(array) array_length = len(array) for x in range(0, array_length - 1): if array[x] > array[x + 1]: for y in range(x + 1, 0, -1): ...
class Card: """ This is the basic card class that will be extended to use for more specific card types. """ __suit = None __rank = None def __init__ ( self, rank, suit ): self._rank = rank self._suit = suit def __repr__ ( self ): return f"Card(\"{self._rank}\",\"{se...
class User: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name def describe_user(self): print(f"First name: {self.first_name}, Last name: {self.last_name}") def greet_user(self): print(f"Greetings of the day, {self.first_name}!"...
def is_isogram(string): """ Check whether given string is an isogram or not. Isogram is a word which contains only unique letters, ignoring whitespaces and hyphens. Also, upper/lower case differences are ignored. >>> is_isogram("first") True >>> is_isogram("FIRST word") False "...
def to_rna(dna_strand): """ Provides RNA complement for DNA sequence. Rules are the following: * `G` -> `C` * `C` -> `G` * `T` -> `A` * `A` -> `U` """ result = "" for symbol in dna_strand: result += convert_symbol(symbol) return result def convert_symbol(symbol): ...
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' a = 3 b = 5 x = 1 result = 0 while x < 1000: if (x % a == 0) or (x % b == 0): result = result + x x += 1 print(result)
x=int(input('Enter the number')) if x==0:print(x,'is zero') elif x%2== 0: print(x,'is even') else: print(x,'is odd')
from threading import Thread, current_thread def displaynumber(): i = 0 print(current_thread().getName()) while(i<=10): print(i) i+=1 print(current_thread().getName()) t= Thread(target=displaynumber) t.start() #for naming a thread
'''from tkinter import * root = Tk()#to make the window root.geometry('300x300')#to make the size of the window c = Canvas(root, height=250, width=300, bg='blue')#to make a paint window c.pack() r= c.create_rectangle(20,20,100,100,fill='red') l1 = c.create_line(5,5,200,200, width = 10) o = c.create_oval(20,20,10...
from functools import reduce lst=[5,10,15,20] result=reduce(lambda x,y:x+y, lst) print(result) #this is used to find sum of all things in the list
import re str = 'Take 1 up one 23 idea.One idea 45 at a time 12-11-2020' result = re.search(r'o\w',str) print(result) #group is for value coming from search result = re.findall(r'o\w\w',str) print(result) result = re.match(r'T\w\w',str) print(result)#putting group() write the letter direct result = re.sub(r'one','two...
class InvalidPasswordException(Exception): pass while True: try: p = input('Enter a password with of minimum length 8 characters: ') if len(p) < 8: raise InvalidPasswordException elif len(p) >= 8: print ('Your password is saved!') break ...
import random def number(z,x): if abs(z-x) and (z-x) == 1: print('too close') print('this is the correct number ',x) elif abs(z-x) and (z-x) ==2: print('close') print('this is the correct number ',x) elif abs(z-x) and (z-x) ==3: print('not close') print('this ...
#!/usr/bin/env python # ------------------------------ # ORIGINAL CODE # ------------------------------ # % Listing 05.02 cylinder function with multiple results # function [area, volume] = cylinder(height, radius) # % function to compute the area and volume of a cylinder # % usage: [area, volume]=cylinder(height,...
expr = input() if expr.find('+') != -1: ns = expr.split('+') if len(ns) == 3: print(int(ns[1]) + int(ns[2])) else: print(int(ns[0]) + int(ns[1])) else: ns = expr.split('-') if len(ns) == 3: print(abs(-int(ns[1]) - int(ns[2]))) else: print(abs(int(ns[0]) - int(ns[1...
#Exercise 29: What If (If statement) """ #If statement creates what is called a "branch" in the code. It creates more branches i.e. more ways which code will be executed based upon boolean result of the statement. #If statement tells your script, "If this boolean expression is True, then run the code under it...
# Exercise 10 What was that? Escape sequences (or "\" backslash) #\t adds a horizontal tab into result #\n adds a new line #\\ escapes one \ and print the other \ tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." # triple quotes mark a string through more...
#Make your own game #basic description - game idea """ Car Competition there are 3 cars Skoda, Nissan and Audi competing in tournament consisting of 5 races. You need to choose your car and throw dice to compete. You can also bet each race which car wins. For each race there are points distributed based on hig...
# 5 More Variables and Printing #Variables continued... my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' # % (modulo) + letter -> are "formatters" # They tell Python to take the variable on the right and p...
import math import rospy from turtleAPI import robot from pid import pidController #END = (-1,0) # test destination # START = (0,0,3*(math.pi)/2) # test start """ FIND STEERING ERROR Calculate steering error to get to point """ def steeringError(): # get current position curr_pos = turtle.getPositionTup() ...
def fac(num): #Same function from Problem15 fac = num if(num % 2 == 0 and num != 2): limit = 2 else: limit = 3 partial = num - 2 toAdd = num while True: toAdd += partial fac *= toAdd partial -= 2 if partial < limit : break ...
import time def sieve(limit): sum = 2 primes = list(range(2,limit+1)) for i in range(2,limit-1): primes[i] = True for p in range(3,len(primes),2): if primes[p] == True: cur = p sum +=p while cur+p < limit-1: cur += p ...
#!/usr/bin/python import random import people import characterClasses import races #Creating player character def characterCreation(): playRaces = ["human","elf","dwarf","half-elf"] alignments = ["chaotic good","neutral good","lawful good","chaotic neutral","neutral","lawful neutral","chaotic evil","neutral evil","l...
import collections import csv def extract_top_words(word_list, count=5): counts = collections.Counter(word_list) return counts.most_common(count) filepath = 'data/harvey/with_harvey_tag/clean/harvey_2017_08_28.csv' tweet_by_city = dict() with open(filepath) as filepointer: text_reader = csv.reader(filep...
celsius=float(input("Enter the temperature in degree celsius:")) fahrenheit = (celsius * 1.8) + 32 print("Fahrenheit=",fahrenheit)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Get count of vowels in string """ def getCount(inputStr): num_vowels = 0 vowels = ['a','e','i','o','u'] #set vowels for i in inputStr: #each character in string for value in vowels: if i == value: #if is in vowels num_v...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Takes list of strings. If string is exactly 4 characters long, adds to friends list. returns friends """ def friend(x): friends=[] for item in x: if len(item) == 4: friends.append(item) return friends
import os # Sets a project's working directory. # Looks for a file named .anchor in the current directory. If it can't # find one, go up one level and look again. Keep looking until the file # is found or the recursion limit is reached. def set_anchor(starting_point = os.getcwd()): dirs = [] path = starting_p...
import numpy as np import pandas as pd from sklearn import neighbors class Imputer: def fit(self, X, column, k=10, is_categorical = False): """Fit a knn classifier for missing column Args: X(pandas.dataframe): dataframe column(str): column name to be imputed k(int): number of nearest neighbors, default 1...
# lab12.py # YOUR NAME(S) AND NETID(S) HERE # DATE COMPLETED HERE """Loop invariant functions""" def num_space_runs(s): """Returns: The number of runs of spaces in the string s. A run is a collection of adjacent spaces. We need a non-space character in-between to break up runs. Example: num...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/3/5 下午7:01 # @Author : Aries # @Site : # @File : itertools_moudle.py # @Software: PyCharm # Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数 # todo 无限的迭代器 import itertools # it = itertools.count(1) # for i in it: # print(i) # todo 无限重复当前str cycle()...
# -*-coding:utf-8-*- import functools import math import time def my_abs(x): if x >= 0: return x else: return -x def my_abs_check(x): # 类型检查 if not isinstance(x, (int, float)): raise TypeError('哈哈哈') if x >= 0: return x else: return -x # 返回多个值 # math...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/5 下午10:55 # @Author : Aries # @Site : # @File : err_raise.py # @Software: PyCharm print("------------------------------------------抛出问题---------------------------------------------------") # class FooError(ValueError): # pass # # # def foo(...
String = list(input()) temp = "" for i in range(0,len(String)-1,2): temp= String[i] String[i]=String[i+1] String[i+1]=temp print("".join(String))
str1 = list(input()) str2=[] for i in str1: str2.append(i) k=str1.reverse() if(str2==str1): print("YES") else: print("NO")
""" Title : Hashtag.py Source : Module 1 Exam Purwadhika no.1 Summary : Create a function called Hashtag that generate hashtag which accepting string separated by space as presented the below with following rules (15 Points): Feat Req : - It must start...
""" This python program reads a ngram counting file and outputs a language model in APRA format """ import sys import math import operator def unigram(input_ngram): """ extract the unigram from input ngram """ uni = {} count = 0 for line in input_ngram: split_line = line.split('\t') co...
""" This python program reads a training file and outputs the ngram count for unigrams, bigrams and trigrams of the training data """ import sys def addebos(line_ebos): """ This function adds BOS and EOS to each sentence """ new_line = ['<s>'] new_line.extend(line_ebos) new_line.append('</s>') ret...
# Linear regression with Gradient Descent # Imports import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn # Dataset is included in sklearn from sklearn.datasets import load_boston # Load dataset boston = load_boston() # boston is a dictionary, showing the keys print boston.keys() # hyper...
import matplotlib.pyplot as plt import numpy as np def graph_editor(grid=True, grid_N = 12): plt.ion() # interactive mode ! fig, ax = plt.subplots(1) ticks = np.linspace(0,1,grid_N) def init_ax(): ax.clear() ax.set_xlim(0,1) ax.set_xticks(ticks) ax.set_xticklabels([])...
import sqlite3 #Open database conn = sqlite3.connect('quiz.db') #Create table quiz # Attributes: title, array of characters, array of questions, and array of options conn.execute('''CREATE TABLE quiz (quizId INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, charArray TEXT, qArray TEXT, optionArr...
def print_lyrics(): print("This is me PSYs0s") print("This is me Toha") def call_first_function(): print_lyrics() print("Why are you here") print("Who are you?") print_lyrics() call_first_function() def print_twice(bruce): print(bruce) print(bruce) print_twice("sapm") print_twice("sapm ...
total=0 count=0 while True: inp=int(input("Number(enter '0 to exit')>>")) if inp == 0: break total=total+inp count=count+1 print(f"Total:{total}") print(f"Count:{count}") print(f"Average:{total//count}")
fhand=open('words.txt') for line in fhand: line=line.rstrip()#this function is used for solving one line blank space print(line)
fName=input('Enter the file name:') try: fHand=open(fName) except: print('File cannot be oppened:',fName) exit() count=0 for line in fHand: if line.startswith('Subject:'):count=count+1 print('Ther were', count,'subject lines in',fName)
import random for i in range(10): x=random.random() print(x) y=random.randint(5,10) print(f"\n{y}") t=[1,2,3] print(random.choice(t))
numToWord=dict() print(numToWord) #ading items numToWord={'2':'two','3':'three','4':'four'} numToWord['1']='one' print(numToWord) print(numToWord['3']) print(len(numToWord))#supports len function #supports in & always return true if key item available.value item always return false print('1' in numToWord) print('one'...
class Solution: def countPrimeSetBits(self, L, R): """ :type L: int :type R: int :rtype: int """ r = 0 def is_prime(n): if n <= 1: return False i = 2 while i*i <= n: if n % i == 0: ...
class Solution: def matrixReshape(self, nums, r, c): """ :type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]] """ if r * c != len(nums) * len(nums[0]): return nums a = [] for row in nums: a.exte...
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if needle == '': return 0 nl = len(needle) def match(offset): flag = False if nl <= len(haystack) - of...
# Range has 3 Parameters #start: Starting number of the sequence. #stop: Generate numbers up to, but not including this number. #step: Difference between each number in the sequence. for i in range(6): print(i) for i in range(1,10,2): print(i) def newFunc(a=0, b=1): x=2 j=4 return x,j def test_...
def encrypt(): strings = input('Enter your message to encrypt: ') even = strings[::2] odd = strings[1::2] print(even + odd) encrypt() def decrypt(): string = input('what is your message to decrypt: ') length = len(string) half_length = (length+1)//2 even = string[:half_length...
string = 'sdfgdsdghhh' unique = [] for char in string[::]: if char not in unique: unique.append(char) print(len(unique))
def h(m,n): ans = 0 while (m >= n): (ans,m) = (ans+1,m-n) print ("ans", ans) print ("m", m) return(ans) if __name__ == '__main__': h(231,8)
#ユーザーに名前と年齢の入力を求めるプログラムを作成する. # 彼らが 100 歳になる年を告げる メッセージを表示してください name='' age=0 year=0 print('ユーザー名を入力してください。') name=str(input()) print('年齢を入力してください。') age=int(input()) year=2019+(100-age) print(name+'さんが100歳になるのは'+str(year)+'年です。')
#input,print,変数の 3 つだけで借金返済計画(無利子)を立てるプログラムを作る #借金の総額と,ひと月に返済する金額を入力すると,返済にかかる年数を表示しする # さらに,毎年のボーナスから返済する金額を入力すると,返済完了が何年早まるかを表示する # その次に返済を完了したい年数を入力すると,ボーナスからいくら返せばよいかを表示する import math sum=0 a=0 b=0 print('借金の総額を入力してください。') sum=int(input()) print('ひと月に返済する金額を入力してください。') a=int(input()) b=sum/a/12 print('...
class EmptyStackError(Exception): pass class Stack(object): def __init__(self): self.array = [] def push(self, element): self.array.append(element) def pop(self): if len(self.array) > 0: del self.array[-1] else: raise EmptyStackError("the stack...
""" Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input st...
""" Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can. Example 1: Input...
""" Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Input: "hello" Output: "holle" Example 2: Input: "leetcode" Output: "leotcede" """ class Solution: def reverseVowels(self, s: 'str') -> 'str': list_s = list(s) l, r = 0, len(s)-1 vowels ...
""" Compare two version numbers version1 and version2. If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate num...
""" Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Explanation: The third maximum ...
""" Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','F...
from typing import Set, List from .bases.graph_like import GraphLike, Node, Edge from .mask import Mask import random class Universe(GraphLike): """Graph structure that used to represent supergraph of any relation.""" def __init__(self, nodes: Set[Node], edges: Set[Edge]): """Initialize relation as ...
# Hibiscus Sense - Exercise 04 Melody # # There is 1x Small Buzzer on-board. # This is a passive buzzer and it is connected to GPIO13. # We need to generate Pulse Width Modulation (PWM) to control the vibration of the piezo element. # # In Arduino ESP32 programming there is no analogWrite() functio...
# Hibiscus Sense - Exercise 03 Breathing Light # # There is 1x blue LED. # This LED is connected to GPIO2 of ESP32 microcontroller. # We need to generate PWM output signal on GPIO2 to control the brightness of this LED. # # Therefore in the sketch, # we configure the PWM controller, choose GPIO f...
#!/usr/bin/env python3 import sys # Parses and checks sys.argv arguments to check for correct number and valid # inputs # Returns two integers: # 1) # of monopoles # 2) # of rooms def checkSysArgs(): # Check for correct number of args if(len(sys.argv) != 3): sys.exit(f"\nERROR: Incorrect number of argu...
"""Verify if the function convert_input returns the username of the specified host addresses with their corresponding dates converted to European format. """ import make_european def test_convert_input(): """Assert correct output for the function convert_input when the host address matches and does not match t...
num=int(input("enter a number")) num1=int(input("enter a number")) i=num while i<=num1: j=0 while j<=10: print(num,"*",j,"=",num*j) j=j+1 print() num+=1 i=i+1
i=1 num=int(input("enter a number")) while i< num: if num %3==0 and num%7==0: print("navgurukul") elif num%3==0: print("nav") elif num%7==0: print("gurukul") else: print(i) i=i+1
'''This program gives all correct calculations except for 56+9, 45*3, 56/6 ''' while 1: print("what type of operation you want to perform?\n" "type + for addition\n" "type - for subtraction \n" "type * for multiplication\n" "type / for division\n") op = input...
"""Bailee Brown""" MIN_LENGTH = 6 password = input("Please enter a password 6 digits or longer: ") while len(password) < MIN_LENGTH: print("Password not long enough,") password = input("Please enter a valid password: ") print(len(password)*'*')
jmeno = input('Zadej sve jmeno, nepouzivaj zdrobneliny ') print(jmeno) if (jmeno[-1] == 'a' or jmeno[-1] == 'e') and jmeno != 'Honza': print('Jsi zena') else: print('Jsi muz')
from tkinter import * from tkinter import ttk from tkinter.messagebox import showinfo from random import randint win = Tk() win.title("Dice Game") def play(): random_number = randint(1,6) number.config(text = f"number is : {random_number}") if random_number == 6: showinfo("You win") number = Label(w...
from enum import Enum class Player(Enum): PLAYER_1 = "Player 1" PLAYER_2 = "Player 2" @staticmethod def other(player): if player is Player.PLAYER_1: return Player.PLAYER_2 return Player.PLAYER_1
from copy import deepcopy class State: def __init__(self, board, black_left, white_left, black_kings, white_kings, turn, first_turn): """" save as arguments all turn information """ self.board = deepcopy(board) self.black_left = black_left self.white_left = white_le...
def dfs(start, end): visited = [] stack = [start] while stack: current = stack.pop() if current not in visited: visited.append(current) # 딕셔너리 내부의 리스트 '값'들을 더해줘야 하므로 리스트 append가 아니라 +로 해야함(제일 중요) stack += reversed(not_arr[current]) return visited v, ...
class Point: def __init__(self, x, y): # x, y가 좌표값이지만 self로 대입해주는게 local -> global과 유사 self.x = x self.y = y # 이 문제에서는 Point만의 기능이 없으므로 상속 굳이 필요 없음 class Rectangle(Point): def __init__(self, x, y): # super().__init__(x, y) self.x1 = x.x self.y1 = x.y se...
def search(): for i in range(n): for j in range(n): if arr[i][j] == 2: return i, j def bfs(x, y): global count queue = [] queue.append((x, y)) dx = [1, -1, 0, 0] dy = [0, 0, 1, -1] while queue: count += 1 current_x, current_y = queue.pop(...
""" Assignment: Stars Completed the assignment by myself. Part I: Create a function called draw_stars() that takes a list of numbers and prints out *. Part II: Modify the function above. Allow a list containing integers and strings to be passed to the draw_stars() function. When a string is passed, instead of displa...
class Node(object): def __init__(self, value): self.value = value self.next = None class SinglyLinkedList(object): def __init__(self): self.head = None self.tail = None list = SinglyLinkedList() list.head = Node('Alice') list.head.next = Node('Chad') list.head.next.next = Node(...
# Python script for sending HTTP request to server # import libraries import requests import json # These two libraries aren't necessary if using requests # import urllib2 # import urllib # GET request # URL = 'http://52.25.79.161/questions' # r = requests.get(URL) # print r.json() # POST request # URL = 'http://loc...
my_string = "egg, egg, Spam, egg and Spam" print my_string.replace("egg", "Spam", 2) # the output would be: # Spam, Spam, Spam, egg and Spam # notice that only the first 2 "egg" matches were replaced in the string.
""" Assignment: MathDojo HINT: To do this exercise, you will probably have to use 'return self'. If the method returns itself (an instance of itself), we can chain methods. PART I Create a Python class called MathDojo that has the methods add and subtract. Have these 2 functions take at least 1 parameter. Then creat...
""" PrintAllVals AddBack(val) AddFront(val) InsertBefore(nextVal, val) InsertAfter(preval, val) RemoveNode(val) ReverseList() """ class Node(object): def __init__(self, value): self.value = value self.next = None class SinglyLinkedList(object): def __init__(self): self.head = None ...
num1 = float(input("Enter your first number: ")) operator = input("What do you want to do?") num2 = float(input("Enter your second number: ")) if operator == " add" or operator == "add" or operator == "+" or operator == " +": print(num1 + num2) elif operator == " subtract" or operator == "subtract" or operator =...
is_male = True is_tall = True if is_male and is_tall: print("You are a male and tall") elif is_male and not(is_tall): print("You are a short man") elif is_tall and not(is_male): print("You are not male but you are tall") else: print("You are short, or not male, or both")
watchWords = ["apple", "head", "example", "bend"] message = input("What do you want to say? : ") for word in watchWords: censoredWord = "*"*len(word) if word in message: msgWord = word approvedMessage = message.replace(msgWord, censoredWord) message = approvedMessage print(message)
# 7.2 Write a program that prompts for a file name, then opens that file and # reads through the file, looking for lines of the form: # # X-DSPAM-Confidence: 0.8475 # # Count these lines and extract the floating point values from each of the lines # and compute the average of those values and produce an output as sh...
# Ex4.6 Exercise 6: Rewrite your pay computation with time-and-a-half for # overtime and create a function called computepay which takes two parameters # (hours and rate). user_hours = input("Enter Hours: ") user_rate = input("Enter Rate: ") def computepay(hours: int, rate: int) -> int: # check if eligible for ov...
# The basic outline of this problem is to read the file, look for integers #using the re.findall(), looking for a regular expression of '[0-9]+' and then #converting the extracted strings to integers and summing up the integers. import re fhand = open("regex_sum_1194587.txt") line_num = [] running_total = int() for li...
import random from time import sleep import copy def isSpaceFree(board,move): return board[move] == ' ' def drawBoard(board): print(board[1] + '|' + board[2] + '|' + board[3]) print('-+-+-') print(board[4] + '|' + board[5] + '|' + board[6]) print('-+-+-') print(board[7] + '|' + board[8] + '|' + board[9]) print...
# Import Neccesary Packages import numpy as np import cv2 from matplotlib import pyplot as plt import copy import math class Util: """ Responsibilty : Read, Write, Display, splitRGB, Expand Functions: imageRead() --> Reads the image from the system and gives us an gray scale image to...
# --- Day 24: Electromagnetic Moat --- # The CPU itself is a large, black building surrounded by a bottomless pit. Enormous metal tubes extend outward from the side of the building at regular intervals and descend down into the void. There's no way to cross, but you need to get inside. # No way, of course, other than...
pizza = str(input("¿Que desea pedir?\nIngrese :\ns -> Para pizza " "vegetariana\nn -> Para pizza no vegetariana\n")) if pizza == "s" or pizza == "n": if pizza == "s": ingre = str(input("¿Que ingredientes desea en su pizza?\nIngrese:\n" "p -> Para añadir pimientos ...
class CombinacionError(Exception): pass class MultplicidadError(Exception): pass class CantidadError(Exception): pass class Cajero(): def __init__(self): self.cant100 = [] self.cant200 = [] self.cant500 = [] self.cant1000 = [] self.montos_p = [] self...
# DNA Sequence Statistics-1 ## Function for Reading FASTA/FASQ File import screed # A Python library for reading FASTA and FASQ file format. def readFastaFile(inputfile): """ Reads and returns file as FASTA format with special characters removed. """ with screed.open(inputfile) as seqfile: for...
#! /usr/bin/env python #coding=utf-8 from __future__ import print_function from __future__ import division def n3(n): """十进转3进制""" t = [] while n > 0: t.append(n%3) n = n // 3 t.reverse() return t def (${2:}): ${0} for i in range(3**9):
#! /usr/bin/env python #coding=utf-8 #By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see # that the 6th prime is 13. # #What is the 10 001st prime number? from __future__ import print_function from __future__ import division def isprime(n): for i in range(2, int(n ** 0.5)+1): if ...