text
stringlengths
37
1.41M
import os import argparse def get_location_from_line(line): if not line: return None return int(line.split(',')[0]) def scan_through_line_for_number(alignment_file, start_line_hint, number): alignment_file.seek(start_line_hint) for line in alignment_file: location = get_location...
# modified version of 'invert_dict()' function From Section 11.5 of: # Downey, A. (2015). Think Python: How to think like a # computer scientist. Needham, Massachusetts: Green Tree Press. def invert_dict(d): inverse = dict() for key in d: val = d[key] for item in val: inverse[item...
""" basicfem.py is the main script to execute the Basicfem solver. """ import sys import os import numpy as np import matplotlib.pyplot as plt from abc import ABCMeta, abstractclassmethod from lib.solvers import * from lib.output_utility import * from lib.solver_input import * def main(): """ Main function t...
import hashlib import random def hash_function(key): """ Returns the low 32 bits of the md5 hash of the key. """ # You don't need to understand this return int(hashlib.md5(str(key).encode()).hexdigest()[-8:],16)&0xffffffff def how_many_before_collision(buckets, loops=1): for i in range(loops):...
class HashTableEntry: """ Linked List hash table key/value pair """ def __init__(self, key, value): self.key = key self.value = value self.next = None self.head = None def find_val(self, value): # start at the head cur = self.head while cur ...
from card import * import random class Deck: def __init__(self): self.cards = [] for suit in [ "clubs","diamond", "hearts", "spades" ]: for rank in range (1,14): new_card = Card(rank, suit) self.cards.append(new_card) def shuffle(self): rand...
limit,moves = input("Enter the char limit:"),input("Enter the moves:") start,goal = [],[] for i in range(limit): start.append(raw_input("Enter the Start:")) for i in range(limit): goal.append(raw_input("Enter the Goal:")) def fn(start,goal,moves): while moves>0:
import os.path as osp import numpy as np def parse_psiblast(path_to_file): """ For a concrete example check example.blastPsiMat format on https://github.com/plopd/ppcs2-project/blob/master/dataset/example.blastPsiMat :param path_to_file: :return: """ # get filename (without extension) -...
class Question: def __init__(self,text,choices,answer): self.text=text self.choices=choices self.answer=answer def checkAnswer(self,answer): return self.answer==answer #print(q1.checkAnswer('Python')) #print(q2.checkAnswer('c')) class Quiz: def __init__(self,questions): ...
class User: def __init__(self,username,password,email): self.username=username self.password=password self.email=email class UserRepository: def __init__(self): self.users=[] self.isLoggedIn=False self.currentUser={} #load users from .json file se...
"""def sum_list(items): sum_numbers = 0 for x in items: sum_numbers += x return sum_numbers print(sum_list([1,2,-8])) multiply=1 list=[1,2,3,4] for x in list: multiply*=x print("multiplication is",multiply) list=[7,5,9,3,4,6] max = list[0] for i in list: if i>max: max=i print("...
def square(num): return num**2 numbers=[1,3,5,7,10,14] """result=list(map(square,numbers)) print(result) for item in map(square,numbers): print(item) square=lambda num: num**2 result=square(3) print(result)""" def check_even(num): return num%2==0 #result= list(filter(check_even,numbers)) result= list(filter(l...
"""Adi = 'Ali' Soyad = ' Yılmaz' AdSoyad = Adi+Soyad Cinsiyet = True #erkek TcKimlik ='123456789' Dogum=1989 Adresi = 'mersin mezitli' yas = 2021-Dogum print(yas) print(AdSoyad) pi=3.14 r=int(input("yarı çap: ")) alan=pi*(r**2) cevre=2*pi*r print("alan "+str(alan)+" çevre "+str(cevre))"""
import random """result=dir(random) print(result) result=random.random() #0.0-1.0 result=random.uniform(10,100) result=int(random.uniform(10,100)) result=random.randint(1,10) print(result) names=['ali','yagmur','deniz','cenk'] #result=names[random.randint(0,len(names)-1)] result=random.choice(names) print(result) gr...
"""import random import os print("Select a random element from a list:") elements = [1, 2, 3, 4, 5] print(random.choice(elements)) print(random.choice(elements)) print(random.choice(elements)) print("\nSelect a random element from a set:") elements = set([1, 2, 3, 4, 5]) # convert to tuple because sets are invalid inpu...
"""def sayHello(name = "user"): print("hello",name) sayHello('nazli') sayHello("melis") sayHello() def total(num1,num2): return num1+num2 print("total is",total(10,20))""" def yasHesapla(yil): return 2021-yil def emeklilik(yil,isim): yas=yasHesapla(yil) emeklilik=65-yas if emeklilik>0: ...
import random def guess(): x=int(input("enter a number between 1 and 20: ")) computer_guess=random.randint(1,20) win=True while win: if x>computer_guess: x=int(input("enter smaller number: ")) elif x<computer_guess: x = int(input("enter bigger number: ")) ...
''' In this project, you will visualize the feelings and language used in a set of Tweets. This starter code loads the appropriate libraries and the Twitter data you'll need! ''' import json from textblob import TextBlob import matplotlib.pyplot as plt from wordcloud import WordCloud #Search term used for this tweet ...
# --- Define your functions below! --- def intro(): print("Welcome to ChatBot!") print("All you have to do is respond to my prompts and hit enter!") name = input("What is you name? ") return name def hello(text): text.lower() if text == "hello" or text == "hi" or text == "yes": print("...
x=int(input("enter the number:")) a=1 while(X>0): a=a*x x=x-1 print("x of the number is:") print(x)
nn = int(input()) v = str(input()) a=v[::-1] for i in a: if i=="a" or i=="e" or i=="i" or i=="o" or i=="u" or i=="A" or i=="E" or i=="I" or i=="O" or i=="U": continue else: print(i,end="")
class Usuario: #Metodo constructor que se inicia cada vez que se crea una instancia def __init__(self, nombre, apellido): self.nombre = nombre self.apellido = apellido # no es necesaria la palabra 'self', puede ser cualquiera, por ser el primer argumento del método def saludo...
import unittest from unittest import mock import challenges class T100BeginnerTests(unittest.TestCase): """Tests for beginner challenge""" def setUp(self): self.store1 = challenges.Store(222.2,33333.3,3,True,['item1','item2','item3']) def test_101_variables(self): '''Check init is ...
# for x in range(1, 11): # print("\U0001f600" * x) times = 1 while times != 10: print("\U0001f600" * times) times += 1
# 作业一 # import math # a = float(input('输入a的值')) # b = float(input('输入b的值')) # c = float(input('输入c的值')) # if b**2-4*a*c>0: # x1=(-b+math.sqrt(b**2-4*a*c))/2*a # x2=(-b-math.sqrt(b**2-4*a*c))/2*a # print(x1,x2) # elif b**2-4*a*c==0: # x1=x2 =(-b+math.sqrt(b...
import sys def counting(input_file, output_file): drug_counter = get_drug_info(input_file,5,2,1,3,4) #start writing our new output txt using the output name provided with open(output_file, 'w') as output: #header row for output file header = "drug_name,num_prescriber,total_cost \n" output.write(header) #...
secret = 'swordfish' pw = ' ' count = 0 auth = False max_attaempt = 5 while pw != secret: count += 1 if count > max_attempt: break if count == 3: continue pw = input(f"{count}: What's the secret word ?") else: auth = True print('.Authorized' if auth else "Calling the FBI...")
#Program to calculate multiplication table of any number for n number of times. print("Multiplication table calculator.") x=int(input("Enter a number for multiplication table: ")) y=int(input("Enter a value for the number of multiplication tables: ")) for i in range(1,y+1): print(i,"x",x ,"= ",x*i)
def three_sum(nums): if len(nums) < 3: return [] nums.sort() res = set() for i, v in enumerate(nums[:-2]): if i > 1 and nums[i] == nums[i - 1]: continue d = {} for x in nums[i + 1:]: if x not in d: d[-v - x] = 1 else: ...
class Count: def __init__(self, func): self.count = 0 self.func = func def __call__(self, *arg, **kwargs): self.count += 1 print( f"{str(self.func)} is called, already called for {self.count} times <including current>" ) return self.func(*arg, **kwarg...
''' Question 2 Level 1 Question: Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 ''' ''' num = int(raw_input('Enter ...
''' Question 7 Level 2 Question Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j Note: i=0,1.., X-1; j=0,1,...,Y-1 Example Suppose the following inputs are given to the program: 3,5 Then, the ou...
def find_substrings(inpstr): p1_v_list = ['a','an','ana','anan','anana'] #p2_c_list = ['b','n','ba','na','ban','nan','bana','nana','banan','banana'] p2_c_list =['b'] out =[] for i in range(len(inpstr)+1): for j in range(1,len(inpstr)+1): if i < j: out.append(inps...
''' Let's learn about list comprehensions! You are given three integers X,Y and Z representing the dimensions of a cuboid. You have to print a list of all possible coordinates on a 3D grid where the sum of Xi + Yi + Zi is not equal to N. If X=2, the possible values of Xi can be 0, 1 and 2. The same applies to Y and Z. ...
''' Question 8 Level 2 Question: Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,...
import fractions import math def mixed_fraction(s): s1,s2 = s.split('/') num,den = int(s1),int(s2) signnum,signden = 1,1 if num < 0: signnum = -1 if den < 0: signden = -1 if den == 0: raise ZeroDivisionError num = abs(num) den = abs(den) q,r = divmod(num,d...
import re def unscramble_eggs(word): w = re.sub('egg','',word) return w print unscramble_eggs('FeggUNegg KeggATeggA')
#example anagrams: # dog, god # act, cat # add, dad # rats, arts # NOT: art, rats # NOT: ada, add # NOT: dog, dog # Write a function find_anagrams that returns a list of the strings which # are anagrams of another word in an input list. #Example: #find_anagrams(['bat', 'rats', 'god', 'dog', 'cat', 'arts', 'star']) ...
''' Question: Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: joh...
''' Question: Define a class, which have a class parameter and have a same instance parameter. Hints: Define a instance parameter, need add it in __init__ method You can init a object with construct parameter or set the value later ''' class Animal: animal_type = 'Animal' def __init__...
#sort the list of lists below based on ascending number of length of each sublist import operator def sort_sublists(): liofli = [['a','b','c'],['d'],['e','f'],['g','h','i','j','k']] out = [] d = dict() for li in liofli: d[tuple(li)] = len(li) sorted_d = sorted(d.items(),key = operator.ite...
# binary search, O(log(m*n)) # we can use binary search to search row first, and then col # but can also use smart index to do binary search only once class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool ...
# method 2, use dictionary # for every word, produce all the possible candidates from word, # do not have to go through all the words, and only # check all the candidates that are no longer than word # note: the pair can either be on the left or on the right # time O(n*k*k), where k is the length of the word, and n is...
# method 2: union find # the seats of the couple don't matter, # as long as the couple is sitting together # paired seats can be saved into a dictionary class Solution(object): def minSwapsCouples(self, row): """ :type row: List[int] :rtype: int """ d = {} for i ...
# https://leetcode.com/problems/kth-largest-element-in-an-array/submissions/ # method 3: quick selection, time O(n) # quick selection, O(n) time, O(1) space import random class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int ...
#!/usr/bin/env python import sys t = float(sys.argv[1]) c = float(sys.argv[2]) print "Temperature is: %s"%t print "Cooling factor is: %s"%c ct = 0 while (t > 1): t=t*c ct = ct + 1 print "Temperature reached 1 after %s iterations"%ct
# SEARCHING (Chapter 15 from programming arcade games) file = open('data/villains.txt', 'r') # open file to read (creates object named file) print(file) for line in file: print(line.strip()) # .strip() method removes spaces and \t \r from beginning and end for line in file: print("Hello", line.strip()) #...
def check(word, longword): while (1): if len(longword) < len(word): return 0 c = longword[len(word)-1] for i in range(len(word))[::-1]: if c == word[i]: print(i,longword[len(word)-1-i:2*len(word)-1-i]) if longword[len(word)-1-i:2*len(wo...
# ------------- sequence -------------- from datetime import timedelta, date class DateRangeSequence: def __init__(self, start_date, end_date): self.start_date = start_date self.end_date = end_date self._range = self._create_range() def _create_range(self): days = [] c...
from statistics import mean import math def k_means(k_list,elements,no_of_elements,value_of_k): i=j=0 diff=[] copy_list=[] count=0 while True: copy_list=k_list[0].copy() count+=1 for i in range(no_of_elements): diff=[] for j in range(value_of_k): diff.append(abs(k_list[0][j]-elements[i])) indx=...
from typing import Tuple from adventure.level import build_level_0, build_level_1 from adventure.scene import Scene def check_level_up_conditions(scene: Scene, level: int) -> Tuple[Scene, int]: # Todo: use set to check level up conditions if scene.score >= scene.level_up_points: if "Key" in [item.nam...
i=lambda:map(int,input().split()) a,b = i() y = 1 while True: if(3*a > 2*b): print(y) break else: y = y+1 a = 3*a b = 2*b
''' # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail ''' inp=lambda:map(int,input().split()) a, b, c, m = inp() p, ans = ...
#-------------------------题目链接---------------- #https://leetcode-cn.com/problems/find-the-most-competitive-subsequence/ #博客:https://www.cnblogs.com/yeshengCqupt/p/14057027.html #----------------------------------------------- import copy class Solution: def mostCompetitive(self, nums, k): ''' 垃圾dfs ...
#---------------------题目链接----------------- #https://leetcode-cn.com/problems/smallest-string-with-a-given-numeric-value/ #-------------------------------------------- class Solution: def getSmallestString(self, n: int, k: int) -> str: k -= n con = k // 25 sur = k % 25 return 'a' * (...
from datetime import date current_date = date.today() print(str(current_date)) User_file = open('user.txt', 'r+') user_login = {} for line in User_file: user_details = line.split(", ") user_login[user_details[0]] = str(user_details[1]).replace("\n", "")#strip away user.txt line by line print("LOG ON BE...
import random print("Random Number Generator!") count = input("How many numbers would you like to generate?") count = int(count) for p in range(count): number = random print(random.randint(random.randint(0,100), random.randint(101,1000))) print("Enjoy your numbers!")
import pygame, math, sys, time iterations = int(sys.argv[1]) # No. of iterations to run the fractal generating algorithm. pygame.init() # Create a new surface and window to display the fractal tree pattern. surface_height, surface_width = 1200, 1000 main_surface = pygame.display.set_mode((surface_height,surface...
def fuel(mass): fuel_mass = mass // 3 - 2 if fuel_mass <= 0: return 0 return fuel_mass + fuel(fuel_mass) with open("in.txt", "r") as f: components = f.read().splitlines() components = map(int, components) fuel_per_component = map(fuel, components) print(sum(fuel_per_component))
# Assignment: Checkerboard # Write a program that prints a 'checkerboard' pattern to the console. # Your program should require no input and produce console output that looks like so: # * * * * # * * * * # * * * * # * * * * # * * * * # * * * * # * * * * # * * * * # Copy # Each star or space represents a square. O...
# Assignment: Fun with Functions # Create a series of functions based on the below descriptions. # Odd/Even: # Create a function called odd_even that counts from 1 to 2000. # As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number. # Your program outp...
def table(): count = 0 x = 1 while count < 13: if count < 2: x = 1 count += 1 print (x * 1, x * 2, x * 3, x * 4, x * 5, x * 6, x * 7, x * 8, x * 9, x * 10, x * 11, x * 12) elif count > 1: x += 1 count += 1 print (x * 1, x * 2, x * 3, x * 4, x * 5, x * 6, x * 7, x * 8, x * 9, x * 10, x * 11, x *...
# Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month. # # The following variables contain values as described below: # # balance - the outstanding balance on the credit card # # annualInterestRate - annual ...
# The greatest common divisor of two positive integers is the # largest integer that divides each of them without remainder. # # For example, # # gcd(2, 12) = 2 # # gcd(6, 12) = 6 # # gcd(9, 12) = 3 # # gcd(17, 12) = 1 # # Write an iterative function, gcdIter(a, b), # that implements this idea. # # One easy way to do t...
import funciones import argparse import pandas as pd import matplotlib import matplotlib.pyplot as plt def parser(): parser = argparse.ArgumentParser(description='Selecciona los datos que quieres ver') parser.add_argument('x', type=str, help='Moneda Seleccionada') parser.add_argument('y', type=str,help='Fe...
""" Errores sintácticos y lógicos Modificaremos el problema del concepto anterior y agregaremos adrede una serie de errores tipográficos. Este tipo de errores siempre son detectados por el intérprete de Python, antes de ejecutar el programa. A los errores tipográficos, como por ejemplo indicar el nombre incorr...
''' Estructura condicional compuesta. Cuando se presenta la elección tenemos la opción de realizar una actividad u otra. Es decir tenemos actividades por el verdadero y por el falso de la condición. Lo más importante que hay que tener en cuenta que se realizan las actividades de la rama del verdadero o las del ...
""" Estructura de programación secuencial Cuando en un problema sólo participan operaciones, entradas y salidas se la denomina una estructura secuencial.""" # Realizar la carga del precio de un producto y la cantidad a llevar. Mostrar cuanto se debe pagar (se ingresa un valor entero en el precio del producto) pr...
from random import randint from random import random import math class sim_Anl: def search(self, problem): visited = 0 expanded = 0 current = problem.state_initialization() neighbors = [] threshold = 10 # counter = 1 T = 1 T_min = .001 while ...
# Classe de Venda de Carros class Venda(): # Método contrutor def __init__(self, carro, cliente, vendedor, desconto,preco, data, forma_pagamento): self.carro = carro self.cliente = cliente self.vendedor = vendedor self.desconto = desconto self.preco = preco self.p...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- """ Example of controlling temporary file and directory """ from tempfile import TemporaryFile, NamedTemporaryFile, TemporaryDirectory # Example-1) Create a nonamed temp file. write a text and read it with TemporaryFile('w+t') as f: f.write('Hello, World!') f....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from typing import Optional class BSTNode(object): def __init__(self, data: int, parent: Optional['BSTNode'] = None, left: Optional['BSTNode'] = None, right: Optional['BSTNode'] = None) -> None: self.data = ...
""" File: word_guess.py ------------------- My project is an improved version of the Word Guessing Game. It allows a multiplayer mode (up to 4 players) """ import random LEXICON_FILE = "Lexicon.txt" # File to read word list from INITIAL_GUESSES = 8 # Initial number of guesses player starts with NUM_OF_...
from words import words import random word = list(random.choice([x for x in words if len(x) < 4])) ans = [] guessed = [] print(len(word)) def play(): life = 5 while word != ans: if life != 0: print("guess a letter: ") a = input() guessed.append(a) if a in...
#Answer to CIS 122 #1 Simple Printing - https://www.codewars.com/kata/cis-122-number-1-simple-printing print "Hello World!" course = "CIS 122" name = "Intro to Software Design" print "Welcome to " + course + ": " + name a = 1.1 b = 3 c = a + b print "The sum of " + str(a) + " and " + str(b) + " is " + str(c) x_pr...
#Answer to Return Negative - https://www.codewars.com/kata/return-negative/train/python def make_negative( number ): return number*-1 if number > 0 else number
""" How many letter of the Alphabet? So I wanted to write a function to find out how many letters of the alphabet would appear in a given text. I've learned that Python has made some optimizations to string manipulations to the point where creating functions to match C-style programming is not needed. """ import tim...
from dataclasses import dataclass from typing import Union, List from game.model.entity.item.item import Item @dataclass class Inventory: capacity: int items: List[Item] selected_item: Union[int, None] def __init__(self, capacity: int, items: List[Item] = None): self.capacity = capacity ...
from abc import ABC, abstractmethod from game.model.entity.item.item import Item class InventoryKeeper(ABC): """ Enables ability to keep items. """ def __init__(self, limit): self.inventory = [] self.limit = limit def pick_item(self, item: Item): """ Try to ad...
''' This Python exam will involve implementing a bank program that manages bank accounts and allows for deposits, withdrawals, and purchases. ''' def init_bank_accounts(accounts, deposits, withdrawals): ''' Loads the given 3 files, stores the information for individual bank accounts in a dictionary, and ca...
import math r = int(input()) h = int(input()) print(math.pi*(r**2)*h/3)
""" Problem description: A plus B, but you can't use '+'. """ class Solution: """ @param a: An integer @param b: An integer @return: The sum of a and b """ def aplusb(self, a, b): # write your code here if a==0: return b elif b==0: return a ...
def isprime(n, p): for e in p: if n % e == 0: return False; return True def primos(): p = set() for e in range(2, 100): if isprime(e, p): p.add(e) return p print(primos())
'''Rasterizador''' import numpy as np import collections def clearscreen(screen): return screen.fill(0) def changepixel(imagen, fila, columna , valor): '''f,c,v es....''' imagen[fila][columna] = valor Point = collections.namedtuple("Point",["x","y"]) Rectangle = collections.namedtuple("Rectangle",["min",...
# coding=utf-8 import math #- Crear una función que dada una altura, pinte un rombo def rombo(altura): for i in range(altura): print(" " * (altura - i) + "*" * (2 * i + 1)) for i in range(altura - 2, -1, -1): print(" " * (altura - i) + "*" * (2 * i + 1)) rombo(input("Introduzca una altura: ")) ...
from datetime import datetime def get_time_at(hour: int, minute: int) -> datetime: """ Helper which generate the datetime for the current day at a given hour and given minute """ now = datetime.now() return now.replace(hour=hour, minute=minute, second=0, microsecond=0)
#Find the nth fibonacci from numpy import empty def Fib(iEnd): iCnt=3 arr=empty(iEnd+1) arr[0]=0 print(int(arr[0]),end=" ") arr[1]=1 while iCnt != iEnd+1: arr[iCnt]=arr[iCnt-1]+arr[iCnt-2] print(int(arr[iCnt]),end=" ") iCnt +=1 def main(): print("Ent...
def main(): name=input("Enter the file name that you want to create") fobj=open(name,"w") #create new file str=input("Enter the data that you want to write in the file") fobj.write(str) if __name__=="__main__": main()
class Base: def __init__(self): self.i=11 self.j=21 print("Inside Base constructor") #class Derived: public Base cpp #class Derived extends Base java class Derived1(Base): def __init__(self): Base.__init__(self) self.x=31 self.y=41 print("Inside Derived1 constructor") class Derive...
def DisplayF(Value): print("Output of for loop") iCnt=0 for iCnt in range(0,Value): print("Jay Ganesh") def DisplayW(Value): print("Output of while loop") iCnt=0; while iCnt < Value: print("Jay Ganesh") iCnt=iCnt+1 def main(): print("Enter the no of iterations") no=int(input()) Displ...
import threading Amount=1000 def ATM(func,kulup): print("Inside ATM") func(kulup) def Deposit(kulup): kulup.acquire() print("Inside Deposit") iValue=int(input("Enter the amount to deposit")) global Amount Amount=Amount+iValue print("Deposit successful - Balance is:",Amount) kulup.release() ...
#named function def Addition(iNo1,iNo2): return iNo1+iNo2 #lambda function Sum=lambda iNo1,iNo2 : iNo1+iNo2 def fun(name): iRet=name(10,20) print("Value form fun is:",iRet) def main(): print("Enter first number") iNo1=int(input()) print("Enter second number") iNo2=int(input()) iRet=Addit...
def main(): Employee={11:{"Name":"Piyush","Age":30},21:{"Name":"Kiran","Age":25},51:{"Name":"Prshant","Age":29}} for eid,einformation in Employee.items(): print("Employee id is:",eid) for key in einformation: print(key,einformation[key]) #OR for eid,einformation in Employee.items(): print(...
import pandas as pd import numpy as np def exponential_weighted_average(data, alpha=0.001): """ Function: Using exponential weighted average to perform normalization of data. The exponential weighted average is calculated recursively given: y<0> = x<0> y<t> = (1 - alpha)*y<t-1> + alpha*x<t...
class Planet(object): def __init__(self, x, y): self.height = int(y) + 1 self.width = int(x) + 1 self.grid = self.build() self.rovers = [] def build(self): # Creating a matrix that represents the grid on mars. # Array of rows with 0 representig no occupied spaces and 1 the ones with a rover. w, h ...
class FizzBuzz: def Say(self, number): result = '{}'.format(number) isDivisible3 = number % 3 == 0 isDivisible5 = number % 5 == 0 if isDivisible3 and isDivisible5: result = 'FizzBuzz' elif isDivisible3: result = 'Fizz' elif isDivisible5: ...
def do_bubble_sort(input_list): for i in range(len(input_list)-1): for j in range(len(input_list)-1): if input_list[j] > input_list[j+1]: input_list[j], input_list[j+1] = input_list[j+1], input_list[j] return input_list if __name__ == '__main__': lists = [3, 1, 5, 2, 6 ...
#层「节点」的概念 #每当你在某个输入上调用一个层时,都将创建一个新的张量(层的输出),并且为该层添加一个「节点」,将输入张量连接到输出张量。当多次调用同一个图层时,该图层将拥有多个节点索引 (0, 1, 2...)。 # #在之前版本的 Keras 中,可以通过 layer.get_output() 来获得层实例的输出张量,或者通过 layer.output_shape 来获取其输出形状。现在你依然可以这么做(除了 get_output() 已经被 output 属性替代)。但是如果一个层与多个输入连接呢? # #只要一个层只连接到一个输入,就不会有困惑,.output 会返回层的唯一输出: import keras from ...
''' 题目:画椭圆。  程序分析:使用 Tkinter。 ''' from tkinter import * x = 360 y = 160 top = y - 30 bottom = y - 30 canvas = Canvas(width = 400,height = 600,bg = 'white') for i in range(20): canvas.create_oval(250 - top,250 - bottom,250 + top,250 + bottom) top -= 5 bottom += 5 canvas.pack() mainloop()
''' 题目:输出一个随机数。 程序分析:使用 random 模块。 ''' import random #生成 10 到 20 之间的随机数 print (random.uniform(10, 20)) print(random.gauss(0,1))