text
stringlengths
37
1.41M
#!python2 """ (C) Michael Kane 2017 Student No: C14402048 Course: DT211C Date: 26/10/2017 Title: Edge and gradient detection. Introduction: Step-by-step: Give an overview: Comment on experiments: References: """ # import the necessary packages: import numpy as np import cv2 from matplotlib i...
""" Name of Activity: Module 3 Live Session Assignment: Class Inheritance Name: Nathan England Computing ID: nle4bz Partner: John Carpenter Partner Computing ID: jmc7dt """ class Student: # fields: name, id, grades(a list) #Local variable #grades = [] # initially empty def __init__(self, nam...
import functools as ft import numpy as np fib = [0,1] array = np.array([]) def fib(integer): if integer < 0: print("Not a valid input") elif integer <= len(fib): return fib[integer - 1] else: temp_fibonacci =
class BinarySearch(list): def __init__(self, first, a, b): """Variables a,b are respectivery the length and step of the list we're creating, when subclassing list""" super(BinarySearch, self).__init__(self) """i.e., Inherit to BinarySearch the arguments of the parent class, list""" array_ = [num for nu...
""" Homework 2 >Problem 4 Author: Derrick Unger Date: 1/24/20 CSC232 Winter 2020 """ # Initialize Variables i = 0 # Array Counter inputSum = 0 print("\n=======================================") print(" Compound Interest Calculator\n") print("Input instructions:") print(" -Input interest rate in percent for...
""" Homework 5 >Problem 8 Author: Derrick Unger Date: 2/14/20 CSC232 Winter 2020 """ while True: try: print("\nInstructions: ") print("Inputs must be a string of digits, separated by a space.") print("Ex: 12345 67890\n") s1, s2 = input("\nInput two numeric strings of digits: ").spl...
""" Homework 7 >Problem 4 Author: Derrick Unger Date: 2/29/20 CSC232 Winter 2020 """ # User Input code = 0 while code == 0: try: puzzle = input("\nEnter puzzle: ").upper() whiteList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ-& " print("\nPuzzle: " + puzzle) # Check input validation for ...
""" Homework 3 >Problem 2 Author: Derrick Unger Date: 1/31/20 CSC232 Winter 2020 """ code, i = 0, 0 mylist = [] # Define your list print("\n=============================================") while code == 0: try: userInput = input("Enter a number or type 'EXIT' or 'exit' to stop: ") if userInput.upp...
""" Homework 5 >Problem 3 Author: Derrick Unger Date: 2/14/20 CSC232 Winter 2020 """ import numpy as np np.set_printoptions(formatter={'float_kind': lambda value: format(value, '8.3f'), 'int_kind': lambda value: format(value, '10d')}) print("\nINSTRUCTIONS") print("-"*len("INSTRUCTIONS...
""" Test 6 >Problem 1 Author: Derrick Unger Date: 3/20/20 CSC232 Winter 2020 """ print("\n" + "="*40) print("PROBLEM 1") print("Input format: last,first 123-45-6789 23.51") print("Notice, no space between first and last as shown in problem statement") print("To exit, enter 'exit ' without quotes and with two spaces ...
import matplotlib.pyplot as plt import numpy as np from sklearn import datasets,linear_model from sklearn.metrics import mean_squared_error # load the data of diabetes from datasets diabetes = datasets.load_diabetes() # load the data of index 2 of diabetes to diabetes_X diabetes_X = diabetes.data[:,np.newaxis,2] # p...
import turtle def draw_triangle(): window=turtle.Screen(); window.bgcolor("red"); brad =turtle.Turtle(); for i in range(1,3): brad.forward(100); brad.right(60) brad.right(90) brad.forward(170) sid=turtle.Turtle(); sid.shape("turtle"); sid.color('yellow'); ...
import math li = {} def factorial(n): if(n==0): return 1 else: fact = n*factorial(n-1) li=fact return fact print(factorial(900)) print(li[3])
class Point: """ 表示一个点 """ def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): if self.x == other.x and self.y == other.y: return True return False def __str__(self): return "x:" + str(self.x) + ",y:" + str(self.y) cla...
# Author: Andrew Davidson # Date: 04/10/2019 # # This application tracks baseball players batting average using parallel lists. # The user can enter 12 player names, which are then populated into a list. # The user can switch between name entry, stat entry, and summary display during runtime. name entry allows # t...
# Enter your code here. Read input from STDIN. Print output to STDOUT import math def bi_dist(x, n, p): b = (math.factorial(n)/(math.factorial(x)*math.factorial(n-x)))*(p**x)*((1-p)**(n-x)) return(b) b1,b2, p, n = 0, 0, 12/100, 10 for i in range(3): b1 += bi_dist(i, n, p) for i in range(2,n+...
# Enter your code here. Read input from STDIN. Print output to STDOUT mean_of_A = 0.88 mean_of_B = 1.55 result_of_A = 160 + 40 * (mean_of_A + mean_of_A**2) result_of_B = 128 + 40 * (mean_of_B + mean_of_B**2) print("{:.3f}".format(result_of_A)) print("{:.3f}".format(result_of_B))
print("Calculadora de fuerza de atraccion") print('Inserta el valor sin el 10 de la primera masa') MassOne = float(input()) print('Inserta el valor sin el 10 de la segunda masa') MassTwo = float(input()) print('Inserta el exponente de la primera masa') MassOne_Exponent = int(input()) print('Inserta el exponente de la s...
#!usr/bin/env python3 import re from re import match, split class genbank_parser: ''' Use this class to parse the genbank file. Parsing the genbank file follows the order of: 1) Accession - 6-8 character string containing the accession code 2) Features - strings which represent the ge...
# # @lc app=leetcode id=199 lang=python3 # # [199] Binary Tree Right Side View # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def right...
# # @lc app=leetcode id=146 lang=python3 # # [146] LRU Cache # from collections import OrderedDict # https://leetcode.com/problems/lru-cache/discuss/45926/Python-Dict-+-Double-LinkedList/45368 # @lc code=start class LRUCache: def __init__(self, capacity: int): self.vals = {} # { key: (val, Node) } ...
# # @lc app=leetcode id=5 lang=python3 # # [5] Longest Palindromic Substring # # @lc code=start class Solution: def longestPalindrome(self, s: str) -> str: def findPalindromeFromPivot(left, right, s): if (s == None): return 0 if left > right: return 0...
# # @lc app=leetcode id=19 lang=python3 # # [19] Remove Nth Node From End of List # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: i...
# # @lc app=leetcode id=141 lang=python3 # # [141] Linked List Cycle # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: # situations: 1) duplica...
# # @lc app=leetcode id=101 lang=python3 # # [101] Symmetric Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, ...
# # @lc app=leetcode id=142 lang=python3 # # [142] Linked List Cycle II # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: ''' Ac...
# # @lc app=leetcode id=34 lang=python3 # # [34] Find First and Last Position of Element in Sorted Array # # @lc code=start class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: # brute force o(n) ''' start = -1 end = -1 ind = 0 f...
# # @lc app=leetcode id=112 lang=python3 # # [112] Path Sum # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def hasPathSum(self, root: T...
# Name: # Date: """ proj04 Asks the user for a string and prints out whether or not the string is a palindrome. """ # raw_input ("lets play a game of hangman, press RETURN to start") # # raw_input ("guess a letter for the word") raw_input ("press RETURN to see if the word is a palindrome") str = "racecar" lst ...
listamulheres = [] #Definido uma classe mãe class mae: def __init__(self,nome,idade,estadocivil,quantfilhos): self.nome = nome self.idade=idade self.estadocivil = estadocivil self.quantfilhos = quantfilhos def cuidarfilhos(self): return '{} Cuidando do filho'.format(se...
# Linguagem de Programação II # Atividade Contínua 02 - Classes e Herança # # e-mail: ermirio.bonfim@aluno.faculdadeimpacta.com.br """ Implementar aqui as cinco classes filhas de Mamifero ou Reptil, de acordo com o caso, conforme dado no diagrama apresentado no padrão UML. Os atributos específicos de cada classe fil...
def recursive_dfs(a): if a not in visited: visited.append(a) for i in graph[a]: if i not in visited: recursive_dfs(i) return visited visited = [] graph = {'A': set(['B', 'C', 'E']), 'B': set(['A', 'D', 'F']), 'C': set(['A', 'G']), 'D': set(['B']), ...
​ #### - 미로1 ​ >일종의 그래프이므로 탐색을 위해 ***DFS 이용***. 0 or 1이므로 결정 문제 ​ ```python ''' 16 x 16 ''' def maze(y, x): global flag dx = [0, 0, -1, 1] dy = [-1, 1, 0, 0] ​ # data[y][x] = 9 #방문표시 ## 사실 한 번만 지나가면 되므로 data 자체에 표시해도 된다. visit[y][x] = 1 for i in range(4): ny = y + dy[i] nx = x +...
array = [1, 5, 2, 6, 3, 7, 4] commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]] def solution(array, commands): answer = [] for command in commands: i, j, k = command answer.append(sorted(array[i-1:j])) return answer print(solution(array, commands)) # def solution(array, commands): # ans = ...
#!/usr/bin/env python # coding=utf-8 """ A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. For example, the above binary watch reads "3:25". Given a non-negat...
#!/usr/bin/env python3 # Create a timer import time run = input("Start? >") seconds = 0 if run == "yes": while seconds !=6: print(">",seconds) time.sleep(1) # tempo de espera seconds+=1 print('Finish')
# coding=UTF-8 def computeResult(x, y, op): result = "" if op == "+": result = x + y elif op == "-": result = x - y elif op == "*": result = x * y elif op == "/": result = x / y elif op == "%": result = x % y elif op == "**": result = x ** y ...
import time def fibonacci (previous, current): if current == 0: return 1 return previous + current previous = 0 current = 0 for i in range(10): previous, current = current, fibonacci(previous, current) print (current) time.sleep(0.5)
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): print("Hello! Let\'s explore some US cities bikeshare data!\n") while True: city = input("Wo...
def selamla(isim ="isimsiz"): print("merhaba", isim) def topla(*vals): topla = 0 for val in vals: topla = topla + val return topla ciftMi = lambda say : ((say % 2) == 0)
class nuqta: def __init__(self, x:int, y:int) -> None: self.x = x self.y = y #bu metod nuqtadan (x, y) nuqtagacha bo'lgan masofani hisoblaydi def gacha_masofa(self, x, y): a=((self.x - x)**2+(self.y - y)**2)**(1/2) return a class planeta: def __init__(self...
#library 추가 import time import RPi.GPIO as GPIO s2 = 23 # Raspberry Pi Pin 23 s3 = 24 # Raspberry Pi Pin 24 out = 25 # Raspberry Pi Pin 25 NUM_CYCLES = 10 def read_value(a2, a3): GPIO.output(s2, a2) GPIO.output(s3, a3) # 센서를 조정할 시간을 준다 time.sleep(0.3) # 전체주기 웨이팅 #GPIO.wait_for_edge(...
import argparse import os import pickle import sys from tictactoe.agent import Qlearner, SARSAlearner from tictactoe.teacher import Teacher from tictactoe.game import Game class GameLearning(object): """ A class that holds the state of the learning process. Learning agents are created/loaded here, and a ...
from urllib.request import urlopen, hashlib sha1hash = input("> Please insert the SHA-1 hash here.\n>") common_passwords_list_url = input("> Please, also, provide the URL of the word list that you would like me to check.\n>") common_passwords_list = urlopen(common_passwords_list_url).read() common_passwords_list = s...
import pandas as pd import numpy as np d = {"a": [1, 2, 3], "c": [4, 5, 6]} a = pd.DataFrame(data=d) b = pd.DataFrame(data={"a": [1, 2, 3], "c": [4, 2, 3]}) c = pd.DataFrame(data={"a": [1, 2, 3], "c": [5, 1, 3]}) d = pd.DataFrame(data={"a": [1, 2, 3], "c": [5, 1, 3]}) rs = a.merge(b, on="a", suffixes=("_a", "_b")).m...
from urllib.request import urlopen import json import datetime import csv import time import pandas as pd # input group name # input access_token # group_name is the name of the group as it appears in the url # access_token can be attained from Graph API Explorer def getGroupID(group_name, access_token): base =...
#!/usr/bin/env python # -*- coding: utf-8 -*- '''get the size of a file''' import os def get_file_size(file_path): size = os.path.getsize(file_path) print('Size of this file is {} byte'.format(size)) if __name__ == '__main__': file_path = 'C:/Users/Bairong/Desktop/graph.txt' get_file_size(file_path...
print("Welcome to the login!") name = input("Enter user name:") password = input("Enter user password:") def login(user_name,user_pass): un = user_name.lower() up = user_pass.lower() account = (un, up) login_msg = ("You are now logged in as %s!" % name) if un.lower() in account: print(login...
def finger(landmark): x = 0 y = 1 thumbFinger = False firstFinger = False secondFinger = False thirdFinger = False fourthFinger = False if landmark[9][y] < landmark[0][y]: Hand_direction_y = 'up' else: Hand_direction_y = 'down' landmark_point = landmark[2][x] ...
"""Estimate the future state of pedestrian motion useing a Kalman Filter. This file contains the class, KalmanFilter, used to store the state of the modeled system to estimate the state in a future timestep. The Kalman Filter is applied as part of the project to the modelling of human motion, relating the predicted po...
import os import csv # identify location of source data sourcedirectory = 'input_data' file1 = 'election_data_1.csv' file2 = 'election_data_2.csv' # wrap files in list for iteration filelist = [file1, file2] # for exploration, shown(n) prints n number of rows in each file def shown(n): # iterate over files ...
#GUI that allows user to toggle Windows Key functionality import keyboard from tkinter import * window = Tk() window.title("NoWinKey") winBlocked = False def disable(): global winBlocked winBlocked = True keyboard.block_key('win') enable.configure(state=ACTIVE) disable.configure(state=DISABLED)...
class Node: """ A node in singly linked list """ def __init__(self, data=None, next=None): self.data = data self.next = next def __repr__(self): return repr(self.data) class SinglyLinkedList: def __init__(self): """ Creates a new singly linked l...
#!/usr/bin/python # GOOGLE VOICE NUMBER ----------- 734-506-8603 ----------- from googlevoice import Voice from googlevoice.util import input import sys def login(voice): username, password = "eecs498.vois@gmail.com", "umichvois" print("Logging in...") client = voice.login(username, password) retur...
str=input("enter any string of choice").split() str.sort() print(str) str2=[] for i in str: if i not in str2: str2.append(i) for i in range(0,len(str2)): print(f'{str2[i]} : {str.count(str2[i])}')
username=input("enter your username to register-->") u,l,n,s=0,0,0,0 while True: password=input("enter your password to register-->") if(len(password)>=8 and len(password)<16): for char in password: if (char.islower()): l+=1 elif (char.isupper()): u+=1 elif (char.isdigit())...
from tabulate import tabulate class Teacher: quizapp = [] score = [] def __init__(self,teacher_name,question,options,correct_answer): self.teacher_name=teacher_name self.question=question self.options=options self.correct_answer=correct_answer def question_answer(obj,i): """displays the...
''' check for map list ''' import time from functools import wraps def time_fun(method): ''' @brief decorator to compute execution time of a function. ''' @wraps(method) def wrap_timed(*args, **kw): ''' @brief compute time elapsed while executing @param *args argumen...
''' Worker threads sample code ''' import threading import time def worker(worker_name, timing): ''' @brief a function that does something ''' for _ in range(10): print(worker_name) time.sleep(timing) if __name__ == '__main__': TH1 = threading.Thread(target=worker, args=('TH1', 0...
import numpy as np import math import matplotlib.pyplot as plt train_dat = np.genfromtxt('Wage_dataset.csv', delimiter=',') train_data = np.array(train_dat) year =train_data[0:2250,0] age = train_data[0:2250,1] edu = train_data[0:2250,4] wage= train_data[0:2250,10] yeart =train_data[2250:3000,0] aget = train_data[2250:...
#coding=utf-8 #自定 def testfunction(x): return -x a=testfunction(2919) print(a) #自定义函数2 def function2(numbers): a=0 for n in numbers: a=a+n*n return a b=function2([1,2,3,4]) print(b) #关键字参数,**代表可以省略的参数 def guanjianzifunction(name,age,**height): print("name",name,"age",age,"other",height) guanjianzifuncti...
#coding=utf-8 #遍历数组进行打印 newArray=["wuhao","ligang","micheal"]; for name in newArray: print(name); #简单的进行计算 a=0; for x in [1,2,3,4,5,6,7,8,9,10]: a+=x; print(a); #简单的求和运算 b=0; #range(101)代表的意思是[0,1,2,3.......100]; #range()函数可以生成整数数列 for x in range(101): b+=x; print(b); newsum=0; n=0; while n<100: newsum+=n;...
# coding: utf-8 from collections import OrderedDict def first_not_not_repeating_number(s): hash_map = OrderedDict() for ch in s: cnt_num = hash_map.get(ch, 0) hash_map[ch] = cnt_num + 1 for k, v in hash_map.iteritems(): if v == 1: return k return None if __nam...
# coding: utf-8 def sort_array_for_min_number(arr): """ :param arr: 数组 :return: int """ length = len(arr) if length == 1: return arr[0] arr = map(str, arr) arr.sort(compare) return ''.join(arr) def compare(a, b): len_a, len_b = len(a), len(b) if len_a < len_b:...
# coding: utf-8 def decode_string(s): res = '' idx = 0 length = len(s) while idx < length: ch = s[idx] if ch.isdigit(): i = idx + 1 while s[i].isdigit(): i += 1 num = int(s[idx:i]) if s[-1] == ']': inner_s...
# coding: utf-8 def greatest_sum_of_subarray(arr): res, tmp = float('-inf'), float('-inf') for n in arr: if tmp < 0: tmp = n else: tmp += n if tmp > res: res = tmp return res if __name__ == "__main__": arr = [1, -2, 3, 10, -4, 7, 2,...
# coding: utf-8 def duplicate(nums): length = len(nums) for i in xrange(length): while nums[i] != i: if nums[nums[i]] == nums[i]: return nums[i] a, b = i, nums[i] nums[a], nums[b] = nums[b], nums[a] return -1 if __name__ == '__main__': pr...
from keras.datasets import mnist # standard dataset of hand drawn numbers - digit recognition import matplotlib.pyplot as plt import keras from keras.layers import Input, Dense, Convolution2D, MaxPooling2D, Flatten import numpy as np (x_train, y_train), (x_test,y_test) = mnist.load_data() x_train = x_train[:10000, :] y...
import requests class Api: """ This is a python class to extract data from different API's in JSON format and store it in files. The different functions are used for extracting data using Non-GMO HTTP library for python known as Requests. Mainly consists the following variables: payload - a...
# # Challenge Description: # # Credits: This challenge appeared in the Facebook Hacker Cup 2011. # # A double-square number is an integer X which can be expressed # as the sum of two perfect squares. For example, 10 is a double-square because 10 = 3^2 + 1^2. # Your task in this problem is, given X, determine the numb...
# # Challenge Description: # # You are given a sorted array of positive integers and a number 'X'. # Print out all pairs of numbers whose sum is equal to X. # Print out only unique pairs and the pairs should be in ascending order # # Input sample: # Your program should accept as its first argument a filename. # Thi...
""" Module for graph-based classes """ from __future__ import annotations from typing import Callable import torch import heat as ht from heat.core.dndarray import DNDarray class Laplacian: """ Graph Laplacian from a dataset Parameters ---------- similarity : Callable Metric function tha...
import sys symbols = ['', ' ', ',', '!', '?', '.', '-', ':'] sentence = sys.argv[1] # print(sentence) sentence = sentence.split(' ') sentence = list(set(sentence)) # print(sentence) sentence.sort() # print(sentence) for i in symbols: try: i sentence.remove(i) # print(i) except: c...
def genPrimes(): number = 2 prime_list = [2] yield number while True: continue_while = False number += 1 for divisor in prime_list: if number % divisor == 0: continue_while = True break if continue_while: continue ...
""" 1. Two Sum Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Inp...
""" 1304. Find N Unique Integers Sum up to Zero Given an integer n, return any array containing n unique integers such that they add up to 0. Example 1: Input: n = 5 Output: [-7,-1,1,3,4] Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. Example 2: Input: n = 3 Output: [-1,0,1] Example 3: ...
""" 23. Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0,...
""" 18. 4Sum Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Notice that the solution set must not contain duplicate quadruplets. Example 1: Inp...
import random # represents a square in the board. class Square: def __init__(self, is_black, piece, board, x, y): self.isBlack = is_black self.piece = piece # 1 is p1, 2 is p2, 3 is p1king, 4 is p2king, 0 is empty self.board = board self.x = x self.y = y self.jump_...
# TODO from sys import argv, exit import csv from cs50 import SQL db = SQL("sqlite:///students.db") if len(argv) != 2 : print("CSV file not provided") exit(1) variableArg = argv[1] myResult = db.execute("SELECT * FROM students WHERE house = (?) ORDER BY last ASC, first ASC", variableArg) for result in myRes...
# <2021>, by ISB Institute of Data Science # Contributors: Dr. Shruti Mantri, Gokul S Kumar and Vishal Sriram # Faculty Mentors: Dr. Manish Gangwar and Dr. Madhu Vishwanathan # Affiliation: Indian School of Business # Script for removing the duplicate entries from the downloaded addresses. import pandas as pd import ...
#!/usr/bin/python3 """ Module Docstring """ __author__ = "Dinesh Tumu" __version__ = "0.1.0" __license__ = "MIT" # imports # init variables # define basic function def function_1(): print("Printed from function_1()\n") def function_2(): print("Printed from function_2()\n") def function_3(): print...
#!/usr/bin/python3 import unittest def Descending_Order(num): num_list = [] str_num = str(num) # To convert string into list of chars for i in range(len(str_num)): num_list.append(str_num[i]) # sort the list and convert it back to string sorted_str = ''.join(sorted(num_list, reverse=Tr...
def choose_level(): choise = int(input("""Выберите уровень: 1 - 1-й уровень 2 - 2-й уровень 0 - Выйти""")) if choise not in (1, 2, 0): return None else: return choise
from tkinter import * # Create an empty Tkinter window window=Tk() # def km_to_miles(): # miles=int(e1_value.get())*1.6 # t1.insert(END, (f'{miles} miles')) def kg_converter(): # Get user value from input box kg = int(e1_value.get()) # converts user value to various units grams = kg*1000 ...
## Multiples # Part I for odd in range(1, 1001,2): print odd # Part II for multiples in range(5, 1000001, 5): print multiples ## Sum List a = [1, 2, 5, 10, 255, 3] print sum(a) ## Average List b = [1, 2, 5, 10, 255, 3] x= sum(b)/len(b) print x
import sqlite3 con = sqlite3.connect('MFM.db') print("Database connected....") cur=con.cursor() cur.execute("INSERT INTO My_Favourite_Movies(movie_name,dor,actor_name,actress_name,director_name) VALUES('3idiots',2009,'Amirkhan','Kareena Kapoor','Rajkumar Hirani')") cur.execute("INSERT INTO My_Favourite_Movies(movi...
#!/usr/local/bin/python3 import datetime from enum import Enum import locale locale.setlocale(locale.LC_ALL, '') class Loan: class PaymentFrequency(Enum): monthly = 1 biweekly = 2 weekly = 3 def __init__(self, name, starting_balance, interest_rate, date_disbursed): self.name = ...
def finiteMult(a, b): aString = '{0:08b}'.format(a) bString = '{0:08b}'.format(b) p = 0 for x in range(0, 8): if(bString[-1] == '1'): p = p ^ a b = b >> 1 carry = (aString[0] == '1') a = (a << 1)%256 if(carry): a = a ^ 27 aString =...
num = [1, 2, 3] print(num + [4, 5, 6]) print(num * 3)
i = 0 while 1==1: print(i) i = i + 1 if i >= 5: print("break statement") break print("end")
#encoding: utf-8 print "\n" print "+ FUNCIÓN REDUCE \n" print "++ Reducir una lista a un solo elemento." print "++ Recorre y junta elementos de par en par." print "\n" s = ("H", "o", "l", "a", "_", "m", "u", "n", "d", "o") l = [1,2,3,4,5] def concatenar(a,b): return a+b def suma(a,b): return a+b sr = reduce(con...
#encoding: utf-8 print "\n" print "+ ARCHIVOS\n" print "++ Sin pasar parámetor, por defecto, modo lectura (r)." print "++ Escritura. Si no existe, lo crea, si no lo pisa. (w)." print "++ Añadir, solo se puede escribir en él. Se agrega al final y debe existir. (a)." print "++ Leer y escribir. Debe existir. (r+)." print...
#encoding: utf-8 print "\n" print "+ FUNCIÓN FILTER \n" print "++ Recibe una función y una lista e itera sobre cada uno de los elementos." print "++ PYTHON 3 SE LLAMA COMPRESIÓN DE LISTAS." print "\n" def filtro(elem): return (elem > 0) def filtro2(elem): return (elem == "o") lista = [1,-3,2,-7,-8,10] s = "hola ...
#encoding: utf-8 print "\n" print "+ CLASES DECORADORES\n" print "++ " print "\n" class Decorador(object): """Mi clase decoradora""" def __init__(self, funcion): self.funcion = funcion def __call__(self,*args,**kwargs): print "Functión ejecutada ", self.funcion.__name__ self.funcion(*args,**kwargs) @Decor...
from math import sqrt def problem10(): # based on the Sieve of Eratosthenes numberList = [True] * 2000000 primesSum = 0 numberList[0] = numberList[1] = False for (i, prime) in enumerate(numberList): if prime: primesSum += i if i <= sqrt(2000000): ...
import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, cohen_kappa_score from keras.models import Sequential from k...
# This is a collection of work snippets from the chapter from typing import NoReturn, Text from textblob import TextBlob """Textblob""" text = 'Today is a beautiful day. Tomorrow looks like bad weather.' blob = TextBlob(text) print(blob.__dict__) """Tokenizing""" # sentences feature breaks apart sentences via the...
from __future__ import print_function from operator import add from pyspark.sql import SparkSession if __name__ == "__main__": # create a SparkSession spark = SparkSession\ .builder\ .appName("PythonWordCount")\ .getOrCreate() # read the input file directly in the same Swift conta...
import sqlite3 import random ### First, initialize a connection db_name = "localEats.db" connection = sqlite3.connect(db_name) cur = connection.cursor() def validTable(name): # This function checks to make sure a user input table name is actually there if(name=="alert" or name=="driver" or name=="m...