text
stringlengths
37
1.41M
# This works was inspire by the worked example "Counting email in databases" which we get the email from a txt file. # Then I want to retrieve the email in the url format and # I successfully get the email from "http://www.py4inf.com/code/mbox-short.txt" # However, I find it cannot read from "https://www.py4e.c...
total = 0 for num in range (1, 1000): if (num % 3 == 0) or (num % 5 == 0): total += num print(total)
import csv import sys def unique_csv(connections, column): connections_list = [] with open(connections, 'r', newline='') as connections_file: reader = csv.reader(connections_file, delimiter=',') for row in reader: if row[column] not in connections_list: connections_list.append(row[column]) ...
from random import randint """ SUDOKU (SOLUTION) BOARD GENERATION 1. Sudoku board is built row by row with recursion 2. For every cell, its row, square and col possible values are checked 3. If no solution can be found, the row is re-built via recursion 4. If the row is re-built too many times, break out of the recursi...
from matplotlib import * from Funcoes import * import time def newton(ai, nit): # Trata divisão por 0 if fd(ai) == 0: return p = ai - (f(ai) / fd(ai)) # Teste de parada if (mod(p - ai) < dx) or (mod(p - ai) / mod(p) < dx) or (mod(f(p)) < dx): print("Raiz:", p) pr...
import math num = int(input("How many species in this gas mixture? ")) x = [0] * num M = [0] * num mu = [0] * num for i in range(0, num): x[i] = float(input("Enter the Molar Fraction: ")) M[i] = float(input("Enter the Molecular Weight: ")) mu[i] = float(input("Enter the mu value: ")) def calculate(x, M, ...
import sys, time MOVE_COSTS = [1, 1, 10, 10, 100, 100, 1000, 1000] AMPHIPOD_INDEX_TO_TYPE = [ "A", "A", "B", "B", "C", "C", "D", "D", ] def solve(): board = [list(l) for l in open("day-23-part-one-input.txt").read().splitlines()[1:-1]] amphipods = get_amphipods_from_board(bo...
def solve(): print("Part one fuel = " + str(sum(partOne()))) print("Part two fuel = " + str(partTwo())) def partOne(): lines = open("day-1-input.txt").readlines() fuel_masses = [] for line in lines: fuel_masses.append(fuelEqn(int(line))) return fuel_masses def partTwo(): fuel_m...
class Str(): def __init__(self,name,expected_type): self.name = name self.expected_type = expected_type # 限制name传入类型 def __get__(self, instance, owner): '''获取''' print("get-->",instance, owner) # 防止类访问name属性 if instance is None: return self ret...
Question:1 What is python?? Ans: Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: web development (server-side), software development, mathematics, system scripting. What can Python do? Python can be used on a server to create web applications. Pytho...
from math import floor def fuel_required(mass): return floor(mass/3) - 2 def get_input_string(): with open('day1input.txt') as f: return f.read() def part1(): input_list = [int(x) for x in get_input_string().splitlines()] total = 0 for m in input_list: total += fuel_required(m) return total def fuel_requi...
import csv from random import choice def gen_num_phrase(): dice = list(map(str, list(range(1, 7)))) num_phrase = [] for _ in range(5): num_phrase.append(choice(dice)) return ''.join(num_phrase) #importing diceware dictionary reader = csv.reader(open('11_diceware.csv')) #crearing dictiona...
from random import choice from collections import defaultdict as dd n = int(input('Enter number of sides of the dice:')) l = list(range(1, n+1)) s = int(input('Enter the number of simulations to be used:')) d = dd(int) for _ in range(s): c = choice(l) d[c]+=1 for k in d.keys(): d[k]=round(d[k]*100/s, 3) ...
#Program to print couln name #Print the total number of rows and columns in a sheet import pandas as PD file_path="D:\\Pythonpractice\\Book1.xlsx" a=PD.read_excel(file_path,sheet_name='Sheet1') print('Column names ',a.columns)
import os import pathlib def home_is_where_this_file_is(): """Changes the working directory to wherever this file is located.""" current_working_directory = pathlib.Path.cwd() file_home_directory = pathlib.PurePath(__file__).parent if current_working_directory == file_home_directory: return ...
# LIBRARIES AND MODULES # # for access to the filesystem and for some useful functions on pathnames from pathlib import Path # and for an additional useful function for changing directories from os import chdir ## Print the current working directory and home directory on screen so I can confirm them visually. print(f...
""" 给定一个已按照 非递减顺序排列  的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。 函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。 你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。   示例 1: 输入:numbers = [2,7,11,15], target = 9 输出:[1,2] 解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 =...
''' A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and dc...
""" Given two strings, write a method to decide if one is a permutation of the other. """ # str_1= "google" # str_2 = "ooggle" str_1= "bad" str_2 = "dab" from itertools import permutations permword = [] def allPermutations(str, str_2): # Get all permutations of string 'ABC' permList = permutations(str) ...
input_str = "LucidProgramming" def countlen(word): if word == "": return 0 else: return 1+ countlen(word[1:]) print(countlen(input_str))
def find_next_empty(puzzle): #finds empty cell in puzzle #return tuple row, col for r in range(9): for c in range(9): if puzzle[r][c] == -1: return r, c return None, None # if all cells are filled def is_valid(puzzle, guess, row, col): #checks if input is vali...
#迭代器切片 def count(n): while True: yield n n+=1 c=count(0) #c无法通过下标切片,通过itertools在迭代器或者生成器上做切片 import itertools for x in itertools.islice(c,10,20): print(x) #消耗性!
#大型数组运算 import numpy as np ax=np.array([1,2,3,4]) ay=np.array([5,6,7,8]) print(ax*2) print(ax+10) print(ax+ay) print(ax*ay) #该模块还提供通用函数 print(np.sqrt(ax)) print(np.cos(ax)) #构造超大数组 grid=np.zeros(shape=(10000,10000),dtype=int) print(grid) #同样所有操作都会作用到每个元素 print(grid+10) #numpy扩展了列表的索引功能 a=np.array([[1, 2, 3, 4], [5, ...
#跳过可迭代对象的开始部分 with open('somefile.txt') as f: lines =(line for line in f if not line.startswith('#')) for line in lines: print(line,end='') #知道获取的元素的形式 from itertools import dropwhile with open('somefile.txt') as f: for line in dropwhile(lambda line:line.startswith('#'),f): print(line,end='...
#序列上索引值迭代 #迭代一个序列的同时跟踪一个正在被处理的元素索引 my_list=['a','b','c'] for idx,val in enumerate(my_list): print(idx,val) #传递开始参数 for idx,val in enumerate(my_list,1): print(idx,val) from collections import defaultdict word_summary=defaultdict(list) with open('somefile.txt') as f: lines=f.readline() print(lines) for idx,l...
#字节字符串的字符串操作 import re #支持正则表达式,正则表达式本身必须是字节串 data=b'a a' #print(re.split('\s',data))报错 print(re.split(b'\s',data)) #注意 #1、字节字符串的索引操作返回的是整数而非字符 #2、字节字符串的输出需要先解码为文本字符串,否则无法支持格式化操作 print(data.decode('ascii'))
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 def conectar(): con = sqlite3.connect('usuarios.db') con.row_factory = sqlite3.Row return con def existe(nombre): con = conectar() c = con.cursor() query = "SELECT * FROM usuarios WHERE user='" + nombre + "'" resultado = c.execute...
import csv from schoolByCondition import * def subjectDict(): from collections import defaultdict data = defaultdict(list) with open('Data/subjects-offered.csv', 'rb') as data_file: reader = csv.DictReader(data_file) for row in reader: data[row['School_Name']].append(row['Subj...
#%% import csv from collections import Counter #%% def leer_arbol(nombre_archivo): types = [float, float, int, int, int, int, int, str, str, str, str, str, str, str, str, float, float] with open(nombre_archivo, 'rt', encoding="utf8") as f: filas = csv.reader(f) headers = next(filas) #Salta l...
# Agustin Avila # tinto.avila@gmail.com # 17/8/21 import csv # Funcion que devuelve los datos del camion como una lista de diccionarios def costo_camion(nombre_archivo): datos = [] with open(nombre_archivo, 'rt') as f: rows = csv.reader(f) headers = next(rows) #Salta los datos de cabecera ...
main_list = [10, 12, 13, 43, 20, 15, 27, 18, 29, 42] # Simple squaring of all elements of main_list def list_comprehension_squared(list): # For rebasing practice # Check if list is not empty if list: # Quadruple all numbers temp_list = [x**4 for x in list] func = lambda x: x + 10 ...
#!/usr/bin/env python3 # File encryption only (micro-arch). # This test implements file encryption encryption and decryption. # Files are encrypted with one round of encryption with the same algorithm as the secret message cipher. # Further work on this function would implement encryption rounds with key permutation. #...
#!/usr/bin/env python3 # File encryption only (micro-arch). # This test implements file encryption encryption and decryption. # Files are encrypted with one round of encryption with the same algorithm as the secret message cipher. # Further work on this function would implement encryption rounds with key permutation. #...
# Let's create reptile class to inherit Animal class from animal import Animal # importing Animal class class Reptile(Animal): # inherting from Animal class def __init__(self): super().__init__() # super is used to iherit everything from the parent class self.cold_blooded = True self.tetra...
def loGtest(): user_key = {'kelvin@gmail.com': 5, 'blue': 1, 'red': 2, 'yellow': 3} passKey = {5: 'rt'} pkey=0 # this gives the set of keys and values that can be displayed for the administrator to see about login details d = user_key.keys() f = user_key.values() pr...
#!/usr/bin/python print "My name is %s and weight is %d kg ! " %('Zara' ,21) para_str= """ this is to show thaat there will be no reason to saccept the the only fine line betweeen this ad tht is lonly a matter of time and this will bew inherently shown by the standards and the will be nothing more to it aa...
print ("Enter a number ") try: caseinterMed=int(input("please enter the number over here ")) reDnum=45 + caseinterMed print(reDnum) except ValueError : print("re enter the right data type which is a number ")
import webbrowser #Permite a exibição de docs web aos usuários import tkinter #Interface padrão do python para o kit de ferramentas TK from time import sleep root = tkinter.Tk( ) #Nome do sistema == root root.title('Abrir browser') root.geometry('300x200') #Tamanho do sistema def opensite(): site = str(input('Dig...
from Util import Util class Node: def __init__(self, key, children, is_leaf=True, value=None): """ Basic element of the Trie :param key: The key of the node :param children: List of children nodes :param is_leaf: Is current node leaf or not, default=False :param va...
import string import numpy as np import math import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer def get_keywords(text): text.rstrip() """ Remove stop words and punctuation """ stop_words = stopwords.words('english') + list(string.punctuation) text = ' '.join...
# -*- coding: utf-8 -*- from __future__ import print_function from random import randint try: input = raw_input except NameError: pass """ Coś tu nie gra! Gracz zgaduje kilka razy, ale widzi zawsze komunikat "pierwsza próba"... Dodaj do funkcji <<zgadnij>> argument "proba" i wypisuj poprawny komunikat z numere...
num = [1, 2, 3, 4, 5] num = iter(num) print(num) x = list(num) # 迭代器转换成列表 print(x) # ######################### 迭代器 ############################## # # 迭代器可以通过 next 进行遍历 # print(next(num)) # 1 # print(next(num)) # 2 # print(next(num)) # 3 # print(next(num)) # 4 # print(next(num)) # 5 # # print(next(num)) # 源列表只有五个...
#%% -1- import numpy as np import cv2 img = cv2.imread(r"C:\Users\OSMANMERTTOSUN\Desktop\barcode.png") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #%% -2- # OpenCV provides three types of gradient filters or High-pass filters, Sobel, Scharr and Laplacian. # If ksize = -1, a 3x3 Scharr filter is used which gives bet...
import random while True: a = input('ask me something') answers = ['yes', 'no', 'maybe', 'shut up', 'go away', 'im sleeping', 'ok'] print(random.choice(answers))
#Alex Chen,CSC201 #Lab03,Part5 #Objective:Computing the total number of matching DNA fragments DNA1 = input("Enter the first DNA sequence:") DNA2 = input("Enter the second DNA sequence:") def dna_Match(DNA1,DNA2): count = 0 if len(DNA1) > len(DNA2): small = DNA2 big = DNA1 else: sm...
# import pandas as pd import csv from difflib import SequenceMatcher file_name = 'data/faq.csv' NO_RESULT = "Ничего не найдено по вашему вопросу, вы можете задать вопрос по " \ "ссылке https://pk.mipt.ru/faq/" def compare(question): global Answer, Answer2, Answer3, Answer4, Answer5, Score, Score2, Sc...
# -*- coding: utf-8 -*- """ Created on Wed Mar 20 23:32:40 2019 @author: Shyam Parmar """ import pandas as pd import numpy as np import random as rd from sklearn.decomposition import PCA from sklearn import preprocessing #Preprocessing for scaling data import matplotlib.pyplot as plt ###############...
a = int(input("Введите сколько км ")) b = int(input("Введите сколько км ")) d = 1 while a < b: a *= 1.1 d += 1 print(d)
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here if number <= 2: return number first,second,third = 1,2,0 for i in range(2,number): third = first + second first,second = second,third return third
# coding: utf-8 import numpy as np import matplotlib.pyplot as plt def main(): m = 1000 # Number of trials for each size sample_sizes = np.array([10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000]) biased = np.zeros(len(sample_sizes)) unbiased = np.zeros(len(sample_sizes)) for i in range(len(sample_sizes))...
def answer(numbers): if (len(numbers) == 2): return 2 else: current=0 index=1 while(numbers[current]>=0): next = numbers[current] numbers[current] = (-1 * index) index+=1 current=next return (index-(numbers[current]*-1)) ...
# 내부 함수로 구현 print("s : ") s = input() print("t : ") t = input() def fcmp(s, t): def numcmp(s, t): num1 = float(s) num2 = float(t) if num1 > num2: return 1 elif num1 < num2: return -1 else: return 0 def strcmp(s, t): str1 = s...
#Task_3 #========================================Метод словаря=================================== calend = { 'Зима':['12','1','2'], 'Весна':['3','4','5'], 'Лето':['6','7','8'], 'Осень':['9','10','11'] } while True: mnt = input('Введите номер месяца - ') if (int(mnt) < 1) | (int(mnt) > 12): ...
#Task_5 my_list = [7,5,3,3,2] j=0 print(my_list) while True: n = int(input("Введите число 1-9 \n")) if not((n<1) | (n>9)): break for i in my_list: if n < i: j+=1 my_list.insert(j,n) print(my_list)
import networkx as nx import matplotlib.pyplot as plt G=nx.DiGraph() G.add_node(0),G.add_node(1),G.add_node(2),G.add_node(3),G.add_node(4) G.add_edge(0, 1),G.add_edge(1, 2),G.add_edge(0, 2),G.add_edge(1, 4),G.add_edge(1, 3),G.add_edge(3, 2),G.add_edge(3,1),G.add_edge(4,3) nx.draw(G, with_labels=True, font_weight='bol...
# EP - Design de Software # Equipe: Pedro Cliquet do Amaral # Data: 18/10/2020 import random fichas = 100 while fichas > 0 : if fichas == 0 : break carta = random.randint(0,9) print('Fichas disponiveis {0} ' .format(fichas)) aposta = int(input('quanto quer apostar? ')) i...
# Daily Challenge : Build Up A String # Using the input function, ask the user for a string. The string must be 10 characters long. # If it’s less than 10 characters, print a message which states “string not long enough” # If it’s more than 10 characters, print a message which states “string too long” # Then, print the...
# Exercise 1 xp : Convert Lists Into Dictionaries # Convert the two following lists, into dictionaries. # Hint: Use the zip method # keys = ['Ten', 'Twenty', 'Thirty'] # values = [10, 20, 30] # Expected output: # {'Ten': 10, 'Twenty': 20, 'Thirty': 30} # Solution : # def Convert_dict(a): # init = iter(keys) #...
#Exercise 2 : Dogs # class Dog: # def __init__(self, name, height): # self.name = name # self.height = height # def bark(self, message): # print("{} {}".format(self.name, message)) # def jump(self): # print("{} jumps {}cm high".format(self.name, self.height*2)) ...
# Exercise 1 xp : What Are You Learning ? # Write a function called display_message() that prints one sentence telling everyone what you are learning about in this chapter. # Call the function, and make sure the message displays correctly. # Solution : # def display_message(): # print("Today we learned function !...
import sys import unittest from unittest.mock import patch from fizzbuzz.app import run, fizz_buzz, convert_to_int class TestFizzBuzz(unittest.TestCase): def test_fizzbuzz_returns_correct_list(self): """ Test that fizzbuzz list has correct values for multiples """ fizzbuzz = fizz_...
def main(): print('This tests if else statements and function') number_test = float(input('Please insert a number')) if number_tester(number_test): print('This number is five.') else: print('This number is not five.') def number_tester(number_test): if (number_test) == ...
from integer import Integer first_number = int(input('Type a first integer number: ')) second_number = int(input('Type a second integer number: ')) print('1 - Add') print('2 - Subtract') print('3 - Multiply') print('4 - Divide') operation = int(input('Type a valid operation! please!: ')) if operation is 1: resul...
''' Esto es un adelanto en hackaton , comentario en bloque ''' nombre = 'Angel Diaz' edad = 15 esta_Trabajando = True # False dato = input ('Introducir un dato: ') print(dato) print(edad) if( edad >= 18 ): print('mayor') else: print('menor') def cuadrado(x): return x * x cuadrado_de_dos = cuadrado(2) p...
import matplotlib.pyplot as pyplot x = [x * x for x in range(1, 100) if x % 2 == 0] x.append(100) y = [y * y for y in range(1, 100) if y % 2 != 0] pyplot.plot(x, y) pyplot.show()
# coding=utf-8 import functools def map_test(): """ map test """ # map 函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 i = (1, 2, 3, 4, 5, 6, 7, 8, 9, 19) map_process = map(lambda x: str(x) + ".", i) for i in map_process: print(i) def reduce_test(): """ reduc...
from collections import deque """ 参数数组 """ de = deque([1, 2, 3]) print(de) """ 单个元素都可 """ de.append('a') de.append('b') print(de) de.appendleft('left') print(de)
# coding=utf-8 """ 解决闭包不优雅的方式""" def return_fun(): fs = [] def go(j): def fun(): return j * j return fun for temp in range(3): fs.append(go(temp)) return fs if __name__ == '__main__': result = return_fun() print(result) for x in result: pr...
# coding=utf-8 def return_fun(): """ return a function :return: """ def add(x, y): """ return result of x plus y :param x: :param y: :return: """ return x + y return add if __name__ == '__main__': add = return_fun() print(add) print(a...
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ rev = 0 w...
############################################################ # CIS 521: Homework 2 ############################################################ student_name = "Shubhankar Patankar" ############################################################ # Imports ##########################################################...
# Lab 1: Python program to check if rectangles overlap using object oriented paradigm # CS107, Haverford College # <replace with your name> # Creating a class rectangle # https://en.wikipedia.org/wiki/Rectangle # # This program is intended to find whether two rectangles overlap (or intersect) each other or not. # In th...
#!/usr/bin/python3 ''' Q4.1 Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. ''' from Graph import Graph from Queue import Queue #depth first search def dfs(graph, u, v, visited=None): if visited == None: visited = set() res...
#!/usr/bin/python3 """ Question 1.2 Check Permutation: Given two strings, write a method to decide if one is a permutation of the other. Note: permutation -> when all charas in str1 are present in str2; order does not matter; whitespace matters; confirm if str is ascii """ #----------------------------------...
#!/usr/bin/python3 ''' Q2.5 Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE In...
########################################################## # Name: greedy_algorithms.py # Description: contains implementation of Prim's algorithm # Author: Medina Lamkin # Last Edited: 13/03/19 ########################################################## import math from graph import * # doesn't account for ...
#!/usr/bin/env python #-*- coding: utf-8 -*- def palindrom(lancuch): lancuch=lancuch.lower().replace(" ", "").decode("utf-8") lancuch_odwrocony=lancuch[::-1] if lancuch_odwrocony==lancuch: return True else: return False print palindrom("Kobyła ma mały bok") print palindrom("Zakopane...
# 现在,对于任一个英文的纯文本 txt 文件,请统计其中的单词总数 # 结果示例: # There are 687 words in words.txt. # 导入模块 import re import os def search(): # 设定查找规则 pattern = re.compile(r"[A-z]+") path = os.listdir(path="D:\\pythonwork\\小应用") while True: user_input = input("请输入您想查询的文件:") # 设置判断如果搜索的文件名在该目录下的话执行查找,否则告知文件...
from typing import List, Dict, Union from .db_conn import DatabaseConnection """ Concerned with storing and retrieving books from a csv file Format of the csv file: name,author,read """ Book = Dict[str, Union[str, int]] def create_book_tables(): with DatabaseConnection() as connection: cursor = connect...
#!usr/bin/env python #coding=utf-8 import nwmath import unittest class addTest(unittest.TestCase): ''' Test the multiplyTest from the nwmath library ''' def test_add_integer(self): """ Test that subtracting integers returns the correct result """ result=nwmath.add(3, 4)...
import datetime class numToWord: _dict20 = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', ...
secret = 'swordfish' pw = '' count = 0 auth = False max_attempts = 5 while pw != secret: count += 1 if count > max_attempts: break pw = input(f'{count}: What is the secret word? ') else: auth = True print('Authorized.' if auth else 'Calling FBI...')
import sqlite3 def main(): print('Create DB connection') db = sqlite3.connect('My_DB-API.db') cur = db.cursor() cur.execute('DROP TABLE IF EXISTS my_table') cur.execute(""" CREATE TABLE my_table ( id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT ...
def main(): x = [5] print(f'in main x is {x}') print(f'id x is {id(x)}') kitten(x) print(f'in main x is {x} after calling the function') print(f'id x is {id(x)}') def kitten(a): print(f'in function id a is {id(a)}') a[0] = 3 print(f'in function a is assigned to {a}') ...
def main(): print("1. Create a list wich consists of elements of the other list which are multiplied by 2.") l1 = range(11) l2 = (i*2 for i in l1) print_list(l1) print_list(l2) print("\n2. Create a list which consists of elements of the other list that are not dividable by 3.") l3 =...
#!/usr/bin/python #word_count.py #python program to count the words in the line. class strcou: def method(self,str): self.str=str a=self.str.split() temp=[] for i in a: temp.append(i) if temp.count(i)>1: pass else: print i,a.count(i) z=strcou() z.method("""sandeep reddy chinna papanna svec ...
#!/usr/bin/python #head.py #python program to open the file, reading and printing. class head: def read1(self,file): self.f=file fd=open(self.f,'r') txt=fd.read() return txt class main(head): def method(self,nam,line): data=head.read1(self,nam) self.line=line s='' count=0 for i in data: if i!='\n...
""" Name : Word Count Author: Benjamin Wacha Email: bmwachajr Disc: A python app that counts the occurrence of a word in a string """ def words(string): dict = {} list = string.split() list.sort() for word in list: if word.isdigit(): word = int(word) if word in dict: dict[word] = dict...
__author__ = 'Renan Nominato' __version__ = '0.0.1' """" This script selects randomly words, and create multiple choice questions looking for the meaning. """ import pandas as pd import numpy as np import random as rn import os from gtts import gTTS import time questions = pd.read_csv("Planilha sem título - Vocab.c...
### delete function of BST #### class node: def __init__(self, value=None): self.value = value self.left_child = None self.right_child = None self.parent = None class binary_search_tree: def __init__(self): self.root = None def insert(self,value): if self.r...
from produto import produtos class estoque: def __init__(self): self.lista = [] self.total = 0.0 def cadastrar(self,produto, valor, tipo,quant_estoque): if len(self.lista) == 0: pro = produto(produto, valor, tipo, quant_estoque) self.lista.append(pro...
import numpy as np import matplotlib.pyplot as plt n = 5 l = [0 for i in range(n)] nv=[0 for i in range(n)] for i in range(n): nv[i]=int(i+1) l[0] = 2**0.5 for i in range (1,n): l[i] = (2+ l[i-1]**0.5)**0.5 print((2+2**0.5)**0.5) print((2+(2+2**0.5)**0.5)**0.5) plt.plot(nv,l,".") plt.xlabel("n") ...
"""This module provides helper functionality with time.""" from datetime import timedelta DATE_FORMAT = "%Y.%m.%d" DATETIME_FORMAT = "%Y.%m.%d %H:%M:%S" def generate_days_period(start_date, end_date): """Yield days in provided date period.""" start_date = start_date.replace(hour=0, minute=0, second=0, micr...
""" David Rubio Vallejo Implements a CNN with an embedding layer consisting of the word vectors for the input words, a 2D convolutional layer with MaxPooling and Dropout, and an output layer mapping into a single neuron. A CNN model is typically represented as the four-tuple (N, C, H, W), where N = Batch size C = Cha...
p1 = input().split(" ") x1 = float(p1[0]) y1 = float(p1[1]) p2 = input().split(" ") x2 = float(p2[0]) y2 = float(p2[1]) Distancia = ((x2-x1)** 2 + (y2-y1)** 2)**0.5 print (f'{Distancia:.5}')
# -*- coding: utf-8 -*- """ Created on Fri Jan 08 14:11:19 2016 @author: ashutoshsingh The file takes the turnstile data and runs a linear regression model on it. It also calculates the R-squared values and plots the graph of it """ import pandas as pd import numpy as np from ggplot import * from scipy import stat...
#!/usr/bin/python n = input('Height (>4): ') if n < 2: print "WTF?! Your tree is too small ! I'll make it higher\n" n = 4 i = 1 while i <= n: print (n/3)*" " + (n-i)*' ' + (i-1)*'*_' + '*' i += 1 print "\nMerry Christmas!"
import json def registra_aluno(nome, ano_entrada, ano_nascimento, **misc): """Cria a entrada do registro de um aluno.""" registro = {'nome': nome, 'ano_entrada': ano_entrada, 'ano_nascimento': ano_nascimento} for key in misc: registro[key] = misc[key] ...
# How many distinct terms are there of the form a^b for 2\leq a,b\leq 100? # # Answer: 9183 import sets nums = sets.Set() for a in range (2,101): for b in range(2,101): nums.add(pow(a,b)) print len(nums)
# Find the largest palindrome made from the product of two 3-digit numbers. # # Answer: 906609 def is_pal(i): s = str(i) pal=True for j in range(1,len(s)/2+1): if(s[j-1] != s[-j]): pal=False break return pal pals = [] for i in range(100, 1000): for j in range(100,1000): if(is_pal(i*j)): pals.appe...