text
stringlengths
37
1.41M
sentence = "We are learning how to program in python. I find python programming fun" print(sentence.count("python")) x ="never" reverse_string = "" result = reverse_string.join(reversed(x)) print(result) name= "Cynthia" print("my name is", name) print(name[::-1]) sentence = "We are learning how to program in python. I...
# evaluate as long as the test expresssion is true #while True: #print("its true") i=10 while i>0: print(i) i-=1
numbers = [1, 2, 3, 4, 5] for each_item in numbers: # iterate over a sequence if each_item%2==0: print(each_item,"is even") else: print(each_item, "is odd") else: print("last item reached") for i in range(1,101): if i%3==0 and i%5==0: print("fizzBuzz") elif i%3==0: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 函数作为返回值 # 通常情况下,求和的函数是这样定义的: def calc_sum(*args): ax = 0 for n in args: ax = ax + n return ax # 如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办? # 可以不返回求和的结果,而是返回求和的函数: def lazy_sum(*args): def my_sum(): ax = 0 for n in args: ax = ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] # 从索引0开始取,直到索引3为止,但不包括索引3 print(L[:3]) print(L[-2:-1]) print(L[:-2])
"""A python linked list implementation.""" from typing import Iterable from data_structures.node import BaseNode class LinkedListNode(BaseNode): """A node for use in linked lists. While this node is usable with arbitrary data values, it also implements rich comparison operators which allow for easy comp...
class Node: def __init__(self,k): self.k=k self.next=None class LinkedList: def __init__(self): self.head=None def PrintList(self): temp=self.head while temp is not None: print(temp.k) temp=temp.next def Push(self,k): if self.hea...
#jumlah huruf pd kata a="okebos" print(len(a)) #array satu tipe b=[10,9,8,7] print(b[0]) print(b[1]) #array beda tipe c=["siap",10] print(c[0]) print(c[1]) #array kosong diisi d=[] d.append(100) d.append("seratus") print(d[0],d[1]) #menyisipkan data pd array e=[0,1,2,3,4] e.insert(e[0],100) #...
#Sign your name: Caleb Hews # 1.) Write a program that asks someone for their name and then prints their name to the screen? # name=input("What is your name?") # print("Hello",name) # 2. Write a a program where a user enters a base and height and you print the area of a triangle. # base=int(input("What is the Base of...
"""Class to create and connect to the database""" import mysql.connector from config import DB_NAME class Sql: """Create and use the database""" def __init__(self, user, password, host): self.user = str(user) self.password = str(password) self.host = str(host) def create_db(self,...
# -*- coding: utf-8 -*- """ Created on Thu Nov 12 20:31:16 2020 @author: pavdemesh """ def calc_months(starting_salary): left = 1 right = 10000 counter_steps = 0 while left <= right: # Increase the counter of bisection searches by 1 counter_steps += 1 # Define the mid poin...
# -*- coding: utf-8 -*- import re patron = re.compile("^\d*$") class Pila: """ Representa una pila con operaciones de apilar, desapilar y verificar si está vacía. """ def __init__(self): """ Crea una pila vacía. """ # La pila vacía se representa con una lista vacía ...
cases = int(input()) data=list() for case in range(cases): line = input() tupla = line.split(" ") tuplaMod=(int(tupla[0]), tupla[1]) data.append(tuplaMod) data.sort(key=lambda x: x[0]) texto=str() for case in range(cases): texto+=data[case][1] print(texto)
from . import helpers class SinglyLinkedListNode(object): """ A node for a SinglyLinkedList Each node contains a data field ("_value") and a reference ("_next") to the next node in the list. """ def __init__(self, value=None): self._value = value self._next = None def get...
#""" #Assignment 2 - Erewhon Mobile Data Plans #October 18, 2018 #Name..: Laura Whalen #ID....: W0415411 #""" __AUTHOR__ = "Laura Whalen <W0415411@nscc.ca>" def main(): # input data = int(input("Enter data usage (Mb): ")) # processing and output def data_plans(): if data <=...
#Assignment 4 - BattleShips #Name..: Laura Whalen #ID....: W0415411 print("Let's play Battleship!\nYou have 30 missiles to fire to sink all 5 ships.\n") map_file = open("map.txt") #hide the grid target_grid = [] #where values are stored for r in map_file: r = r.replace("\n","") columns_as_list = ...
# range, for and while loops, breaks, cont. # range(start, stop, step) # it will range from the start to one before the stop # range(0, 10) has the default step of always 1 # range(0, 10, -1) will range from 10 -> 1 range(8, 0, -2) # 8, 6, 4, 2 # doing range(8, 0, 2) will not do anything ###########################...
# try and except # if an error is encounterd, a try block code execution is stopped and... # transferred down to the except block # use try and except for runtime errors # example - divide by zero def meanUser(num, denominator): try: answer = num/denominator print(answer) except: pri...
# Day 15 - turtle events # review modules first import turtle import random # instead of importing the way above.. you can ##from turtle import * # the star means everything and all ##from random import * # it makes a difference in terms of how you use them # if you import the new way, you use them this way ##myr...
#Day 2 - Variables and Expressions # finish chapters 3 and 4 by Friday # a variable is an identifier (a name) that points to a value myname = "Madison" mynumber = 27 # Rules to variable naming: a variable can only be made up of letters, # numbers, and an underscore _ # a variable must start with a letter # variables...
# Day 31 - classes that interact with each other # chapters 13, 16, and 21 cover this week's material class Student: def __init__(self, name, gpa, idnum): self.name = name self.gpa = gpa self.idnum = idnum def __eq__(self, other): return self.idnum == other.idnum def ...
# Exam 3 Review # TRY AND EXCEPT # some good exceptions- # division by zero # operations on incompatible types # accessing a list item, dict value, or object attribute that doesn't exist # using an identifier that has not been defined # trying to access a file that doesn't exist #----------------...
# Last Day Notes # aliases v. clones num = 22 # this is not an object, just an integer (called a primitive) mylist = [1,2,3,4] # this is an object num2 = num # makes a copy and stores it in num2 mylist2 = mylist # makes an alias (a pointer to the same area of memory) mylist2[1] = 99 num2 = 44 print(num) # num is ...
# day 23 - Try and Except # an exception is another name for a runtime error # you can handle these errors in your code # before try... except review break and continue for num in range(50): if num % 7 == 0: continue # go back to start of loop if num % 25 == 0: break # exits loop ...
idade = int(input("Digite sua idade (ex. 32): ")) while idade < 0 or idade > 150: idade = int(input("Digite sua idade (ex. 32): ")) salario = float(input("Digite seu salário (ex. 2100,50): ")) while salario < 0: salario = float(input("Digite seu salário (ex. 2100,50): ")) genero = input("Informe seu genero ...
numero = int(input("Digite um número: ")) contador = 1 soma = 0 while contador <= numero: soma = soma + contador contador = contador + 1 print(soma) # Exemplo 1: # input: 4 # output: 10
# Faça um programa que leia 10 números do usuário # e os coloque corretamente no dicionário D abaixo. D = {'pares': [], 'impares': []} for i in range(10): numero = int(input("Digite um número: ")) if numero % 2 == 0: D['pares'].append(numero) else: D['impares'].append(numero) print(D)
import random numero_aleatorio = random.randint(1, 40) numero_aleatorio_menos = numero_aleatorio - 3 numero_aleatorio_mais = numero_aleatorio + 3 numero = int(input("Digite um número de 1 a 40: ")) while numero != numero_aleatorio: if numero > numero_aleatorio_menos and numero < numero_aleatorio_mais: p...
x = 0 y = 10 while x < y: if x % 2 == 0: print(x) else: print(y) x = x + 1 y = y - 1 print(x, y)
alunos = {'nomes': ['Ayrton', 'Dandara', 'Felipe', 'Gustavo', 'Jeferson'], 'cpf': [], 'idades': [25, 20, 50, 19, 32]} for chave in alunos: # "lista" é o "valor" da "chave" do dicionário "alunos" lista = alunos[chave] print(lista) for elemento_da_lista in lista: print(ele...
camisas = int(input("Quantas camisas? ")) calcas = int(input("Quantas calças? ")) parmeias = int(input("Quantos pares de meias? ")) total = (camisas * 12) + (calcas * 20) + (parmeias * 5.50) print("Seu total é R$" + str(total))
while True: genero = input("Informe seu gênero: ") if genero == "M" or genero == "F" or genero == "outro": break else: print("Genero inválido.")
si = float(input("Si: ")) v = float(input("t: ")) t = float(input("v: ")) s = si + v * t print(s)
################################################################## '''''' '''''' ''' This file is to Generate the negative samples, with the sample size and form as the training and testing data 1. The negative samples are generated by the random method. 2. The negatiev samples should not have any element in ...
class Word(): def __init__(self, word): self.word = word self.phone = [] self.syns = [] self.pos = '' def __str__(self): ret = '' ret += self.word + ': ' ret += self.pos + ', ' ret += ' '.join(self.phone) + ', ' ret += '[' + ', '.join(self.syns[:3]) + '...]' return ret
class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.firsst = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of_emps += 1 def fullname(self): return '{} {}'.format(self.first, self.last) def apply_rais...
b=int(input("enter no:")) a=1 n=2 print(a) while n<=b: print(n,end='/') a=(n/(n+1)) n=n+1 print('=',a)
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data print("check tensorflow version: ", tf.__version__) # tensorflow 交叉熵 import numpy as np import matplotlib.pyplot as plt mnist = input_data.read_data_sets("MNIST_data", one_hot=True) batch_size = 100 n_batch = mnist.train.num_example...
import jsonParsing building = raw_input("Enter building name or number: ") level = raw_input("Enter level: ") maps = jsonParsing.mapParser() maps.setMap(building, level) for i in range(maps.numElements): print maps.getLocationName(i)
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixe...
class Shape(): def area(self): return 0 class Square: def __init__(self,cd): self.cd=cd def area(self,): a=1 return a a=Square(0) a.area() print(a)
# coding: utf-8 # In[187]: # Importing Pandas,Numpy and Matplotlib import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns get_ipython().magic('matplotlib inline') # # Question Phase # For this project I come up one question that I'll address in following analysis: # # Q: Wha...
def login(): user = input("Username: ") pwd = input("Password: ") if user == "admin" and pwd == "111": showMenu() else: print("Wrong username or password") login() def showMenu(): print("---- Welcome to Shop -----") print("1. Vat Calculator") print("2. Pr...
#Recordar que en binario comienza en 1---2----4---8---16---32---64---124--256--512---1024 #funcion shift >>,<< #10 es 1010 #a>>1 ,es 101 a=10 b=a>>1 print('Valor entero: {} ,con shift a la derecha: {}'.format(a,b)) print('Valor binario: {},con shift a la derecha: {}'.format(bin(a),bin(b)))
#Permite saber los parametros de una llamada class Callee: def __call__(self, *pargs, **kargs): # Intercept instance calls print('Called:', pargs, kargs) varCalle=Callee() varCalle(1,5,9,s=12,m=122) class Comparacion: data = 'queso' def __gt__(self, other): # 3.X and 2.X version return len...
# Static and Class Methods , en primera instancia sin decoradores.con palabras staticmethod y classmethod #1.METODO ESTATICO, no tengo la necesidad de pasarle como argumento la variable o self a el metodo deseado. # class Spam: # numInstances = 0 # def __init__(self): # Spam.numInstances = S...
#Tuples #Interactive CODE #This function shows the output of the data regardless of the arguments def imprime(dato,*kwargs): print(dato,*kwargs) miTupla=(1,2,3,2,2) imprime(len(miTupla)) #Adicion temporal de dos elementos a la tupla imprime(miTupla+(6,7)) #Mustra la posicion del elemento 2 solo una vez #tambie...
#INVV-investigar libreria tkinter #eventualmente podria existir un parametro sin *,para usar una funcion osea def example(function,*args,**kwargs) #*args >>> Non-Keyword Arguments , **dict >>> keywords arguments def func(*args,**dict): return [args,dict.items()] diccionario1=dict(kills=8,deaths=5,assist=4) print...
# In this assignment you will write a Python program that expands on https://www.py4e.com/code3/urllinks.py. # The program will use urllib to read the HTML from the data files below, extract the href= values from the # anchor tags, scan for a tag that is in a particular position from the top and follow that link, r...
from collections import deque class MarsRover: RIGHT_ROTATION_DICT = { 'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N' } LEFT_ROTATION_DICT = { 'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N' } def __init__(self, plateau_width: int,...
# -*- coding: utf-8 -*- RAT = "rat" OX = "ox" TIGER = "tiger" RABBIT = "rabbit" DRAGON = "dragon" SNAKE = "snake" HORSE = "horse" GOAT = "goat" MONKEY = "monkey" ROOSTER = "rooster" DOG = "dog" PIG = "pig" ANIMALS = [ RAT, OX, TIGER, RABBIT, DRAGON, SNAKE, HORSE, GOAT, MONKEY, ...
#!/bin/python3 import math import os import random import re import sys """ Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated...
import numpy as np from util_funcs import * import matplotlib.pyplot as plt """Implement multi-class classification using Logistic Regression and One-vs-Rest method.""" # Todo: # Read data from .mat format # Implement LR class # Implement one-vs-rest method. class LogisticRegression: def __init__(self, X, num_cl...
# A simple Python program to introduce a linked list # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function ...
from tkinter import* import sqlite3 import tkinter.messagebox class ATM1(): def __init__(self, top): self.mOffsets = Toplevel(top) self.mOffsets.geometry("1400x900+0+0") self.mOffsets.title("STATE BANK OF INDIA") self.mOffsets.configure(bg='blue') def exit1(): ...
# import the python testing framework import unittest, math # our "unit" # this is what we are running our test on def reverseList(array): for index in range(math.floor(len(array)/2)): array[index], array[len(array)-index-1] = array[len(array)-index-1], array[index] return array def isPalindrome(word)...
import re def contains_gold(bags): containing_gold = set() def search_for_gold(bag_colour='shiny gold'): for bag in bags: if bag_colour in bags[bag]: containing_gold.add(bag) search_for_gold(bag) search_for_gold() return len(containing_gold) de...
import argparse from cache import Cache, Query from memoria import Memoria """ Entrada: um arquivo .txt, obtido dos argumentos, com as instruções Saída: outro arquivo .txt, com os resultados das instruções, opcional (padrão=out.txt) """ def main(): # Lê os argumentos para obter nome dos arquivos de entrada e saí...
#!/usr/local/bin/python from time import time fn = 'files/3-1.txt' def read_and_split_file_lines(filename): """Splits input into lines""" with open(filename) as f: lines = f.readlines() split_lines = [line.strip() for line in lines] vectors_1 = split_lines[0].split(',') vectors_2 = spli...
# # consider this previously common Python code # f = None # try: # f = open('some_file.txt') # # do stuff with f like read the file # finally: # if f: # f.close() # # The above code can be changed to read like this with the 'with' keyword # # allows you to not have to write try/finally blocks every...
# # Lists # friends = ['derek', 'kyle', 'robby', 'gabe'] # print(friends[1]) # print(friends[-1]) # print(friends[:-1]) # print(friends[1:]) # print(friends[::2]) # # functions that mutate the list # supplies = ['crayons', 'pencil', 'paper', 'Kleenex', 'eraser'] # supplies.append('markers') # print(supplies) # supp...
'''Determine Body Mass Index (BMI)''' import sys import speaking import docx #----------------------------------------------------------------------- print(f"\n----------Program Start----------\n") #----------------------------------------------------------------------- print(f"Hello! Welcome...\n") p...
import sys def read_array(filename): f = open(filename, 'r') matrix = [] for line in f: line = line[:-1] points = line.split(' '); matrix.append(points) #print points f.close(); return matrix def array_to_file(twoDArray, filename): f = open('out.txt', 'w') for i in range(0, len(twoDArray)): for j in ...
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): if not self.root: self.root = Node(new_val) el...
from collections import Counter text = "A December squall came in search of him and"\ " knocked his door. Yes, It was her. She came in like a "\ "swift stormy wind leaving no room for doubt or fear to crawl "\ "back in. All of a sudden a hidden thought came alive. "\ "It stole a glance at all the busyness of...
expense = [300,500,700,859,123,235,634] def double(dollars): return dollars * 2 new_expense = list(map(double, expense)) print(new_expense) ''' we can also run this list through for loop. but map is much easier for x in expense: print(x*2) '''
def isprimal(n): for i in range(2, n): if n % i == 0: return False return True def primals(n): # res = [] # ! for i in range(2, n): if isprimal(i): yield i # res.append(i) # return res def mytest(n): prims = primals(n) # res = [] for...
# Create a dictionary containing some information # about yourself. The keys should include name, age, country of birth, favorite language. # # Write a function that will print something like the following as it executes: # # My name is Anna # My age is 101 # My country of birth is The United States # My favorite lang...
from Employee1 import Employee class Manager (Employee): #this is the basic constructor. As this class is a sub-class of Employee, first calls Employee's constructor #and initializes that part of the object # and all other values are assigned as per parameters passed. def __init__(self, first_name, last_name,...
__author__ = 'priyanka.' from functools import total_ordering @total_ordering class Employee: """ One object of class Employee represents one employee's first name, last name, social security number and his salary """ #this is the basic constructor. Here the current Employee's firstname, lastname, soc...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Roger TX (425144880@qq.com) # @Link : https://github.com/paotong999 import random def confict(state, pos): nextY = len(state) if pos in state: return True '''判断斜线''' for i in range(nextY): if nextY-pos == i-state[i]: return True ...
from itertools import count from math import sqrt def main(): with open("input", "r") as file: minPresents = int(file.readline()) // 10 def calcPresents(house): presents = 0 for elve in range(1, int(sqrt(house)) + 1): if house % elve == 0: presents += elve ...
from collections import defaultdict def main(): graph = defaultdict(lambda: {}) weights = {} with open("input", "r") as file: for line in file.readlines(): parts = line.strip().split(" -> ") root, weight = parts[0].split(" ") weights[root] = int(weight[1:-1]) ...
dic={} a=input("enter your favourite language") b=input("enter your favourite language") c=input("enter your favourite language") d=input("enter your favourite language") dic["shubham"]=a dic["shivam"]=b dic["saurabh"]=c dic["sonia"]=d print(dic)
class Animals: def __init__(self, age, weight, alive, name): self.age = age self.weight = weight self.alive = alive self.name = name def birthday(self): self.age += 1 class Insects(Animals): def __init__(self, longevity, initialSpeed): self.longevity = long...
import string import random import pyperclip class Credential: """ Class that generate new instances of user credentials. """ credential_list = [] def save_credential(self): """ function to save user details """ Credential.credential_list.append(self) def dele...
# Problem # # You're watching a show where Googlers (employees of Google) dance, and then each dancer is # given a triplet of scores by three judges. Each triplet of scores consists of three # integer scores from 0 to 10 inclusive. The judges have very similar standards, so it's # surprising if a triplet of scores con...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def findLen(self, head): result = 0 return result def rotateRight(self, head, k): """ :type head: ListNode :t...
#!/usr/bin/env python # coding: utf-8 # # Project - Wrangle and Analyze data # # Tasks in this project are as follows: # # Data wrangling, which consists of: # # Gathering data # # Assessing data # # Cleaning data # # Storing, analyzing, and visualizing wrangled data # # Reporting on 1) data wrangling efforts...
class Spot: def __init__(self, name, info=""): self.name = name self.info = info self.next_spots = {} self.characters = [] def connect(self, next_spot, direction): self.next_spots[direction] = next_spot def show(self): print(self.name) print("-" * l...
import VigenereCipher while True: try: cryptanalysis = int(input("Entrer 1 si vous voulez calculer l'indice de coincidence d'un texte :")) except ValueError: print("Veuillez présenter un choix correct.") if cryptanalysis == 1: try: cipher = str(input("Enter le message ...
""" http://rosalind.info/problems/iprb/ Given: Three positive integers k, m, and n, representing a population containing k+m+n organisms: k individuals are homozygous dominant for a factor, m are heterozygous, and n are homozygous recessive. Return: The probability that two randomly selected mating organisms will p...
import os import re def preprocess(document): """This function converts non-alphabetic characters to whitespace, lowercases all letters, and collapses all subsequent whitespace down to a single space. It returns a string of the preprocessed document""" document = re.sub(r'\W+', ' ', document) document = re...
class Bank: def __init__(self): self.accounts = {} def insert(self, account): if self.accounts.has_key(account.get_person_id()): print ("Account exists") return False self.accounts[account.get_person_id()] = account def remove(self, person_id):...
#!/usr/bin/env python # Default color levels for the color cube cubelevels = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff] # Generate a list of midpoints of the above list snaps = [(x+y)/2 for x, y in zip(cubelevels, [0]+cubelevels)[1:]] print(snaps) def rgb2short(r, g, b): """ Converts RGB values to the nearest equivale...
def addToEach(value,aList): result = [] for item in aList: result = result + [ item + value ] return result #def addToEach(value,aList): # result = [] # for item in aList: # result.append(item + value) # return result def test_addToEach_1(): assert addToEach(1,[3,4,5])==[4,5,6] def test_a...
"""Do this now: Write a function to get a valid age from a user Write two lines of main code to show its use """ MAXIMUM_AGE = 130 def main(): """Program for getting ages.""" age = get_valid_age() print(f"You are {age} years old!") def get_valid_age(): """Get a valid age between 0 and MAXIMUM_AGE.""...
#!/usr/bin/python """ //[]------------------------------------------------------------------------[] //| | //| Problema dos Monges e Canibais | //| Version 1.0 ...
import wikipedia from topicblob import TopicBlob # get random wikipeida summaries wiki_pages = [ "Facebook", "New York City", "Barack Obama", "Wikipedia", "Topic Modeling", "Python (programming language)", "Snapchat", ] def main(): texts = [] for page in wiki_pages: text...
# # # Utils # # import re import os.path import mimetypes from urllib.parse import urlparse def splitext(path): """ Split file into name and extension with support for .tar.gz / .tar.bz2 extensions Parameters ----------- path: str File path Returns -------- name: str ...
from queue import PriorityQueue import math class WayPointsProblem: def __init__(self, inputGrid, startPos, goalPos, cylinders, boundaryPoints): self.grid = inputGrid self.start = (startPos[0], startPos[1]) self.startAlt = startPos[2] self.goal = (goalPos[0], goalPos[1]) sel...
""" Task 1 String calculation: The method can take two numbers, separated by commas, and will return their sum. For example "1,2" would return 3. Task 2 The method can take up to two numbers, separated by commas, and will return their sum. For example "" or "1", where an empty string will return 0. """ import pytest ...
import random name = "구도" english_name = "Gu" # pyformat print("안녕하세요, {}입니다. My name is {}".format(name,english_name)) # f-string print(f"안녕하세요, {name}입니다. My name is {english_name}") numbers = list(range(1,46)) lotto = random.sample(numbers,6) print(f"오늘의 행운의 번호는 {sorted(lotto)} 입니다.")
print() print("//// Part 3: Perform Financial Calculations \\\\\\\\") """ Perform financial calculations using functions. 1. Define a new function that will be used to calculate present value. a. This function should include parameters for `future_value`, `remaining_months`, and the `annual_discount_rate` b. T...
import numpy as np # Define a main() function that transpose matrix and # create view array containing only 2nd and 4th row. def main(): arr = np.arange(1, 16).reshape(3, 5) arr_transpose = arr.T print(arr_transpose) second_and_forth_row_arr = arr_transpose[[1, 3], :] print(second_and_forth_row_a...
import unittest from convert import CurrencyConverter class TestCurrencyConverterClass(unittest.TestCase): def test_get_current_rates(self): """Test get_current_rates()""" CurrencyConverter.get_current_rates() self.assertEqual(type(CurrencyConverter.current_rates), dict) ...
# !/usr/bin/env python # -- coding:utf-8 -- ''' 习题7-9 ''' def tr(srcstr, dststr, string,case=False): ''' 一个字符翻译程序 功能类似于 Unix 中的 tr 命令 ''' assert len(srcstr) == len(dststr) ,'srcstr length must be equal to dststr' # 替换字符串 arr = list(string) length = len(arr) if case: srcstr = srcstr.lower() for i in range(...
# -- coding: utf-8 -- # 对列表的解析 squared = [x ** 2 for x in range(4)] ''' print squared 结果: [0,1,4,9] ''' sqdEvens = [x ** 2 for x in range(8) if not x % 2] ''' print squared 结果: [0, 4, 16, 36] ''' print sqdEvens
'''@file character.py contains the character target normalizer''' def normalize(transcription, alphabet): '''normalize a transcription Args: transcription: the transcription to be normalized as a string Returns: the normalized transcription as a string space seperated per characte...
#Python Text RPG# #The Dream Hero# #Imports# import os import sys import time import random import textwrap screen_width = 100 ## Player Setup ## class player: def __init__(self): self.name = '' self.location = 'b2' self.hp = 0 self.mp = 0 self.role = ' ' ...