I've been trying to figure out this code challenge for a while. I have to write a callable function in python...

I've been trying to figure out this code challenge for a while. I have to write a callable function in python, that will find the lowest number from a list of numbers, as well as a function that will find the highest number from a list of numbers. The catch? Min() and Max() cannot be used at all. I know that I probably shouldn't be asking for help with a project on here but i'm getting desperate here. Any help or suggestions?

Other urls found in this thread:

api.mathjs.org/v1/?expr={}>{}'.format(number,
api.mathjs.org/v1/?expr={}
en.wikipedia.org/wiki/Big_O_notation
twitter.com/SFWRedditGifs

compare each number using < and >

import random

def mymax(x):
while True:
x = random.shuffle(x)
if x == sorted(x):
return x[0]

def mymin(x):
while True:
x = random.shuffle(x)
if x == sorted(x):
return x[-1]

are you fucking retarded OP
explain to me how you'd do it on paper

Swap 0 and -1

kek

also replace
x = random.shuffle(x)

with
x = random.sample(x, k=len(x))

because random.shuffle doesn't work that way

How can you possibly be in any form of schooling and are unable to do this?

You mean with random.shuffle(x)
Shuffle does exactly what you'd expect it does but it does it in place.

why simplify it tho?

Sort the list and then look at the first and last entry in it.

Give up now. This is too basic to struggle with.

>nlogn instead of n
fucking hell Sup Forums is full of idiots.

Thanks I appreciate it

because university level education is a joke and my professor has a worse grasp on the English language than I have on python

nah man, I just started learning. I havent been taught very well but I figure I might as well just self teach from here.

>compare shit until you are left with highest, pass
>compare shit until you are left with lowest, pass
>I don't have an exact command to do what I want, WHAT DO I DO?!?!?
Get out of programming now, you will NEVER make anything of value, or even anything usable.

Good question. I tried to improve it.

import random

def mymax(x):
while True:
new_list = []
selected = []
while len(selected) < len(x):
while True:
index = random.randrange(len(x))
if index not in selected:
break
selected += [index]
new_list += [x[index]]
if new_list == sorted(x):
return x[-1]

def mymax(x):
while True:
new_list = []
selected = []
while len(selected) < len(x):
while True:
index = random.randrange(len(x))
if index not in selected:
break
selected += [index]
new_list += [x[index]]
if new_list == sorted(x):
return x[0]

def min(xs): reduce((lambda x,y: x if xy else y), xs)

Oh come on don't be so harsh on him

that's nothing but intellectual wankery, it's not like enjoying the smell of your farts ie code is going to make the program run faster

Try the dpt, our thread specifically for programming

beautiful. slightly reminds me of my swapsort algorithm if it wasn't for the randomness.

...

truly it can be improved?
from functools import reduce, partial
min = partial(reduce, lambda x, y: x if x < y else y)
max = partial(reduce, lambda x, y: x if x > y else y)

Whoops, return x[-1] should be return new_list[-1]

We can do better.
from functools import reduce, partial
min = partial(reduce, lambda x, y: [x,y][x>y])
max = partial(reduce, lambda x, y: [x,y][x

def min(x):
min = x(0);
for i in range(len(x)-1):
if x(i) < min:
min = x(i)
return min
repeat for max, swap < for >

why did you give him the answer you idiot

Let a be your list
def minimum(a):
a.sort()
return a[0]
def maximum(a):
a.sort()
return a[-1]

see
vs
stop giving advice. stop programming. stop breathing. you're retarded.

>stop giving advice. stop programming. stop breathing. you're retarded.
Did it say anywhere that the functions should be as efficient as possible? No. The OP hasn't even taken an algorithms class yet (otherwise he wouldn't have started this thread), so the solution should be as easy as possible for him to understand.

def minimum(a):
for i in a:
for j in a:
if i > j:
break
else:
return i

I'm a python baby and I never feel like I'm good at programming, but this is what I made
def find_high(num_list):
result = num_list[0]
for i in num_list:
if i > result:
result = i
print(result)
return result

def find_low(num_list):
result = num_list[0]
for i in num_list:
if i < result:
result = i
print (result)
return result

rate on a scale of pajeet to ok

>posting O(n) solution
y u do tis

I'm sorry, did I do something I'm not supposed to do?

lol are these people sorting the list for fucking real?

95% of programmers haven't taken an algorithms class. they copy paste solutions like yours off stack overflow. that's why we have disgustingly inefficient monstrosities all over the place.

if you're going to give OP come code to copy and paste into his homework or pet project, at least have him copy something that isn't slow.

perfect.

Sup Forums can't program for shit. what's worse is they will put the sort into their method bodies so they have to sort the same list twice to get a max and min

never ceases to amaze me

>mfw nobody posts the logn solution

>python baby
>manages to do an O(n) solution

meanwhile

>implies you need to take an algorithms class to give an O(n) answer
>gives a shitty code golf answer that doesn't help at all

Really makes you think

I'm the aforementioned python baby.
What is an O(n) solution? the thing O(n) itself just looks like a function call.

>did I do something I'm not supposed to do?
print and then return

Beautiful.

This is worth extra points
You're welcome OP
import urllib.request

def max(x):
result = x[0]
for number in x:
if urllib.request.urlopen('api.mathjs.org/v1/?expr={}>{}'.format(number, result)).read() == b'true':
result = number
return result

def min(x):
result = x[0]
for number in x:
if urllib.request.urlopen('api.mathjs.org/v1/?expr={}

en.wikipedia.org/wiki/Big_O_notation

It's a pretty big concept in computer science to describe algorithm complexity. Sorting the list first and then checking the first and last entries in the list O(n log n) is much less efficient than doing what you did, checking each value in the list and storing the lesser or greater value into a variable, O(n).

ah okay.
I don't actually have any training or schooling on algorithms, so I don't really have an idea on what is more efficient over other things. My results were just the first way I thought of doing the problem.

>The catch? Min() and Max() cannot be used at all.
In what sense is this a fucking catch?

kek'd

Look up Big O Notation - its an approximation of the time complexity of an algorithm

Wrong, it's higher order programming and it's the best way to write correct programs.

Well good job user you might actually turn out to be a good programmer after all if you keep learning.

I'm not trying to call you wrong, but I ran a test just to compare the two results and .sort() for this particular application seems to be faster

from time import time


def min(numlist):
sm = numlist[0]
start = time()
for i in numlist:
if i < sm:
sm = i
end = time()
print('< method, Seconds to return: {}'.format(end - start))
return sm


def sort_method(numlist):
start = time()
numlist.sort()
sm = numlist[0]
end = time()
print('.sort() method: Seconds to return: {}'.format(end - start))
return sm


def gen_list():
return [i for i in range(0, 100000000)]


nums = gen_list()
min(nums)
sort_method(nums)


And the results:
< method, Seconds to return: 3.1073946952819824
.sort() method: Seconds to return: 1.4041564464569092

Keep in mind, I'm not saying you're wrong (I haven't done much algorithm design yet) but how long would a list have to be before .sort() becomes less efficient? Or is my timing method inaccurate?

it's a catch for pythonfags

for instance ask them to write a function that checks if a number is a palindrome, but without using string methods, they'll be pissed

your list is already sorted you absolute retard

who hurt you

Haha, good point, Let me rewrite it

> [i for i in range(0, 100000000)]
> list(range(0, 100000000))

I never claimed to know what I'm doing, that's why I'm asking, jesus christ.

Replace it with [random.randint(1, 100) for i in range(0, 100000)]
You'll see the difference

Consider fixed length arrays, for exmaple of size 4, plus unsigned ints of maximum size 4 bits.
store the following patterns in memory
P1 = [0001 0001 0001 0001]
P2 = 0010 0010 0010 0010]
P3 = [0100 0100 0100 0100]
P4 = [1000 1000 1000 1000]
(all the way to P(log(size of int...))

REPEAT:
consider the array to be a single value, e.g.
A = [4, 5, 2, 8] = [0100 0101 0010 1000]

for each Px perform
R = A & Px

until R = 0, with some Px
so the highest values were at P(x-1)
recalculate R = A & P(x-1)
Parallelize the following
propagate each 1 in the bit sequence L = 4 (size of int) - (x-1) to the right and 4 - L to the left
0000 0100 0000 0101 -> N = 0000 11111 0000 11111

perform M = N & A to mask out all the smaller values
END REPEAT
GOTO REPEAT, but only perform the steps up to P(x-2) and perform them on N instead of A
maybe you will end up with a single masked 4 bit block in the sequence and then somehow find the answer based on that :(

Well first of all your list is already in order. But secondly, python calls C code for its built-in functions which is generally much faster than native python code. Test the built-in max() or min() functions against the built-in sort() function or write a manual mergesort in python (which is really what sort() is, just written in C) and test it against your min function. Either way, iterating over the list once is always slower than trying to sort the list and then testing the first and last values.

> Either way, iterating over the list once is always slower than trying to sort the list and then testing the first and last values.
fuck meant *faster

I definitely structured my test poorly, reran it via a list of random numbers
< method, Seconds to return: 3.0342931747436523
.sort() method: Seconds to return: 33.992687463760376

Learn something new all the time.

This really

thanks.
Any resources that you reccommed I read through to get a better understanding of how to make efficient code?

That's a fun challenge. I am currently learning as well and this is the best I could come up with, any tips on how to improve it? Thanks.

>What is an O(n) solution? the thing O(n) itself just looks like a function call.

bait?
read the thread

Not gonna lie I was hoping someone would reply to with a solution for me because I have no clue wtf the whole O(n) thing is

nobody hurt us. this is just like someone coming up to you on the street in a panic asking where used toilet paper is supposed to go. if you're this stupid, you should be quarantined. if you're trolling, then fuck off

>these are the people who do i % 3 && i % 5 in their fizzbuzz instead of just the LCM, i % 15
>these are the people who can't even sum the primes under 2 million
>these are the people who can't bubble sort

Just ran it again to compare vs .min(), turns out that the '< method' is actually marginally faster than .min().

Thanks for your explanation

someone above posted a link to wikipedia with the explanation of what it is, definitely read it, you have to atleast understand it

I wonder if that actually turns out to be an improvement, creating a list every iteration

What's wrong with
def mymax(x):
a = [0]
[a.insert(0, b if b>a[0] else a[0]) for b in x]
return a[0]

>>> mymax([-1, -2, -3])
0

try heapq module

Just keep using logic for now. CLRS once you have some maturity.

I've been running it for a few min, doesn't seem to work for the dataset I fed it, seems to be caught in an infinite loop.

>callable function
Are you sure they wanted it to be callable?

Fails on empty list because [0] is out of range.

To be fair, what would you expect it to do given an empty list? If an empty list has no sane answer, then it should fail fast rather than return None or something else.

>can't bubble sorr
Why should anyone know bubble sort? It's only useful as a cautionary tale. Even for snall n, where you expect a low-k algorithm to perform well, insertion sort beats it and is even simpler to implement.

Lol, one person applied for the dev position at my company who happened to be a phythonfag had the same problem.

you just take a for loop, set min/max to numbers(0) and use an if statement to see if numbers(i) is less than min/bigger than max. If you can't figure this out drop out now.

Not a perfect answer, because it does index iteration rather than foreach. On top of being needlessly verbose, it degrades to O(n^2) if x is a linked list or other O(n) retrival-by-index list.

so like this you mean:
def min(x):
min = x(0)
for i in x:
if i < min:
min = i
return min

Yes
Although x(0) should be x[0] if you want it to actually compile.

Right I knew that, the guy who posted the original one just threw me off.