text
stringlengths
37
1.41M
""" This program has been written to complete the programming challenge 1 in the HTS. Much of it is self explanatory . Itertools has been included to scramble the scrambled words""" from itertools import * wordfile = open("wordlist.txt","r") dictionary = wordfile.read() words = dictionary.split() def unscrambl...
# num = [1,2] # print(num[2]) # try: # age = int(input("Enter your age")) # print(age) # except ValueError: # print("You didn't input a valid age") # else: # print("Hai") # try: # age = int(input("Enter your age")) # k = 10/age # print(k) # except ValueError as x: # print("Not valid age...
class student(): def __init__(self,x,y,z): self.id = x self.name = y self.age = z def getdetails(self): print(self.id,self.name,self.age) def change_value(self,y): self.name = y # def check_att(self) e1 = student(1,'sara',10) e2 = student(2,'Jose',20) e1.getdetai...
a=(10,20) b=(5,) c=a+b print(c) p=[1,2,3,4,5,6,7,8,9,10] q=(1,2,3,4,5,6,7,8,9,10) p[5]=100 t=q[5] print(t) print(p) # to change the list value # tuple value do not change #s="nikhil" #s[3]=="p" # the tuple in the python is immutable value assigned in the tuple data set cannot be changed #print (s)
x=0 while x<10: x=x+1 if x==3: continue print(x)
r=int(input("enter the range")) l=[] for i in range(r): s=i**2 l.append(s) print(l)
def square(a): return(a*a) # a=int(input("enter the number")) # square(a) s=[2,3,4,5,6,7,8,9,10] print(list(map(square,s)))
import time start_time = time.time() o = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] t = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"] h = ["", "One Hundred", "Two Hundred", "Three Hundred", "Four Hundred", "Five Hundred", "Six Hundred", ...
r = int(input("Enter the no of rows")) c = int(input("Enter the no of columns")) matrix=[] print("Enter the enteries") for i in range(r): a = [] for j in range(c): a.append(int(input())) matrix.append(a) # matrix = [[1,2,3],[2,3,4]] for i in matrix: for j in i: print(j,end=" ") ...
a="Dream high sky is the limit" for i in a.split(): s=len(i) if s%2==0: print(i,"has even number of letters")
n=int(input("Enter the Number")) s=0 while(n>0): b= n%10 s= s*10+b n= n//10 print(s)
def nikhil(): v = float(input("Enter the wind speed: ")) t = float(input("Enter the temp: ")) if(0 <= v <= 4): wci = t print(wci) elif(v >= 45): wci = 1.6 * t - 55 print(wci) else: wci = 91.4 + (91.4 - t)*(0.0203 * v - 0.304 * (v) * 1/2 - 0.474) prin...
a="Betty Bought a butter the butter was bitter so betty bought a better butter which was not bitter" v=[a[-1] for a in a.split() if(len(a)%2==0)] print(v)
import random a=int(input("Enter the Upper Bound")) b=int(input("Enter the Lower Bound")) k=random.randint(a,b) print(k)
a="betty bought a butter the butter was bitter so betty bought a better butter which was not bitter" y=a.split() z={i:y.count(i) for i in y} print(z)
from timeit import default_timer as timer from BubbleSort import * from SelectionSort import * from InsertionSort import * def isEqual(lst1, lst2): if len(lst1) != len(lst2): return False for i in range(0,len(lst2)): if lst1[i] != lst2[i]: return False return True def test(exp...
# Definition for a binary tree node. import copy class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param {TreeNode} root # @return {integer} def sumNumbers(self, root): def aux(node, res, path): ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param {TreeNode} root # @param {integer} sum # @return {boolean} def hasPathSum(self, root, target): def aux(nod...
# 1. 사고 싶은 것 5개를 입력 받아서, 리스트에 넣으세요! (for문 사용!) 전체 프린트 buy = [] for _ in range(5): #index 없이 5번 반복만 할 경우 변수 없어도 됨 # data = input('사고 싶은 것은?? ') buy.append(input('사고 싶은 것은?? ')) print(buy) # 2. wish에 들어갈 입력을 다음과 같이 하나의 스트링으로 입력 받아서 리스트에 넣어보세요. # 입력: 프로그래머,분석가,기획가,마케팅전문가 # 나는 프로그래머가 되고 싶어요! 나는 분석가 되고 싶어요! 나는 기획가가...
num1 = input('숫자를 입력하세요>> ') num2 = input('숫자를 입력하세요>> ') print(int(num1) + int(num2)) print(int(num1) - int(num2)) print(int(num1) * int(num2)) print(int(num1) / int(num2)) print('=======================') name = input('이름을 입력하세요>> ') age = input('나이를 입력하세요>> ') print('출력은 ' + name + '은 ' + age + '세입니다.') if int(...
''' 동적계획법을 사용해 풀었습니다. n x m 배열(board)을 만들고, 배열의 값을 집(1,1)에서 각 위치까지의 최단경로의 경우의 수를 저장하고, 목적지인덱스에 담긴 값(board[n][m])을 반홥했습니다. ''' def is_possible(row, col, board): """ board[row][col]이 웅덩이인지 확인. """ return True if board[row][col] > -1 else False def calc_number_of_case(row, col, board): """ boa...
""" File: classes.py Authors: Bob Wei Date: 6/6/2017 Project Name: 8 Ball Pool Description: A file containing the definitions of various classes that are called upon in main.py """ # imports necessary modules import pygame # ================================================================...
# _*_ coding: UTF-8 _*_ ''' Created on 2017年7月4日 @author: Chenxi ''' # 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 # 程序分析:利用while语句,条件为输入的字符不为'\n'。 import string s = raw_input('input a string:\n') letters = 0 space = 0 digit = 0 others = 0 for c in s: if c.isalpha(): letters += 1 elif c.isspace(): ...
# _*_ coding: UTF-8 _*_ ''' Created on 2017年7月4日 @author: Chenxi ''' # 题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。 # 程序分析:学会分解出每一位数。 x = int(raw_input("请输入一个五位数:\n")) a = x / 10000 b = x % 10000 / 1000 c = x % 1000 / 100 d = x % 100 / 10 e = x % 10 if a != 0: print "5 位数:",e,d,c,b,a elif b != 0: print "4 位数:",e...
# _*_ coding: UTF-8 _*_ ''' Created on 2017年7月4日 @author: Chenxi ''' # 题目:将一个数组逆序输出。 # 程序分析:用第一个与最后一个交换。 if __name__ == '__main__': a = [9,6,5,4,1] N = len(a) print a for i in range(len(a) / 2): a[i], a[N-i-1] = a[N-i-1],a[i] print a
# _*_ coding: UTF-8 _*_ ''' Created on 2017年7月4日 @author: Chenxi ''' # 题目:学习使用auto定义变量的用法。 # 程序分析:没有auto关键字,使用变量作用域来举例吧。 num = 2 def autofunc(): num = 1 print 'internal block num = %d' % num num += 1 for i in range(3): print 'The num = %d' % num num += 1 autofunc()
age = input("How old are you? ") #you can also include a string inside the parantheses of the input function to prompt the user to type the info you need height = input("How tall are you? ") weight = input("How much do you weigh? ") print(f"So, you're {age} old, {height} tall and {weight} heavy.")
from functools import reduce num = [5, 4, 3, 8, 9, 2, 1, 6, 11, 10] print('Python list: ', num) evens = list(filter(lambda x: x%2==0, num)) print('Filter: ', evens) doubles = list(map(lambda x: x*2, evens)) print('Doubles: ', doubles) sum = reduce(lambda x, y: x+y, doubles) print('Sum: ', sum)
class Account: def __init__(self,name,amount): self.name=name self.amount=amount def __str__(self): return "Account owner: " + self.name + "\nAccount balance: " + str(self.amount) def deposit(self,dep): self.amount=self.amount+dep return str(self....
# -*- coding: utf-8 -*- """ Created on Jun 9, 2013 filedesc: @author: serg """ import time time.time() a = {'time': 1, 'name': 'a'} b = {'time': 2, 'name': 'b'} c = {'time': 3, 'name': 'c'} d = {'time': 5, 'name': 'd'} dicts_list = [b, c, d, a] #first.sort(cmp=compare, key=None, reverse=False) #dicts_list.sort(key=...
# -*- coding: utf-8 -*- """ Created on Dec 25, 2013 filedesc: @author: serg """ from timeout import call_with_timeout import time from gevent.timeout import Timeout from gevent import monkey import gevent monkey.patch_all() _time = 3 DEFAULT_TIMEOUT = 5 class _call_with_timeout: def __init__(self, function, t...
class B(): pass class A(): def __init__(self): print 'init' self.b = B() def __getattr__(self, *args, **kwargs): print "__getattr__" a = A() b1 = a.b b2 = a.b print b1 is b2 a1 = A() print a1.b is b1
def strxor(a, b): # xor two strings (trims the longer input) #a = hex(a) #b = hex(b) return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)]) flag = "zenseCTF{0tp_0n1y_0nc3}" #n0w y0u kn0w 0tp 15 0n3 71m3}" print(len(flag)) key = "This is going to be a phrase of length 42" print(len(key)) p1 = "...
e=int(input()) f=1 while(f<6): g=e*f f=f+1 print(g,end=" ")
k=int(input()) if k==0: gh=1 print(gh) elif k>0: sum=1 for k in range(1,k+1): sum=sum*k print(sum)
def square(x): return x**2 numbers = range(10) #map takes a function and iterable, returns a new iterable applying the function on each element squareNum = map(square,numbers) print numbers print squareNum #the above can be achieved by lambda expression lambdaSquare = map(lambda x:x**2,numbers) print lambdaSquar...
dict1 = { "fname":"khaled", } dict1["lname"] = "Hossain" list1 = ["khaled","Mahtab","Anjan"] print dict1.keys() print dict1.values() print dict1.items() print len(dict1)
from datetime import date from datetime import time from datetime import datetime #create a timestamp t = time(11,25,59) print t print t.hour print t.minute print t.second #todays date d = date.today() print d print d.month print d.year print d.day d1 = d.replace(year=2017) print d1 #date and time now now = datetime...
#!/usr/bin/env python import sys def sgn(x): return (x > 0) - (x < 0) def gilbert3d(x, y, z, ax, ay, az, bx, by, bz, cx, cy, cz): """ Generalized Hilbert ('Gilbert') space-filling curve for arbitrary-sized 3D rectangular grids. """ w = abs(ax + ay +...
################################################################################ # 'SNAKEY' GAME ## Adapted by George Deeks from https://gist.github.com/sanchitgangwar/2158089 ## Use ARROW KEYS to play and Esc Key to exit ################################################################################ # Import helper ...
from LinkedList import * def add(headA, headB): dummy = LinkedListNode(-1) curr = dummy carry = 0 while headA != None and headB != None: initVal = headA.val + headB.val + carry carry = initVal // 10 newNode = LinkedListNode(initVal % 10) curr.next = newNode curr...
class LinkedListNode: def __init__(self, val): self.val = val self.next = None def arrayToList(arr): dummy = LinkedListNode(-1) curr = dummy for element in arr: newNode = LinkedListNode(element) curr.next = newNode curr = newNode return dummy.next def pri...
from Tree import * def preorderTraversal(root): if not root: return [] res = [] stack = [] stack.append(root) while stack: top = stack.pop() res.append(top.val) if top.right: stack.append(top.right) if top.left: stack.append(top....
def reverse(s): if s == "": return s return reverse(s[1:]) + s[0] def reverseBetweenParens(s): """ Write a function that reverses characters in (possibly nested) parentheses in the input string. Input strings will always be well-formed with matching ()s. For inputString = "(bar)...
from collections import defaultdict import math def minWindow(s, t): """ Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no s...
from LinkedList import * def deleteNode(node): """ Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. """ node.val = node.next.val node.next = node.next.next def reverseLinkedListIterative(head): """ Reverse a linked list ite...
from collections import defaultdict def group(strs): """ Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] """ mapping = defaultdict(list) ...
def textJustification(words, maxWidth): """ Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line...
#-*- coding: utf-8 -*- """ Reorders CoarseMC output by temperature. Usage example: python reorder_output.py output-*.json The script creates corresponding files sorted-0.json, sorted-1.json, etc. Together they contain the same information as the input files of the script but now a single file contains only the outpu...
import hashlib, string, random def evenify(value1, value2): # adds leading 0's if two string values are not equal diff= len(value1) - len(value2) if(diff < 0): value1 = "0"*(-diff) + value1 if(diff > 0): value2 = "0"*(diff) + value2 return [value1, value2] # returns 'evenified' values a...
""" Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ def ...
""" Given a collection of distinct integers, return all possible permutations. """ def permute(nums): if len(nums) == 1: return [nums] result = [] for i in range(len(nums)): others = nums[:i] + nums[i+1:] other_permutations = permute(others) for permutation in other_perm...
""" Given two binary trees 'original' and 'cloned' and given a reference to a node 'target' in the original tree. The 'cloned' tree is a copy of the 'original' tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to change any of the two trees or the target node and the answer ...
""" Given two arrays of integers nums and index. Your task is to create target array under the following rules: - Initially target array is empty. - From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. - Repeat the previous step until there are no elements to read in...
'''This program receives a folder location that holds one or more image files and creates HTML code that can be copy and pasted into a .html document.''' import os def main(): path = input("Please type the filepath of the image folder. ") if os.path.isdir(path): parent = input("What is the name of t...
#Programa para saber se três retas formam um triangulo. #Treinando também a exibiçao em outras cores lado1 = int(input('Digite o tamanho do primeiro lado de um triangulo: ')) lado2 = int(input('Digite o tamanho do segundo lado de um triangulo: ')) lado3 = int(input('Digite o tamanho do terceiro lado de um triangulo: '...
# Exercise for training repetition structure # Program to know the sum of the odd and multiple by three numbers # Between 0 and 500 (five hundred) sum = 0 for c in range(1, 500+1, 2): if c % 3 == 0: sum = sum + c print(c, 'is divisible by 3') print(sum)
# Exercise to training tuples # Program that returns the vowels of some words inside the tuple words = ('Manuella', 'Samanta', 'Enir', 'Eli') for c in words: print(f'\nThe vowels of word {c} are: ', end='') for x in c: if c.lower() in ('aeiou'): print(c.lower(), end='')
# Exercise to training repetition structure (for) # In this program the user will type name, age and genre of 4 people # And the program will return their middle age, which man is older and how many women are under 20 years old sum_age = 0 older_man_age = 0 older_man_name = '' count_woman = 0 print('Type the data of ...
# Exercise for training lists # Program that you can put the students and your grades grade = [] repository = [] student = [] while True: student.append(input('Type the student name: ')) grade.append(int(input('Type first grade: '))) grade.append(int(input('Type de second grade: '))) student.append(gr...
import random from time import sleep print('='*40) print('Vamos brincar? Vou pensar em um numero, tente adivinhar!!') n1 = int(input('Digite um numero: ')) print('PROCESSANDO ...') sleep(3) n2 = random.randint(0,5) if n1 == n2: print('PARABENS, VC ACERTOU') else: print('VOCE ERROU! O numero era: ', n2)
def readInt(msg): number = input(msg) while not number.isnumeric(): print('ERROR.') number = input(msg) return number # Main Program number = str(readInt('Type a number: ')) print(f'You typed the number {number}')
#Exercise to training repetition structure with break #Program to count and sum numbers under 999 sum = count = 0 while True: number = int(input('Type a number under 999 to sum: ')) if number == 999: break sum += number count += 1 print('You typed {} numbers and the sum is {}'.format(count, su...
from time import sleep def title(txt): print('-'*40) print(f'{txt}'.center(40)) print('-'*40) def save(): title('NEW REGISTRATION') while True: try: name = input('Name: ').strip() age = int(input('Age: ')) file = open("people.txt", "a") fi...
import math n = float(input('Digite um número decimal: ')) print(math.trunc(n))
distancia = int(input('Distancia viagem: ')) preco = 0.50 #50 cents ate 200 km 45 mais longas if distancia > 200: preco = 0.45 print('O preco da sua passagem eh R${:.2f} '.format(distancia*preco))
import socket #importa modulo socket TCP_IP = "192.168.0.21" # endereco IP do servidor TCP_PORTA = 31911 # porta disponibilizada pelo servidor TAMANHO_BUFFER = 1024 # Criacao de socket TCP do cliente cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Conecta ao servidor em IP e porta especifica cli...
from sl_node import Node class SList: def __init__(self): self.head = None def add_to_front(self, val): new_node = Node(val) new_node.next = self.head self.head = new_node return self def print_values(self): runner = self.head while (runner ...
def outer(f): def inner(): result = f() return result ** 2 return inner @outer def num(): return 5 print(num())
# passing positional arguments to decorators def accept_the_arguments(function_to_decorator): def inner_function(*args, **kwargs): print("positional arguments are", args) print("The Keyword arguments are", kwargs) function_to_decorator(*args) return inner_function @accept_the_arguments ...
from typing import List class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: # 1. Sort array # 2. Linear search through once to find the min difference comparing adjacent elements # 3. A second linear search finding all adjacent elements with the min dif...
""" Approach 1: - Iterate through list to find shortest string length and use for index boundaries. - For i in range(0, min length in list): get ith char of first string for(all strings): compare ith value to the above value: build stir...
from collections import defaultdict, deque, namedtuple class Vertex(object): """ Defines a single vertex and its neighbors. """ def __init__(self, vertex_id): """ Initialize a vertex and its neighbors dictionary. Parameters: vertex_id (string): A unique identifier to i...
# -*- coding: utf-8 -*- """ 参考链接: http://www.cnblogs.com/fnng/p/3670789.html http://www.cnblogs.com/fnng/p/3691053.html """ # --单线程例子-- # # from time import sleep, ctime, time # # # def listenMusic(func): # 听5次歌,每次用2秒 # for i in range(5): # print('我正在听 %s, 现在的时间是 %s' % (func, ctime())) # sleep(2) ...
# Unit 3 Python Assignment 1 # Assignment 1 for Python: https://education.launchcode.org/data-analysis/assignments/scrabble-scorer.html # Julie (she/her) 4:46 PM # @channel Starter code for Scrabble Scorer: https://github.com/LaunchCodeEducation/scrabble-scorer-python # inspired by https://exercism.io/tracks/javasc...
''' This program is a student management system, allowing users to add student records and run reports.''' from guizero import App class Student: ''' The student class has a name, age, phone number, gender and a list classes All students are automatically set as enrolled when instantiated. Each student bel...
import sys digits = sys.argv[1] digits=str(digits) i, j = 0, 0 for letter in digits: if not letter.isdigit(): print(f"Please correct input: {letter}") j=1 break i+=int(letter) if j==0: print(i)
f = open('filename') text_modes=['r','w','a','r+'] f=open('filename','w') f.write('New text') f.close() #r+ = read write f.read() #get to the beginning of the file f.seek(0) f.readline() #read 1 line f.readlines() #read all lines, separated #context manager with open('filename') as...
#Beginners questions on 2d arrays rows = int(input("Enter rows")) cols = int(input("enter cols")) mat = [] for i in range(rows): a=[] for j in range(cols): a.append(int(input())) mat.append(a) print(mat) flag = True for i in range(rows): for j in range(i+1,cols): p...
#https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem from collections import Counter string=Counter(input()) string=Counter(string.values()) print(string) if len(string.keys())==1: print("YES") elif len(string.keys())==2: key1,key2=string.keys() print(key1,key2) if stri...
#PROBLEM LINK : https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/ #https://leetcode.com/problems/maximum-subarray/ from sys import maxsize def maxSubArraySum(arr,n): max_value = -maxsize max_value_end = 0 for i in range(0, n): max_value_end = max_value_en...
from Problem3 import is_prime __author__ = 'erlafont' def find_all_x_prime_numbers(number_of_prime): primes = [] index = 2 while(len(primes) < number_of_prime): if is_prime(index): primes.append(index) index += 1 return primes if __name__ == '__main__': print(__fil...
import math __author__ = 'erlafont' def is_prime(number): for index in range(2,math.ceil(math.sqrt(number))+1): if number % index == 0 and number != index: return False return True def find_all_prime_factors(number): list_of_primes = [] for index in range(2,math.ceil(math.sqrt(nu...
""" Performs FAST corner detection without machine generated code. Reference: - http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_fast/py_fast.html """ """ ***** Begin NumPy and OpenCV functions. ****** """ def shape(array): """ Returns a list of 2D array dimensions """ rows = ...
class Flight(object): flight_count = 0 def __init__(self, Flight_Number, From, To, Date): self.Flight_Number = Flight_Number self.From_Loc = From self.To_Loc = To self.Date = Date Flight.flight_count += 1 def getFlight(self): #print("Details of flight are: ",...
# This Python file uses the following encoding: utf-8 import os, sys, math nota1 = float (input("Digite a nota 01 : ")) nota2 = float (input("Digite a nota 02 : ")) media = (nota1 + nota2) / 2 if media <= 4 : conceito = 'E' elif media <= 6 : conceito = 'D' elif media <= 7.5 : conceito = 'C' elif media <= ...
''' 读入10个学生成绩,定义一个函数 计算成绩平均数,最高分,最低分 ''' def avg(ls): sum = 0 for j in ls: sum += j print("平均成绩{},最高分{},最低分{}".format(sum/10,max(ls),min(ls))) i = 0 list1 = [] while i < 10: score = int(input("请输入10个成绩(0-100):")) if 0 <= score <= 100: list1.append(score) else: continue i += 1 avg(list1)
''' 用面向对象实现学生管理系统,实现增删改查 ''' class Scourse(): '''学生科目成绩管理类''' #student = dict(student) subject = dict() def __init__(self,subitem): #定义字典属性接收科目和成绩 for i in subitem.items(): Scourse.subject[i[0]] = i[1] def add_sub(self,sub,val): #增加科目和成绩 for i in self.subject.keys(): if i == sub: return 'already ex...
import unittest import math def find_rotation_point(words): # if('ptolemaic' < 'xenoepist'): # print('yo') # Find the rotation point in the list l = 0 r = len(words)-1 first = words[0] while l <= r: # print(words[l:r]) print (words[l:r+1]) if words[l] <= words[r...
import unittest class Stack(object): def __init__(self): """Initialize an empty stack""" self.items = [] def push(self, item): """Push new item to stack""" self.items.append(item) def pop(self): """Remove and return last item""" # If the stack is empty, re...
""" Module to teach implementation of a feed forward neural network from scratch (no Deep learning libraries for Deep) """ import numpy as np class NeuralNetwork(object): """ Fully connected 2 hidden layer Deep neural network, with log loss and SGD (we can implement something more fancy...
# Given an integral number N.The task is to find the count of digits present in this number. #Solution 1 : TC- O(n) num = 12345 count = 0 while(num != 0): num = int(num/10) count += 1 print(count) #Solution 2 : TC - O(1)
#translates value from left ---> right def translate(value, leftMin, leftMax, rightMin, rightMax): # Figure out how 'wide' each range is leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin # Convert the left range into a 0-1 range (float) valueScaled = float(value - leftMin) / float(leftSpa...
import time import pandas as pd import numpy as np from datetime import datetime from datetime import timedelta CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, ...
import numpy as np class sigmoid_neuron(): def __init__(self, n, w=None): """Constructor method. Parameters ---------- n : int The number of synaptic connections, a vector. """ if w is not None: weights = np.loadtxt(w) s...
""" Created on Mon Apr 8 12:40:43 2019 @author: bdbaus """ #number of possible tiles n=50 red=2 green=3 blue=4 def possible(m, n): #r is length of tile (2,3,4) and n is N slots possible = [1] + [0]*(n) #creates list of n + 1 length [1,0,0,0,0...n] for x in range(1, len(possible)):...
""" Created on Mon Mar 25 12:10:16 2019 @author: bdbaus """ #ask for Zm m=11 Flist = [] #a * b = 1 for z in range(1,m): for a in range(1,m): if (z*a)%m==1: Flist.append([z,a]) #continue print("The ",len(Flist)-1," multiplicative inverses in Z",m," (exclud...
# importing required libraries import numpy as np import networkx as nx import math ############## Dijkstra Algorithm ########## def Dijkstra(cities_dict): i = 0 stop_condtion = True current_city = 0 # to keep track of cities we had visited visited = [] # to keep track of cities...
""" Utility functions for visualization, typically anything shared among modules """ import csv from Bio import Entrez Entrez.email = 'ballardt@knights.ucf.edu' def parse_gra(filename, delimiter='\t'): """ Parse a gra file containing taxids, relative abundances, and errors Args: filename (strin...
# Student Number 400422179, Xiaoyu Wu # check two different traffic light to see if the requirement is met # which needs two lights to be different colors. class MainTrafficLight(): trafficLight = "green" time = 0 def set_traffic_light(self, color): return NotImplemented def check_traffic_lig...