python Python.Math.Algebra

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python.Math.Algebra相关的知识,希望对你有一定的参考价值。

# When parsing positive / unsigned integers you can use:
>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False


######################################################
# benchmark solutions

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
    
# Then iterate over the function list.
funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)
        
#############################################################
from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()
    
    
#######################
# Check if complex or float

def is_number(s):
    try:
        float(s) # for int, long and float
    except ValueError:
        try:
            complex(s) # for complex
        except ValueError:
            return False



#######################################
# Check for various types
# x.isdigit() works well for checking if x is an integer.
# x.replace('-','').isdigit() works well for checking if x is a negative.(Check - in first position)
# x.replace('.','').isdigit() works well for checking if x is a decimal.
# x.replace(':','').isdigit() works well for checking if x is a ratio.
# x.replace('/','',1).isdigit() works well for checking if x is a fraction
Contents:
  
  1. factors                = Calculates factorilization of number
  2. gcd                    = Calculates greatest common divisor (Iterative/Recursive)
  3. lcm                    = Calculates least common multiple 
  4. square_root            = Calculates square root
  5. full_euclid            = Calculates euclid relation
  6. is_prime               = Calculates whether a number is prime or not
  7. binomial_coefficient   = Calculates Binomial Coefficient of two numbers
  8. find_last_index        = Finds index of element so that List[element] <= bound
  9. prime factorization    = Finds all prime factors of a number and appends to list
  10. fibonacci_numbers     = Prints / Returns all fibonacci numbers up to n
  11.fibo_sum_series        = Calculate the sum of the first n elements of fibonacci
  12.biggest_number         = Returns the biggest number out of all provided
  13.smallest_number        = Returns the smallest number out of all provided
  14.distancefromzero       = Returns the absolute value out of all provided
  15.normalizenumbers       = Normalize all numbers in list
  16.geometric_series       = Fill an array with geometric series up to n
  17.geo_series_sum         = Calculate the sum of first n elements of geometric list
  18.harmonic_series        = Fill an array with harmonic series up to n
  19.harm_series_sum        = Calculate the sum of first n elements of harmonic series
  20.prime_generate         = Generate primes in various ways
  21.apply_to_array         = Apply calculation to all array elements or Boolean
  22.mean_value             = Calculates the mean value of list elements
  23.stdev                  = Calculates the standard deviation of list elements
  24.quotientremainder.py   = Calculates a tuple of quotient / remainder for two numbers
  25.Compoundinterest.py    = Calculates compound interest
  26.Permutations.py        = Many forms of combinatronics and permutations
  27.Checkifdigitfloat.py   = Check if a string is a float or digit
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 09:49:49 2017

@author: P.Doulgeridis
"""

import itertools

def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        print("Combination length required longer than populace")
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

            
            
def permutations2(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)            
            
a = [ 1, 2, 3, 7, "the" ]
c = [ 5, 6, 8, 9, "ifthen" ]
b = '4567'

# print(list(permutations(b, 3)))
# print(list(permutations(a, 5)))
# print(list(permutations(a, 4)))

# Permutation (Order matters)
#print (list(itertools.permutations(a, 3)))

# Combination (Order does not matter)
#print (list(itertools.combinations(a, 3)))

# Cartesian product (with several iterables - combine each with each one by one)
#print (list(itertools.product(a, c)))

# Cartesian product (with one iterable by itself, repeat factor)
#print (list(itertools.product(a, repeat=4)))


def permutation_generate(input, slots=2):    
    try:
        import itertools
    except ImportError:
        return([],"ImportError: Itertools")
    
    output_list = []
    count = 0
    calc = list(itertools.permutations(input, slots))
    count = len(calc)
    return [count, calc]

def combination_generate(input, slots=2):
    try:
        import itertools
    except ImportError:
        return([],"ImportError: Itertools")
    
    output_list = []
    count = 0
    calc = list(itertools.combinations(input, slots))
    count = len(calc)
    return [count, calc]

def combi_repl_generate(input, slots=2):
    
    checks = True
    
    try:
        import itertools
    except ImportError:
        return([],"ImportError: Itertools")
    
    output_list = []
    count = 0
    calc = list(itertools.combinations_with_replacement(input, slots))
    count = len(calc)
    return [count, calc]   
    
def cartesian_prod_generate(input1, input2):
    try:
        import itertools
    except ImportError:
        return([],"ImportError: Itertools")
    
    output_list = []
    count = 0
    calc = list(itertools.product(a, c))
    count = len(calc)
   
    return [count, calc]
    
def cartesian_prod_repeat(input1, integer):
    try:
        import itertools
    except ImportError:
        return([],"ImportError: Itertools")
    
    output_list = []
    count = 0
    calc = list(itertools.product(a, repeat=integer))
    count = len(calc)
   
    return [count, calc]
    

    
#print (permutation_generate(a, 4))
# print (combination_generate(a, 3))
# print (combi_repl_generate(a, 3))
#print (cartesian_prod_generate(a, c))
#print (cartesian_prod_repeat(c, 2))
#One important formula in finance and accounting is the formula for continually
#compounding interest. This formula takes as input an amount of money invested,
#an interest rate, and an amount of time (in years), and returns the value of
#the investment after that period of time.
#
#The formula, shown above, is Amount = Principal * e ^ (Rate * Time).
#
#In the code below, we have created a function called CalculateAmount. This
#function has access to three variables: Principal, Rate, and Time. Note that
#e is a constant; you may access it with math.e. Complete this function by
#completing the marked lines so that the function returns the value of an
#investment given a certain Principal, Rate, and Time.

import math

def CalculateAmount(Principal, Rate, Time):
    #If you want, you may add additional code here. Note that in the code you
    #write here, you have access to three variables: Principal, Rate, and Time.
    
    amount = Principal * math.e**(Rate*Time)
    
    #We'll round the answer to the nearest dollar to avoid long decimals.
    return round(amount)

#You may modify the variables below to test your code above.
testPrincipal = 5000
testRate = 0.05
testTime = 5

testAmount = CalculateAmount(testPrincipal, testRate, testTime)

print("After", testTime, "years invested with a", testRate, "interest rate, a", testPrincipal, "dollar investment will be worth", testAmount, "dollars.")
def _ss(data):
    """Return sum of square deviations of sequence data."""
    c = mean(data)
    ss = sum((int(x)-c)**2 for x in data)
    return ss

def pstdev(data):
    """Calculates the population standard deviation."""
    n = len(data)
    if n < 2:
        raise ValueError('variance requires at least two data points')
    ss = _ss(data)
    pvar = ss/n # the population variance
    return pvar**0.5
    
    
    
#####################################################################
# One function form


def pstdev(data):
    
    def _ss(data2):
        """Return sum of square deviations of sequence data."""
        c = mean(data2)
        ss = sum((int(x)-c)**2 for x in data2)
        return ss
    
    """Calculates the population standard deviation."""
    n = len(data)
    if n < 2:
        raise ValueError('variance requires at least two data points')
    ss = _ss(data)
    pvar = ss/n # the population variance
    return pvar**0.5
def square_root( n ):
    """ 
    Function: square_root
    Description: Calculates sq.root
    Input : Integer
    Output: Sqrt of integer
    Usage: sqrt( n )
    Is infinite-precision long-integer square-root evaluator
    Uses Newton's method, not floating-point 
    """
    if n < 1000000:
        return int(math.sqrt(n))
    digits = len( repr(n) ) - 1
    if digits <= 0: digits = 1
    x = 10 ** (digits/2)        ## smaller than actual sqrt
    decr = (x - n/x)/2
    while decr >= 1 or decr <= -1:
        x = x - decr
        decr = (x - n/x)/2
    return x
    
    
print (sqrt(34300003))
def smallest_number(*args):
    '''
    Function: smallest_number
    Description: Finds the smallest number
    Input: numeric arguments
    Output: smallest number
    Usage: smallest_number(-10, -5, 5, 10)
    Notes: Convert to biggest by changing min with max
    '''
    print min(args)
    return min(args)




smallest_number(-10, -5, 5, 10)
def quotientAndRemainder(dividend, divisor):
    quotient = dividend // divisor  
    #Complete this line such that quotient receives the
                #quotient of dividend and divisor
    remainder = dividend % divisor
    			#Complete this line such that remainder receives the
                #remainder of dividend and divisor
    return (quotient, remainder)

#You may modify these two variables to test your code
testDividend = 7
testDivisor = 3

#Don't modify these lines; they're used to test your code above!
(quo, rem) = quotientAndRemainder(testDividend, testDivisor)
print("The quotient is", quo)
print("The remainder is", rem)
def prime_factors(n):
  '''
  Function: prime_factors
  Description: Calculates prime factors of an integer
  Input: Integer
  Output: Prime factors of integer
  Usage: prime_factors(n)
  '''
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors
    
print (prime_factors(78))
def normalize(numbers):
  '''
  Function: normalize 
  Description: Normalizes a set of numbers
  Input: array of numbers
  Output: normalized array
  Usage: norm = normalize(a)
  Notes: Used to morph raw data
  '''
  max_number = max(numbers)
  for i in range(len(numbers)):
    numbers[i] /= float(max_number)
  return numbers  
    
    
a = [ 13, 11, 40, 10, 9 ]


print (normalize(a))
def mean(list):
    mean = 0
    for j in list:
        mean += int(j)
    return mean / len(list)

# First way - With repeated modulo
def lcm(p,q):
  '''
  Function : lcm
  Description : Calculates lcm of two numbers
  Input : p, q
  Output : lcm
  Usage : a = lcm(3,4)
  Notes : Using repeated modulo
  '''
	p, q = abs(p), abs(q)
	m = p * q
	if not m: return 0
	while True:
		p %= q
		if not p: return m // q
		q %= p
		if not q: return m // p
		
		
# For more than one value
def lcm(*values):
  '''
  Function: lcm
  Description: Calculates lcm (for more than 2 values)
  Input: a, b, c, d
  Output: lcm
  Usage: print (lcm(3,4,8))
  Notes: Can take any arguments
  '''
	values = set([abs(int(v)) for v in values])
	if values and 0 not in values:
		n = n0 = max(values)
		values.remove(n)
		while any( n % m for m in values ):
			n += n0
		return n
	return 0
	
	
print (lcm(3,4,8))
def is_prime( n ):
    '''
    Function: is_prime
    Description : Checks if a number is prime
    Input: Integer
    Output: Boolean (T/F)
    Usage: is_prime(10)
    Usage: is is_prime(11):
    Notes: Contains call to "Factors" function(Embedded)
    '''
    import math
    
    def factors( m, verbose = 0 ):
        lfactors = []
        sq = math.sqrt(m)
        while m % 2 == 0:
            lfactors.append( 2 )
            m = m/2
            sq = math.sqrt(m)
            if verbose:
                print (2)
        d = 3
        while  d <= sq:
            if m % d == 0:
                lfactors.append( d )
                m = m/d
                sq = math.sqrt(m)
                if verbose:
                    print (d)
            else:
                d = d+2
        if m > 1:
            lfactors.append( m )
            if verbose:
                print (m)
        return lfactors
    

    if (factors(n) == [n]):
        return True
    else:
        return False
        
        
print (is_prime(18))
print (is_prime(17))
def harmonic(n):
	''' 
	Function: harmonic
	Description: Evaluate harmonic series up to n into array
	Input : n > 0
	Output : Array with n first elements of harmonic series
	Usage: b = harmonic(50)
	Notes: Only integer arguments
	'''
	harmonic_series = [1]
	for i in range(2,n,1):
		temp = 1.0/i
		print (i)
		print (temp)
		harmonic_series.append(temp)
	return harmonic_series
	
n = input("Print n first numbers of Harmonic: ")
print (harmonic(n))
def harmonicsum(n):
    '''
    Function: harmonicsum
    Description: Compute partial sum of the harmonic series:
    1/1 + 1/2 + 1/3 + 1/4 + ... + 1/n.
    Input: n must be an integer > 0.
    Output: Returns the harmonic sum, as a float.
    Usage: a = harmonicsum(100)
    Notes: Harmonic sum has no upper limit
    '''
    sum = 0.0
    for i in range(int(n)):
        sum += 1.0 / (i+1)
    return sum

# The rest of this is a testbed program;
# the exam did not require this.

# n = input("Compute harmonic sum up to (n>0) n=")	# Py3: int(input(...
# print "The sum is: %.10f" % harmonic(n)			# Py3: print(...

def geometric(n):
	'''
	Function: geometric
	Description: Evaluate geometric series up to n into array
	Input: n > 0 (Integer)
	Output:  Array with n first elements of geometric series
	Usage: llista = geometric(5)
	Notes: Only integer arguments
	'''
	geometric_series = [0]
	for i in range(1,n,1):
		temp = 1.0/(2*i)
		# print (i)
		# print (temp)
		geometric_series.append(temp)
	return geometric_series
	
n = input("Print n first numbers of geometric: ")
print (geometric(n))
def geometricsum(n):
	'''
	Function: geometricsum
	Description: Evaluate geometric series sum up to n 
	Input : n > 0
	Output : Sum of n first elements of geometric series
	Usage: a = geometricsum(5)
	Notes: Only integer arguments
	'''
	geometric_series = [0]
	for j in range(1,n,1):
		temp = 1.0/(2*j)
		# print (i)
		# print (temp)
		geometric_series.append(temp)
	
	total = 0
	for i in geometric_series:
		total += i
	
	return total
	
print (geometricsum(n))	
def genPrimesFn(amount):
    '''
    Function: genPrimesFn
    Description: Generates a set amount of primes
    Input: Amount of primes
    Output: List with primes
    Usage: genPrimesFn(5)
    Notes: Only integer input
    Function to return 1000000 prime numbers
    '''
    primes = []   # primes generated so far
    last = 1      # last number tried
    while len(primes) < amount:
        last += 1
        for p in primes:
            if last % p == 0:
                break
        else:
            primes.append(last)
    return primes

def genPrimesinterval(amount, interval):
    '''
    Function: genPrimesinterval
    Description: Function to print every 10th prime
    number, until you've printed 20 of them.
    Input: Amount(Integer) - amount of primes to be stored
           Interval - amount of primes to be skipped
    Output: List
    Usage: a = genPrimesinterval(5,10)
    Notes: Arguments can only be integers
    '''
    primes = []   # primes generated so far
    intervalprimes = [] # interval primes to be stored
    last = 1      # last number tried
    counter = 1
    while True:
        last += 1
        for p in primes:
            if last % p == 0:
                break
        else:
            primes.append(last)
            counter += 1
            if counter % interval == 0:
                # Print every 10th prime
                intervalprimes.append(last)
            if counter % (amount*interval) == 0:
                # Quit when we've printed the 10th prime 20 times (ie we've
                # printed the 200th prime)
                return intervalprimes


c = genPrimesFn2(10, 5)
print (c)
             



def genPrimesmanual():
    '''
    Function: genPrimesmanual
    Description:  Function to keep printing the prime number until the user stops the program.
    This way uses user input; you can also just run an infinite loop (while True)
    that the user can quit out of by hitting control-c
    Input: None
    Output: STDOUT, print
    Usage: genPrimesmanual()
    Notes: No arguments
    '''
    primes = []   # primes generated so far
    last = 1      # last number tried
    uinp = 'y'    # Assume we want to at least print the first prime...
    while uinp != 'n':
        last += 1
        for p in primes:
            if last % p == 0:
                break
        else:
            primes.append(last)
            print(last)
            uinp = input("Print the next prime? [y/n] ")
            while uinp != 'y' and uinp != 'n':
                while uinp:
                    print("Sorry, I did not understand your input. Please enter 'y' for yes, or 'n' for no.")
                    uinp = input("Print the next prime? [y/n] ")
            if uinp == 'n':
                break
def gcd(x,y):
    """ 
    Function: gcd
    Description : Finds greatest common divisor
    Input : 2 integers
    Output: Greatest common divisor
    Usage: gcd(10,2)
    """
    while ( y>0 ):
        x = x % y
        (x,y) = (y,x)
    return x
def full_euclid(x,y):
    """ 
    Function: full_euclid(x,y)
    Description: Calculates euclid relation
    Input: 2 integers
    Output: List of integers [a,b,g]
    Usage: full_euclid( x, y )
    Returns [a,b,g] so that a.x + b.n = g = gcd(x,n) 
    """ 
    def sgn( n ):
        if n > 0:
            return 1
        elif n < 0:
            return -1
        else:
            return 0
     
     
     
    a,b,c,d = 1,0,0,1
    sgnx = sgn(x)
    sgny = sgn(y)
    x = abs(x)
    y = abs(y)
    while y != 0:
        [q,r] = divmod(x,y)
        x,y = y,r
        a,b,c,d = c,d,a-c*q,b-q*d
    # now a.x_abs + b.y_abs = gcd
    return a*sgnx, b*sgny, x # now x is the gcd


print (full_euclid(30,10))
def find_last_index( bound, List ):
    
    import math
    """ 
    Function: find_last_index( bound, List )
    Description : finds highest index i so that List[i] <= bound 
    Input: Two integers
    Output: Tuple of (Index, List Element)
    Usage: find_last_index( bound, List )
    Notes: Uses divide-and-conquer (binary expansion) search 
    """
    lg = int( math.log( len(List)-1 )/ math.log( 2 ) )
    now = pow(2, lg) - 1
    while ( lg > 0 and (List[now] > bound or
                        ( now+1 < len(List) and List[now+1] <= bound ))):
        lg = lg - 1
        inc = pow(2,lg)
        if List[now] > bound: # guess is too high
            now = now - inc
        else:                   # too low
            if now + inc < len(List):
                now = now + inc
            else:
                pass
    return (now, List[now])

a = [ 1, 2, 3, 8, 2, 6, 7, 8 ]

print (find_last_index(5, a))
# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
  '''
  Function: fib(n)
  Description: prints the first n fibonacci numbers
  Input: n (integer)
  Output: STDOUT, screen
  Usage: fib(n)
  Notes: Prints on screen
  '''
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b

def fib2(n):   # return Fibonacci series up to n
  '''
  Function: fib2(n)
  Description: Stores the first n fibonacci numbers in list
  Input: n (integer)
  Output: List
  Usage: fib2(n)
  Notes: Stores output in list
  '''
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result
    
###################################

def fibonacci(n):
	'''
	Function: fibonacci(n)
	Description: Calculates the sum of first n fibonacci
	Input: Integer > 09FA
	Output: Prints first n numbers of fibonacci
	Usage: print (fibonacci(n))
	Notes: Compute partial sum of fibonacci series : (0 + 1 + 1 + 2 + 3 + 5)
	'''
	fibonacci_numbers = [0, 1]
	for i in range(2,n):
		fibonacci_numbers.append(fibonacci_numbers[i-1]+fibonacci_numbers[i-2])
	return fibonacci_numbers
	
n = input("Print n first numbers of Fibonacci: ")
print (fibonacci(n))
def fibonaccisum(n):
  '''
  Function: fibonaccisum(n)
  Description: Returns the sum of first n fibonacci numbers
  Input: Target number
  Output: Sum of fibonacci up to target number
  Usage: b = fibonaccisum(n)
  Notes: n = integer
  '''
	fibonacci_numbers = [0, 1]
	
	for i in range(2,n):
		fibonacci_numbers.append(fibonacci_numbers[i-1]+fibonacci_numbers[i-2])
	
	for j in fibonacci_numbers:
		j += j
		
	return j
	
n = input("Print the sum of the first n Fibos: ")
print (fibonaccisum(n))
def factors( m, verbose = 0 ):
    import math
    """
    Function: factors
    Description: Finds a factor combination of a number
    Input: Integer
    Output: List of factors
    Usage: factors( m, verbose = 0 )
    returns [list_of_factors]
    """
    list_of_factors = []
    sq = math.sqrt(m)
    while m % 2 == 0:
        list_of_factors.append( 2 )
        m = m/2
        sq = math.sqrt(m)
        if verbose:
            print (2)
    d = 3
    while  d <= sq:
        if m % d == 0:
            list_of_factors.append( d )
            m = m/d
            sq = math.sqrt(m)
            if verbose:
                print (d)
        else:
            d = d+2
    if m > 1:
            list_of_factors.append( m )
            if verbose:
                print (m)
    return list_of_factors
    
    
    
print (factors(1485674))

def distance_from_zero(arg):
  '''
  Function: distance_from_zero
  Description: returns the absolute value
  Input: Number
  Output: Absolute of number
  Usage: distance_from_zero(number)
  Notes: Works on any kind of number
  '''
    print abs(arg)
    return abs(arg)


distance_from_zero(-10)
def checkiftriangleexists(side1, side2, side3):
    '''
    Name: checkiftriangleexists
    Function: check if a triangle exists by comparing sides
    Description: Check if a triangle exists
    Input: 3 integers
    Output: Boolean
    Usage: print (checkiftriangleexists(1,2,4))
    '''
    return (side1 + side2) > side3
    
print (checkiftriangleexists(1,2,4))
def binomial_coefficient( n , k ):
  '''
  Function: binomial_coefficient(n.k)
  Description: Calculates binom coefficient of n by k
  Input : Integer (n,k)
  Output: Integer (Binomial Coefficient)
  Usage: binomial_coefficient(n,k)
  Usage: print (binomial_coefficient(n,k))
  '''
    out = n + 0
    for i in range(1,k):
        out = out * (n-i)
    for i in range(1,k+1):
        out = out/i
    return out
    
    
print (binomial_coefficient(20, 2))

#### BETTER VERSION

def binomial(x, y):
    from math import factorial as fac
    try:
        binom = fac(x) // fac(y) // fac(x - y)
    except ValueError:
        binom = 0
    return binom



print (binomial(45,5))
def biggest_number(*args):
  '''
  Function: biggest_number
  Description: Returns the greatest number provided
  Input: Any number of numbers
  Output: Largest number
  Usage: biggest_number(5, 6, -10, -1)
  Notes: Works for any kind of number
  '''
  print max(args)
  return max(args)
    


biggest_number(-10, -5, 5, 10)
######################################################
# FUNCTION - CALC_ARRAY
# APPLIES CALCULATION OF FUNC TO ARRAY ELEMENTS 
# ELEMENT BY ELEMENT
# NOTES : THE ARRAYS NEED TO BE OF THE SAME SIDE
# THE ARRAYS NEED TO BE OF THE SAME TYPE, OTHERWISE :
# MIXED NUMBERS WILL BE CONVERTED TO FLOATS
# MIXED ARRAYS WITH STRINGS WILL YIELD STRING
def func(x, y):
    '''
    Token function defined for calc purposes
    '''
    return x * y

def func2(x, y):
    '''
    Token function defined for calc purposes
    '''
    return y - x ** 2    
    
def func3(x, y):
    '''
    Token boolean function used for calc purposes
    '''
    return x > y
    
def calc_array(list1, list2, f):
    '''
    Function: calc_array
    Description: Element-wise calculations in lists
    Input: list1, list2, function
    Output: f(list1, list2)
    Usage: print (calc_array(height, weight, func))
    Notes: Lists must be of the same size
    '''
    import numpy as np
    flist1 = np.array(list1)
    flist2 = np.array(list2)
    return f(flist1, flist2)
    
print (calc_array(height, weight, func))
print (calc_array(height, weight, func2))
print (calc_array(height, weight, func3))
print (calc_array(height, alt, func))
b = (calc_array(height, alt, func))
print (type(b[1]))
_
# Float will either be given as XXX,YY
# or XXXX.YY

#xxx.yy - straight conversion
float_in = float(XXX.YY)

#XXX,YY - replace with ., then convert
string_in = "XXX,YY"
string_fixed = string_in.replace(",", ".")
float_in = float(string_fixed)


# Example with comparison
try:
            value_fl = value_in.replace(',', '.')
        except Exception as e:
            print("cant convert to float with exception: " + str(e))
        else:
            value_fl_fixed = float(value_fl)
        finally:
            #print(key_in, value_in, value_fl, value_fl_fixed)
            pass
            
        if value_fl_fixed >= 150:
            outfile_first.write(line)
        else:
            outfile_firstr.write(line)

以上是关于python Python.Math.Algebra的主要内容,如果未能解决你的问题,请参考以下文章

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python

python初识