#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0

    Exclamation Average and medians


    if i have already defined a list "X" how would I go about sorting the list "X" in place, and then use an if statement to find the median of X?

    Also if X has an even number of elements, take the average of
    the middle 2 elements of X as the median and print it.
    Otherwise i would like to use an "elsif" statement to take the middle element of X as the median and print it.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480
    >>> help(list)

    ...


    shows that there is a sort method.


    >>> LIST.sort()

    sorts it in place.


    >>> len(LIST)//2
    gives the near-median.

    Code:
    >>> def odd(a):
    ...     'return 1 if the integer a is odd, else return 0'
    ...     return a & 1
    ... 
    >>> def even(a):
    ...     'return True if the integer a is even, else return False'
    ...     return not odd(a)
    ... 
    >>>

    A function for average follows:
    Code:
    import sys
    import math
    import operator
    
    
    ALPHABET = ''.join('%c'%c for c in range(256))
    
    def out(x, y = sys.stdout):               # foreign1_2
        w = y.write
        if (not hasattr(x, '__len__')) or (type(x) is str):
            w(str(x))
        else:
            if type(x[0]) is str:
                w(''.join(x))
            elif not hasattr(x[0], '__len__'):
                w(' '.join(str(X) for X in x))
            else:
                for X in x:
                    out(X,y)
        w('\n')
    
    def integers(y):
        if 0 == y:
            return []
        result = range(abs(y))
        if y < 0:
            result = reversed(result)
        return list(result)
    
    assert integers(8) == [0, 1, 2, 3, 4, 5, 6, 7]
    assert integers(-2) == [1, 0]
    
    def steps(y):
        'to do: implement complex steps'
        STEP = (0 <= y) - (y < 0)
        return list(range(-y, y + STEP, STEP))
    
    assert [0] == steps(0)
    assert [-3, -2, -1, 0, 1, 2, 3] == steps(3)
    assert [3, 2, 1, 0, -1, -2, -3] == steps(-3)
    
    def tally(y):
        return len(y)
    
    def table(u):
        def table(x, y, u = u):
            return [[u(X,Y) for Y in y] for X in x]
        return table
    
    def polynomial(x, y):
        result = 0
        for a in reversed(x):
            result *= y
            result += a
        return result
    
    def factorial(y):
        return math.factorial(y)
    
    def combinations(x, y):
        return math.factorial(y) / (math.factorial(x) * math.factorial(y - x))
    
    def base(x, y):
        if not hasattr(x, '__len__'):
            x = [x]*len(y)
        w = [1]
        for f in reversed(x[1:]):
            w[:0] = [w[0] * f]
        return sum(map(operator.mul, w, y))
    
    def antibase(x, y):
        '''
            doctest.  Run with bash command  $ python -m doctest this_file.py
        	Find base 10 digits of small numbers.
            >>> antibase([10]*8, 23456)
            [0, 0, 0, 2, 3, 4, 5, 6]
        	>>>
    
        	convert $1.38 to coins.
        	A quarter is 2.5 times more valuable than a dime.
                A dime has twice the value of a nickel.
        	A nickel is worth 5 pennies.
        	A penny is worth 1.
    
        	The output [5.0, 1.0, 0.0, 3.0, 0.0] represents
        	the number of quarters, dimes, nickels, pennies, and fractional pennies.
    
        	>>> US_COINS = antibase([9999, 2.5, 2, 5, 1], 138)
        	>>> print(US_COINS)
        	[5.0, 1.0, 0.0, 3.0, 0.0]
        	>>>
        '''
        n = y
        base = x
        cumprod = [1]
        for b in reversed(base):
            cumprod[:0] = [cumprod[0]*b]
        result = []
        for f in cumprod[:-1]:
            (a,n,) = divmod(n,f,)
            result.append(a)
        result.append(n)
        return result[1:]
    
    def antibase2(y):
        if (y < 0) or (int(y) != y):
            raise ValueError('y must be non-negative integer')
        result = []
        while y:
            result[:0] = [y & 1]
            y >>= 1
        return result if result else [0]
    
    def From(x, y):
        if hasattr(x,'__len__'):
            result = []
            for X in x:
                result += [From(X,y)]
            return result
        return y[x]
    
    def mfork(f, g, h):
        def fork(y, f = f, g = g, h = h):
             return g(f(y), h(y))
        return fork
    
    def dfork(f, g, h):
        def fork(x, y, f = f, g = g, h = h):
             return g(f(x, y), h(x, y))
        return fork
    
    def mhook(f, g):
        def hook(y, f = f, g = g):
            return f(y, g(y))
        return hook
    
    def dhook(f, g):
        def hook(x, y, f = f, g = g):
            return f(x, g(y))
        return hook
    
    def reflexive(u):
        def reflexive(y, u = u):
            return u(y, y)
        return reflexive
    
    def passive(u):
        def passive(x, y, u = u):
            return u(y, x)
        return passive
    
    def mat(u, v):
        def at(y, u = u, v = v):
            return u(v(y))
        return at
    
    def dat(u, v):
        def at(x, y, u = u, v = v):
            return u(v(x, y))
        return at
    
    def mcompose(u, v):
        def compose(y, u = u, v = v):
            return u(v(y))
        return compose
    
    def dcompose(u, v):
        def compose(x, y, u = u, v = v):
            return u(v(x), v(y))
        return compose
    
    def insert(u):
        def insert(y, u = u):
            result = y[:]
            for i in reversed(range(len(y)-1)):
                result = result[:i] + [u(result[i], result[i+1:][0])]
            return result[0]
        return insert
    
    def mbond(m, v):
        def bond(y, m = m, v = v):
            return v(m, y)
        return bond
    
    def nbond(u, n):
        def bond(y, n = n, u = u):
            return u(y, n)
        return bond
    
    base2 = mbond(2, base)
    
    def dotproduct(u, v):
        def dotproduct(x, y, u = u, v = v):
            result = [[0] * len(y[0]) for i in x]
            for (i, X,) in enumerate(x):
                for (j, Y,) in enumerate(zip(*y)):
                    result[i][j] = u(list(map(v, X, Y)))
            return result
        return dotproduct
    
    mp = dotproduct(insert(operator.add), operator.mul)
    assert [[11, 6], [17, 6], [20, 6]] == mp([[1,2,3],[3,2,1],[4,2,0]],[[4,1],[2,1],[1,1]])
    
    quadratic_table = mfork(                   # y >= (1 + 0*x + (x**2)/4)
        mat(integers, operator.neg),
        table(dhook(
            operator.ge,
            mbond([1, 0, 0.25], polynomial))),
        steps)
    
    average = mfork(insert(operator.add), operator.truediv, tally)
    # example:  A is a list of even length
    # average(A[len(A)//2:len(A)//2+2])
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0
    thanks you b49P23TIvg, alot more than i thought i was diving into. Is there an easier way to do the average? it seems very tedious to have to define every antibase. Also I am unfamiliar with some of the language ( use of mp = , quadratic table).

    Thank you
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480

    How about this version?


    Code:
    tally = len
    
    def average(LIST):
        return sum(LIST) / float(tally(LIST))
    
    def round_down(A):
        return int(A)
    
    def round_up(A):
        return int(A+0.6)
    
    def median(LIST):
        '''
            >>> median([1,2,3,4])
            2.5
            >>> median([1,2,4])
            2.0
            >>> median([1])
            1.0
            >>> 
        '''
        LIST.sort()
        mid_index = (tally(LIST)-1) / 2.0
        LEFT = LIST[round_down(mid_index)]
        RIGHT = LIST[round_up(mid_index)]
        return average([LEFT, RIGHT])
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0
    yes thank you very much i'm still learning so the simplicity helps alot

    when i work with command lines

    how do i Read the third command-line option as an integer.
    and if the number is less than or equal to zero, print "too small".
    -otherwise, create a list containing all the integers starting with 0
    up to and including the number the user input.
    - then print that list to standard out.
    -If the sum of the numbers in the list is more than 10, print the
    sum to standard out. Otherwise, print "sum is less than 10".
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    5
    Rep Power
    0

    Question


    also how to Read the second command-line option as a floating-point number.
    # If the number is less than zero, print its absolute value.
    # If the number is greater than zero, print the string "too big".
    # If the number is exactly zero, print the string "zero".

IMN logo majestic logo threadwatch logo seochat tools logo