text
stringlengths
37
1.41M
"""implemenation of factorial with recursion""" def factorial(n: int) -> int: """recursive implementation of factorial. Simple example without error checking. args: n: positive integer for factoial input returns: integer of product of factorial""" # stop recursion when we get to 1 ...
#!/usr/bin/env python """ Simple iterator examples """ class IterateMe_2: def __init__(self, start=0, stop=5, step=1): self.current = start-step self.stop = stop self.step = step def __iter__(self): return IterateMe_2_iter(self.current+self.step, self.stop, self.step) class...
# -*- coding: utf-8 -*- """ Created on Wed Jun 13 17:18:15 2018 @author: Karl M. Snyder """ # recursive function for factorials def factorial(x): if x == 0: return 1 return x * factorial(x-1) if __name__ == "__main__": for x in range(1, 11): print("factorial for,",x, "is ", factorial(x))
#!/usr/bin/env python3 import pandas as pd def make_upper_att_filter(att, value): def att_filter(data): return [(song, artist, attribute) for song, artist, attribute in zip(data.name, data.artists, data[att]) if attribute > value] return att_filter if __name__ == '__m...
''' Lesson 2 Assignment #1: Generators ''' import numpy as np import pandas as pd music = pd.read_csv("featuresdf.csv") def get_name(result): return result[1] results = sorted([(a,n) for a,n in zip(music.artists, music.name) if a == "Ed Sheeran"], key=get_name) def my_generator(): for i, result in enumerate...
#!/usr/bin/env python 3 def sum_of_int(max): '''Sum of the integers 0 + 1 + 2 + 3 + 4 + 5 + ...''' sum = 0 a = 0 while a < max: sum += a a += 1 yield sum def doubler(max): '''Each value is double the previous value: 1, 2, 4, 8, 16, 32, ...''' a = 1 while a < max: ...
#!/usr/bin/env python """ Regular synchronous script to see how much a given word is mentioned in the news today https://newsapi.org NOTE : you need to register with the web site to get a key """ import time import requests import threading import queue __author__ = "Wieslaw Pucilowski" WORD = "trump" NEWS_API_KEY =...
# multiplier.py """This module provides a multiplication operator""" class Multiplier(): """this performs multiplication""" @staticmethod def calc(operand_1, operand_2): """Multiplication""" return operand_1 * operand_2
# lesson 07 mailroom using peewee # !/usr/bin/env python3 """ Add, Delete, and Modify Donor Database Models in Peewee""" import logging from mailroom_setup import * import datetime logger = logging.getLogger(__name__) database = SqliteDatabase('mailroom_db.db') def add_donation(): """ Add new donation data ""...
""" This module provides a Divider class """ class Divider: """ This class allows for calculator division """ @staticmethod def calc(operand_1, operand_2): """ This method calculates, and returns, the division of the two operands """ return operand_1/operand_2
#!/usr/bin/env python3 class Locke: def __init__(self, size): self.size = size def __enter__(self): print("Stopping the pumps.") print("Opening the doors.") return self def move_boats_through(self, boats): self.boats = boats if self.boats > sel...
"""subtractor Module Contains a single Subtractor class that provides subtraction functionality """ class Subtracter(object): """This class performs a single static subtraction calculation""" @staticmethod def calc(operand_1, operand_2): """Performs subtraction of the two passed operands ...
# ---------------------------------------------------------------------------------------------------------------------- # AUTHOR: Micah Braun # PROJECT NAME: Closures.py # DATE CREATED: 09/13/2018 # UPDATED: N/A # PURPOSE: PYTHON 220 Lesson 02 # DESCRIPTION: Program exemplifies aspects of Python's closures (a function...
""" Simple database example with Peewee ORM, sqlite and Python Here we define the schema Use logging for messages so they can be turned off """ import logging from peewee import * from pprint import * logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info('Here we define...
import pandas as pd # 1st ex.: Using Spotify 2017 top100 track data w/ Pandas + List Comprehensions # m = pd.read_csv('featuresdf.csv') m = pd.read_csv('featuresdf.csv') print('m.head() returns:\n') print(m.head()) print('\nm.describe() returns:\n') print(m.describe(), '\n'*2) a = sorted(list(zip(m.danceability, m.n...
#!/usr/bin/env python # Lesson 1: learning generators def intsum(i=0, count=0): while True: count += i yield count i += 1 def intsum2(i=0, count=0): while True: count += i yield count i += 1 def doubler(i=1): while True: yield i i *= 2 ...
#!/usr/bin/env python3 """ Simple metaclass example that creates upper and lower case versions of all non-dunder class attributes """ class NameMangler(type): # deriving from type makes it a metaclass. def __new__(cls, clsname, bases, _dict): uppercase_attr = {} for name, val in _dict.items(): ...
#!/usr/bin/env python3 import sys import re import json from donor_class import * import os # New instance of the MyDonation class donations_list = MyDonations() def main(): """ Displays the main menu selection options """ # Menu options options = {1: send_thank_you, 2: create...
""" This module provides an Adder class """ class Adder: """ This class allows for calculator addition """ @staticmethod def calc(operand_1, operand_2): """ This method calculates, and returns, the addition of the two operands """ return operand_1 + operand_2
#-------------------------------------------------# # Title: Context Managers: Lockes # Dev: LDenney # Date: February 11th, 2019 # ChangeLog: (Who, When, What) # Laura Denney, 2/11/19, Started work on context Managers Assignment # Laura Denney, 2/13/19, Finished testing #-----------------------------------------...
"""defines divider objects""" class Divider: """defines basic divider object""" @staticmethod def calc(operand_1: float, operand_2: float): """performs division of two numerators with first input being numerator and second input denomenator args: operand_1: numerator f...
import time from math import sqrt, factorial times = 35 def fib_recursive(n): """ The Fibonacci sequence as a generator: f(n) = f(n-1) + f(n-2) 1, 1, 2, 3, 5, 8, 13, 21, 34… """ if n <= 1: return n else: return fib_recursive(n-1) + fib_recursive(n-2) def factoria...
""" Learning persistence with Peewee and sqlite delete the database to start over (but running this program does not require it) """ from mailroom_db_model import * import logging def populate_donor_db(): """ add person data to database """ logging.basicConfig(level=logging.INFO) ...
#!/usr/bin/env python3 import pandas as pd __author__="Wieslaw Pucilowski" music = pd.read_csv("featuresdf.csv") def Find_Artist(artist="Ed Sheeran"): selection = [x for x in list(zip(music.name, music.artists)) if x[1] == artist] def music_gen(): ...
""" Simple module that provides class instances for subtraction operations """ class Subtracter(): """This class has only a static calc method that returns the result of subtraction of two operands """ @staticmethod def calc(operand_1, operand_2): """Subtracts second operand from first ...
"""Module for adding two numbers""" class Adder(object): """Class for addition of 2 numbers.""" @staticmethod def calc(operand_1, operand_2): """ Perforn the addition step.""" return operand_1 + operand_2
import time def memoize(f): memo = {} def helper(x): if x not in memo: memo[x] = f(x) return memo[x] return helper @memoize def fib(n): if n <= 1: return n else: return fib(n-1) + fib(n-2) def fib1(n): if n <= 1: return n else: ...
import pandas as pd music = pd.read_csv("featuresdf.csv") song_list = [ x for x in zip(music.name, music.artists, music.danceability, music.loudness) if x[2] > 0.8 and x[3] < -5] def danceability_sort(x): return x[2] for song in sorted(song_list, key=danceability_sort, reverse=True): print(song)
""" Write a context manager class named "Locke" WHen locked entered: stop pump opens doors closes doors restarts pumps When Locke exited: stops pumps opens doors closes doors restarts pumps class initiation: class accepts locke's c...
# Ballard Locks context manager exercise from time import sleep class Locke(object): """ Creates Locke objects """ def __init__(self, boat_capacity): self.boat_capacity = boat_capacity def typical_operation(*args): op_text = """ Stopping the pumps. Opening the doo...
class Generator: def sum_of_integers(self, int_list): my_sum = 0 for num in int_list: my_sum += num yield my_sum def doubler(self, start, stop): if start < 1: start += 1 cur_value = start for num in range(start, stop): yi...
#!/usr/bin/env python3 """Recursive module""" import sys def my_func(n): if n == 2: return True return my_func(n / 2) if __name__ == '__main__': n = int(sys.argv[1]) print(my_func(n))
def intsum(): x = 0 x_sum = 0 while True: x_sum += x yield x_sum x += 1 def intsum2(): x = 0 x_sum = 0 while True: x_sum += x yield x_sum x += 1 def doubler(): x = 1 while True: yield x x = x + x def fib(): x...
#!/usr/bin/env python3 from math import sqrt def intsum(): x, increment = 0, 1 while True: yield x x += increment increment += 1 def intsum2(): x = 0 while True: yield x * (x + 1) / 2 x += 1 def doubler(): x = 1 while True: yield x x *...
""" ORIGINAL AUTHOR: INSTRUCTOR CO-AUTHOR: Micah Braun PROJECT NAME: adder.py DATE CREATED: File originally created by instructor, date unknown UPDATED: 10/18/2018 PURPOSE: Lesson 6 DESCRIPTION: Returns the calculation of divider(x / y) back to method caller divide(), which returns the calculation to method _do_calc()....
#!/usr/bin/python import sys def my_fun(n): if n == 2: return True return my_fun(n/2) if __name__ == '__main__': n = int(sys.argv[1]) print(my_fun(n)) # The function keeps calling itself without stopping because its termination condition was not set very clearly. It only stops by returning ...
# ------------------------------------------------- # # Title: Lesson 1, pt 2, Iterators Assignment # Dev: Craig Morton # Date: 11/6/2018 # Change Log: CraigM, 11/6/2018, Iterators Assignment # ------------------------------------------------- # # !/usr/bin/env python3 class IterateMe_1: """Simple iterator th...
__author__="Wieslaw Pucilowski" def intsum(): i, sum = 0, 0 while True: sum += i yield sum i += 1 def intsum2(): i, sum = 0, 0 while True: sum += i yield sum i += 1 def doubler(): i = 1 while True: yield i i = i * 2 def fib(): ...
""" Learning persistence with Peewee and sqlite delete the database to start over (but running this program does not require it) """ from personjobdept_model import * from datetime import datetime import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) database =...
from googleapiclient.discovery import build import pandas as pd import demoji import urllib.request import urllib from langdetect import detect import re # regular expression import json from textblob import TextBlob key="AIzaSyAIGeU6DMwurpAb9Ndcwyr9TB2rVzzPnbk" def can_you(): return "hello" #* 1st step # * th...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 29 23:27:43 2018 @author: vicky """ # review probability #inferential statistics #roulette import random class FairRoulette(): def __init__(self): self.pockets = [] for i in range(1,37): self.pocekts.append(i) ...
def get_digits(n): r = [n % 10, n//10 % 10, n//100 % 10, n//1000 % 10, n//10000 % 10, n//100000 % 10] return r def increasing(digits): result = True N = len(digits) for i in range(len(digits) - 1): result = result and digits[N-1 - i] <= digits[N-1 - i-1] return result def adjacent(dig...
#!/usr/bin/env python # coding: utf-8 # In[64]: import pandas as pd import numpy as np import io import warnings warnings.filterwarnings(action='ignore') from matplotlib import pyplot as plt #Import the data file #Distance (meter), Delivery Time (minute) df = pd.read_csv('/Users/hcy/Desktop/수업자료/3학년 1ᄒ...
class Productos(): def __init__(self,nombre,costo,tipo): self.nombre=nombre self.costo=costo self.tipo=tipo def informe(self): print(f""" ---INFORME DEL PRODUCTO--- Nombre: {self.nombre} Costo: {self.costo} Tipo: {self.tipo} """) ...
# Plot import matplotlib.pyplot as plt # Math packages import pandas as pd import math import numpy as np import itertools class Task(object): def __init__(self, dislikes, likes, leadership, learning, language): self.dislikes = dislikes self.likes = likes self.leadership_features = leade...
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 13:58:54 2019 @author: 748418 """ num1 = int(input("Digite um numero: ")) num2 = int(input("Digite outro numero: ")) if (num1 % num2 == 0): print("Numeros são divisíveis.") else: print("Os numeros não são divisíveis")
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 14:05:57 2019 @author: 748418 """ lista = [0,1,2,3,4,5,6,7,9,10,11,12,13,4,15] num = int(input("Quantos elementos você deseja que seja imprimido: ")) print(lista[:num]) #ou for i in range(1,num): print(i)
# a list of strings from builtins import print animals = ['cat', 'dog', 'fish', 'bison'] # a list of integers numbers = [1, 7, 34, 20, 12] # an empty list my_list = [] one_variable = 'touraj' another_variable = 'vitalii' third_variable = 'daniel' # a list of variables we defined somewhere else things = [ one_v...
import types class StrategyExample: def __init__(self, func = None): self.name = 'Strategy Example 0' if func is not None: self.execute = types.MethodType(func, self) def execute(self): print(self.name) def execute_replacement1(self): print(self.name + 'from execute 1') def execu...
def rotate(arr,n): x = arr[n-1] for i in range(n-1,0,-1): arr[i] = arr[i-1] arr[0] = x arr = [1,4,6,8,7] n =len(arr) for i in range(0,n): print(arr[i] ,end=' ') rotate(arr,n) print('\n') for i in range(0,n): print(arr[i] , end=' ')
def maxProfit(prices): maxprofit = 0 for i in range(1,len(prices)): if prices[i] > prices[i-1]: maxprofit += prices[i] - prices[i-1] return maxprofit foo = [1,7,2,3,6,7,6,7] print(maxProfit(foo))
def Uper(word): word = word[0].upper() + word[1:].lower() return word list_of = [] n = int(input()) for i in range(n): person = input() list_of_rezome = person.split('.') person = (list_of_rezome[0], Uper(list_of_rezome[1]) +' ' +list_of_rezome[2]) list_of.append(person) list_of.sort(key=...
# -*- coding: utf-8 -*- # PN: 16 lesson python - try except, Created Mar, 2017 # Version 1.0 # KW: try except # Link: # --------------------------------------------------- lib import while True: # program must pass try loop to enter if loop, prevent function try: age = int(input("What is your age?")) break exce...
# -*- coding: utf-8 -*- # PN: 16 lesson python - 9*9 chart, Created Mar, 2017 # Version 1.0 # KW: for, 9*9 # Link: # --------------------------------------------------- python 2 for i in range(1,10,3): for j in range(1,10): print('%d * %d = %d ' %(i, j, i*j), end="") print('%d * %d = %d ' %(i+1, j, (i+1)*j)...
# -*- coding: utf-8 -*- # PN: 16 lesson python - earthquake, Created Mar, 2017 # Version 1.0 # KW: json, datetime # Link: # --------------------------------------------------- lib import import json, datetime # --------------------------------------------------- start fp = open('earthquake.json', 'r') eqs = json.load(...
# -*- coding: utf-8 -*- # PN: 16 lesson python - filter for prime, Created Mar, 2017 # Version 1.0 # KW: for, filter() # Link: # --------------------------------------------------- lib import import sympy a, b = 500, 600 numbers = range(a, b) prime_numbers = filter(sympy.isprime, numbers) # use filter for numbers to...
""" Módulo responsável por realizar as operações de validação e execução com o DELETE. Sintaxe para criação da table: DELETE FROM nome_tabela WHERE coluna = condição; """ # from pprint import pprint def valida_delete(lista_query, termo_meio): """ pass """ if ve...
""" Módulo responsável por realizar as operações de validação e execução com o INSERT. Sintaxe para criação da table: INSERT INTO nome_tabela VALUES ( valor1, valor2, valor3, ... ); """ def valida_insert(lista_query, termo_meio): """ pass ...
#!/usr/bin/python import sys # input comes from STDIN (stream data that goes to the program) for line in sys.stdin: l = line.strip().split(',') if len(l)>30: dist_lat = (float(l[7]) - float(l[11]))**2 dist_lon = (float(l[8]) - float(l[12]))**2 dist = (dist_lat + dist_lon)**0.5 ...
import nltk import sys def main(grammar_file, input_file, output_file): '''Read the sentences in a file, generate parse trees and count average amount of trees Args: grammar_file(str): a filename for a cfg file, input_file(str): a filename of input file containing sentences to be parsed, output_file(str): ...
def cal_passing_grade(midt, project, finalp): passing_grade = midt * 0.3 + project * 0.3 + finalp * 0.4 return passing_grade st_list = [None] * 5 for index in range(5): print("Write student's info(name-midterm grade -project grade-final project grade)") st = {"Name": input(), "Midterm": float(...
"""Module """ # import math # import cmath from matrix import Matrix def main(): """Main method """ _m1 = Matrix().random_int_matrix(3, 5, -9, 9) # _m2 = Matrix().random_int_matrix(1, 8, -9, 9) # _m3 = Matrix().random_int_matrix(5, 1, -9, 9) # _m4 = Matrix().random_int_matrix(1, 8, -9, 9) ...
f = open("/Users/mcneillc/Dev/my-stuff/advent-of-code-2019/inputs/day6input.txt", "r") orbits_input = f.readlines() orbits_input = [orbit.strip('\n') for orbit in orbits_input] f.close() def retrieve_objects(orbit): object1, object2 = orbit.split(')') return [object1, object2] def find_inner_orbits(orbits, ...
from nltk.corpus import stopwords # 先token⼀把,得到⼀个word_list # ... # 然后filter⼀把 word_list = {'a','b','c'} filtered_words = [word for word in word_list if word not in stopwords.words('english')]
from util import get_input, get_int_input, char_to_int, int_to_char, invmodp from errors import InvalidCharError, InvalidInputError def decode_affine(ciphertext, multiply, offset): """ TODO: this function should return the plaintext. For example: "SGHR HR Z SDRS." should return "THIS IS A TEST." (note t...
from typing import Optional import numpy as np import pandas as pd import plotly.graph_objects as go import seaborn as sns from . import stats def plot_bar( df: pd.DataFrame, ddg_cols: str, error_cols: str, exp_col: str = "exp", exp_error_col: str = "dexp", name_col: str = "edge", title:...
# def measure_string(myStr): # count = 0 # if myStr == myStr[-1]: # return count + 1 # else: # return 1 + measure_string(myStr[1:]) # # count = 0 # # if myStr == myStr[-1]: # # return count # # else: # # return measure_string(myStr[1:]) # #The line below will tes...
# Video 8 ''' Tirar 4 veces un dado1Eliminar el Valor menor y Sumar el Total restante ''' import random ''' dado1 = random.randint(1,6) dado2 = random.randint(1,6) dado3 = random.randint(1,6) dado4 = random.randint(1,6) suma = dado1 + dado2 + dado3 + dado4 menor = min(dado1, dado2, dado3, dado4) Fuerza = suma - menor...
import random p = 1 r = 1 s = 1 while True: print(f'p = {p} \t r = {r} \t s = {s}') mylist = ['p', ] * p + ['r', ] * r + ['s', ] * s our_combination = random.choice(mylist) player_combination = input('input p, r, s for playing. q for finish ') if player_combination in {'p', 'r', 's'}: if player_combination == ...
""" Кода до 10ти строк. использование: notifier = notify(every=1000) создали нотификатор и внутри цикла дергаем его а он каждые 1000 раз выводит "Итерация __ выполнена" (используется при генерации допустим большого файла чтоб видеть на какой стадии процесс) """ def count_squares(stop): for j in range(stop): ...
""" Read about the Fibonacci search and implement it using python. Explore its complexity and compare it to sequential, binary searches. """ def fibonacci_search(collection, value): fib_m_minus_2 = 0 fib_m_minus_1 = 1 fib_m = fib_m_minus_1 + fib_m_minus_2 while fib_m < len(collection): fib_m_m...
"""Create your own implementation of an iterable, which could be used inside for-in loop. Also, add logic for retrieving elements using square brackets syntax.""" class IterObj: def __init__(self, *args): self.__iter_obj = [*args] self.__start = 0 def __iter__(self): return self ...
""" Найти кратчайший маршрут на графе из одной заданной точки в другую """ class Node: instances = {} def __init__(self, name): self.name = name def __repr__(self): return f'{self.name}' def __new__(cls, *args, **kwargs): name = args[0] if name not in cls.instances: ...
""" task 4 получаем в цикле число действие второе число пишем промежутчный результат запрашиваем действие и снова число действие... если вместо числа или действия введено Q выходим""" def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def get_number(): ...
from collections import deque from lesson_24.stack import Stack ERROR_MSG = 'ERROR' class InfixToPostfix: def __init__(self, expression): self.expression = expression self.__operators = Stack() self.__output = [] self.__precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3, ')': ...
"""Task 4 The math quiz program Write a program that asks the answer for a mathematical expression, checks whether the user is right or wrong, and then responds with a message accordingly. """ import random start = 0 stop = 20 while True: number_1 = random.randint(start, stop) number_2 = random.randint(start, stop...
# https://www.hackerrank.com/challenges/string-validators/problem if __name__ == '__main__': string = input() if len(string)> 0 and len(string)<= 1000: print(any(c.isalnum() for c in string)) print(any(c.isalpha() for c in string)) print(any(c.isdigit() for c in string)) print(a...
# https://www.hackerrank.com/challenges/python-print/problem # The included code stub will read an integer, , from STDIN. # Without using any string methods, try to print the following: # Note that "" represents the consecutive values in between. # Example n = 5 #Print the string 12345 if __name__ == '__main__': ...
# https://www.hackerrank.com/challenges/list-comprehensions/tutorial if __name__ == '__main__': x,y,z,n = map(int,input('Enter values separated by a space:').split(" ")) results = [] for x in [i for i in range(x+1)]: for y in [j for j in range(y+1)]: for z in [j for j in range(z+1)]: if ...
from selenium import webdriver from selenium.webdriver.support.select import Select driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.get("https://rahulshettyacademy.com/angularpractice/") driver.find_element_by_name("name").send_keys("mounika") driver.find_element_by_css_selector("input[name =...
# # 7-6 # age = float(input("Enter your age:")) # grade = int(input("Enter your grade:")) # bug: 56age and 2grade will not respond # if age >= 8 : # if grade >=3: # print("You can play this game.") # else: # print("Sorry, you can't play the game.")
# print("Enter your name:") # somebody = input() # print("Hi, %s, how are you today?" % somebody)
# print("I am 6'2\" tall.") # # print('I am 6\'2" tall.') # # tabby_cat = "\tI'm tabbed in." # persian_cat = "I'm split\non a line" # backslash_cat = "I'm \\a \\ cat." # # fat_cat = ''' # I' ll do a list: # \t* Cat food # \t* Fishies # \t* Catnip\n\t* Grass # ''' # # print(tabby_cat) # print(persian_cat) # print(backsl...
# test items #1. 5 times # for i in range(1, 6): # print('Hi, Warren') #2. 3 times # for i in range(1, 6, 2): # print('Hi, Warren') #3. 1234567 # for i in range(1, 8): # print(i) #4. 01234567 # for i in range(8): # print(i) #5. 2-4-6-8 #6. 10-8-6-4-2 #7. continue #8. when the condition is not adapt # ...
# 测试题 apple = int(3.14) print(apple) # 第二题不行 先算5/9 等于零 temp = 13.2 # 第三题 print(int(temp+0.5)) # 动手试一试 cat = '12.34' dog = float(cat) duck = int(56.78) ken = int(float(cat)) print(dog, " ", duck, " ", ken)
# test items # 1. insert( , ) , extend([]), append(), # 2. pop() ,remove(), del letters[3] # 3. sorted() # 4. 'value' in letters # 5. ------> letters.index('d') # 6. couple = (1,3,5) # 7. couple = [[], []] # 8. value = couple[0][0] # try items # # 1. # print("Enter 5 names:") # names = [] # for i in range(5): # ...
# -*- coding: utf-8 -*- # @Time : 2020/8/1 16:05 # @Author : sml # @File : 7.跳台阶.py """ 题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。 题目解析 这是一道经典的递推题目,你可以想如果青蛙当前在第n级台阶上,那它上一步是在哪里呢? 显然,由于它可以跳1级台阶或者2级台阶,所以它上一步必定在第n-1,或者第n-2级台阶, 也就是说它跳上n级台阶的跳法数是跳上n-1和跳上n-2级台阶的跳法数之和。 """ class Solution: def ju...
# -*- coding: utf-8 -*- # @Time : 2020/8/24 10:25 # @Author : sml # @File : 49.把字符串转换成函数.py """ 题目描述 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0 输入描述: 输入一个字符串,包括数字字母符号,可以为空 输出描述: 如果是合法的数值表达则返回该数字,否则返回0 思路:1.先考虑第一个字符是否存在[+,-] 2.考虑字符串内是否有特殊字符,有就返回0 3.考虑字符串是否仅有[+,-] 4.考虑空字符串 """ class Solution...
# -*- coding: utf-8 -*- # @Time : 2020/8/1 13:29 # @Author : sml # @File : 3.从头到尾打印列表.py #insert() 函数用于将指定对象插入列表的指定位置。 class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): # write code here l = [] head = listNode while head: l....
x = input("Digite un numero x para compararlo con 30: ") if int(x) < 30: print("x es menor que 30") elif int(x) == 30: print("x es igual 30") else: print("x es mayor que 30") y = input("Digite un numero y para verificar si esta entre 2 y 100: ") if int(y) > 2 and int(y) <= 100: print("y esta ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn data=pd.read_csv("Salary_Data.csv") X=data.iloc[:,:1].values y=data.iloc[:,1].values from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.33) from sklearn.linear_model ...
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X:...
####################################################################### # Sort paperauthors import pandas as pd import sys from sets import Set ####################################################################### #### Get the subset of authors that are found in paperauthors # I do a few things to cut down the size o...
# -- coding: utf-8 -- f = "%r %r %r %r" print f % (1,2,3,4) print f % ("one","two","three","four") print f % (True,False,False,True) print f %(f,f,f,f) print f % ("I had this thing.", "That you could type up right.", "But it didn't sing.", "So I said goodnight.") #效果全部答应出来了 ''' 习题: 手打代码,没有发生错误 对...
l1 = list('ABCDE') print(l1*3) print(3*l1) print(l1+l1) del l1[2] print(l1) l1.reverse() print(l1)
decision=True while decision: import random import time HANGMANPICS=[''' +---+ | | | | | | =========''',''' +---+ | | O | | | | =========''',''' +---+ | | O | | | | | ...
# Parte de scrypt.py # Documentacion de: https://passlib.readthedocs.io/en/stable/lib/passlib.hash.scrypt.html # Integrantes: # Jorge Azmitia # Cristina Bautista # Sebastian Maldonado # Abril Palencia # Cesar Rodas from passlib.hash import scrypt def opcion1(password): h = scrypt.using(salt=b'salt', salt_size=1024,...
print("hello,world") print("how are you") def learn(n): sum = 0 for i in range(n): sum+=i return sum
#!/usr/bin/env python3 # for looping large number of data stream from itertools import groupby """ Poker Hand: Read poker_hand.txt. Create High card number for 'T', 'J', 'Q', 'K' and 'A' as 10,11,12,13,14 and combine with range(2, 10) and save it to card_value variable. """ # Card Value for card...
import numpy as np A = np.array([[1, 2], [3, 4]]) B = np.array([10, 20]) print(A * B) #1차원 배열인 배열 B가 2차원 배열 A와 똑같은 형상으로 변형된 후 원소별 연산 수행