Open Side Menu Go to the Top
Register
Programming homework and newbie help thread Programming homework and newbie help thread

02-22-2015 , 08:18 AM
Crawl before you walk imo
Programming homework and newbie help thread Quote
02-25-2015 , 02:17 PM
Question about big O for binary search.

From what I understand, the Big O for worst case scenario is O(log2N) where the 2 is sub.

So for a 1000 items it would be:
2^x = 1000
xlog 2 = log 1000 //me taking log of both sides
x = log1000/log2
Where x is the number of comparisons for 1000 items.

Am I understanding this correctly?
Programming homework and newbie help thread Quote
02-25-2015 , 04:42 PM
Quote:
Originally Posted by Barrin6
Question about big O for binary search.

From what I understand, the Big O for worst case scenario is O(log2N) where the 2 is sub.

So for a 1000 items it would be:
2^x = 1000
xlog 2 = log 1000 //me taking log of both sides
x = log1000/log2
Where x is the number of comparisons for 1000 items.

Am I understanding this correctly?
I think you understand it but the math is wrong. If I'm not mistaken:

x = log2 1000

For.instance 1024 is 2**10. For 1024, x equals 10.
Programming homework and newbie help thread Quote
02-25-2015 , 07:12 PM
Right but that's the same as log(1000) / log (2)?

x = log2 1000 is the same as x = log 1000/ log 2? No?

Actually yea, that both comes out to 9.96.

She did however say that in class we can simplify log2(N) as log(N) but doesn't that changes the number quite a bit?
Programming homework and newbie help thread Quote
02-25-2015 , 09:01 PM
Quote:
Originally Posted by Barrin6
Right but that's the same as log(1000) / log (2)?

x = log2 1000 is the same as x = log 1000/ log 2? No?

Actually yea, that both comes out to 9.96.

She did however say that in class we can simplify log2(N) as log(N) but doesn't that changes the number quite a bit?
Not sure about the log equation but 9.96 looks right so I guess your equation is right.
Programming homework and newbie help thread Quote
02-25-2015 , 11:53 PM
seriously reworked my poker hand program to simulate preflop heads up equity

seems to work OK, although it takes a little longer than i would like for it to run

going to set this aside for now and focus more on the course materials

thanks to everyone for the advice

Code:
from operator import itemgetter
import random

VALUES = map(str, range(2, 10)) + ['T', 'J', 'Q', 'K', 'A']
SUITS = ['c', 'd', 'h', 's']
FULL_DECK = [v + s for s in SUITS for v in VALUES] 
VALUES_DICT = dict(zip(VALUES, range(13)))
HAND_RANK = {
    (1,1,1,1,1,'s','f'): ('Straight flush', 9), (4,1): ('Four of a kind', 8),
    (3,2): ('Full house', 7), (1,1,1,1,1,'f'): ('Flush', 6), 
    (1,1,1,1,1,'s'): ('Straight', 5), (3,1,1): ('Three of a kind', 4),
    (2,2,1): ('Two pair', 3), (2,1,1,1): ('One pair', 2),
    (1,1,1,1,1): ('High card', 1) 
}

class Card(object):

    def __init__(self, name):
        """name is a string with value and suit, e.g. 'As', '8c', or 'Td'"""
        self.n = name
        self.r = name[0]
        self.v = VALUES_DICT[name[0]]
        self.s = name[1]
    
    def rank(self):
        return self.r
    
    def value(self):
        return self.v
    
    def suit(self):
        return self.s
    
    def __str__(self):
        return self.n

class Hand(list):

    def __init__(self, cards):
        """cards is a list of card objects"""
        list.__init__(self, cards)
        name = '<'
        for c in cards:
            name += str(c) + ','
        self.n = name[0:-1] + '>'
    
    def ranks(self):
        return [c.rank() for c in self]
    
    def values(self):
        return [c.value() for c in self]
    
    def suits(self):
        return [c.suit() for c in self]
    
    def sorted_values(self):
        self.sv = list(self.values())
        self.sv.sort()
        return self.sv
    
    def counts(self):
        i, j, counts, sv = 0, 0, [], list(self.sorted_values())
        while i < len(sv):
            counts.append(sv.count(sv[i]))
            i += counts[j]
            j += 1
        return counts
    
    def sorted_counts(self):
        self.sc = list(self.counts())
        self.sc.sort()
        return self.sc
    
    def __str__(self):
        return self.n

class PokerHand(Hand):

    def __init__(self, cards):
        """cards is a list of 5 card objects"""
        Hand.__init__(self, cards)
    
    def flush(self):
        return len(set(self.suits())) == 1
    
    def straight(self):
        sv = self.sorted_values()
        if max(self.counts()) != 1:
            return False 
        return ((sv[4] - sv[0] == 4) or sv == [0, 1, 2, 3, 12])

    def rank(self):
        rank = list(self.sorted_counts())
        rank.sort(reverse=True)
        if self.straight():
            rank.append('s')
        if self.flush():
            rank.append('f')
        return HAND_RANK[tuple(rank)]
    
    def index(self):
        c = list(self.counts())
        counts_x = [c[i] for i in range(len(c)) for j in range(c[i])]
        counts_vals = zip(self.sorted_values(), counts_x)
        index, x =zip(*sorted(counts_vals, key=itemgetter(1,0), reverse=True))
        index = list(index)
        if index == [12, 3, 2, 1, 0]:
            index = [3, 2, 1, 0, -1]
        index.insert(0, self.rank()[1])
        return index

def hands_in_long_hand(long_hand):
    """Assumes long_hand is a Hand object containing seven Card objects
       Returns list of all five card combinations"""
    two_cards = [(x, y) for x in range(0, 7) for y in range(0,7) if x < y]
    all_hands = []
    for x, y in two_cards:
        long_hand_copy = list(long_hand)
        del long_hand_copy[x]
        del long_hand_copy[y - 1]
        all_hands.append(PokerHand(long_hand_copy))
    return all_hands

def best_poker_hand(long_hand):
    """Assumes long_hand is a Hand object containing seven Card objects
       Returns the highest ranking Poker Hand"""
    all_hands = hands_in_long_hand(long_hand)
    indexes = []
    for hand in all_hands:
        indexes.append(hand.index())
    best_position = indexes.index(max(indexes))
    best_hand = all_hands[best_position]
    return best_hand

def deal(deck):
    return deck.pop(random.randint(0, len(deck) - 1))

def heads_up(hole_cards1, hole_cards2):
    hole_cards = hole_cards1 + hole_cards2
    deck = list(FULL_DECK)
    board = []
    for c in hole_cards:
        deck.remove(str(c))
    deck = [Card(c) for c in deck]
    for i in range(5):
        board.append(deal(deck))
    hand1 = hole_cards1 + board
    hand2 = hole_cards2 + board
    return Hand(hand1), Hand(hand2)

def equity(hole_cards1, hole_cards2, num_trials):
    """Assumes hole_cards1 and hole_cards2 are two card hands and
         num_trials is an int > 0
       Calculates simulated preflop equity of hole_cards 1 and hole_cards2"""
    equity1 = 0.0
    for i in range(num_trials):
        hand1, hand2 = heads_up(hole_cards1, hole_cards2)
        poker_hand1 = best_poker_hand(hand1)
        poker_hand2 = best_poker_hand(hand2)
        if poker_hand1.index() > poker_hand2.index():
            equity1 += 1
        elif poker_hand1.index() == poker_hand2.index():
            equity1 += 0.5
    avg_eq1 = 100*(equity1/num_trials)
    avg_eq2 = 100 - avg_eq1
    print 'Preflop equity of', hole_cards1, 'vs.', hole_cards2
    print '  is', str(round(avg_eq1, 2)), 'vs.', str(round(avg_eq2, 2))
    
y1 = Card('Ks')
y2 = Card('Ad')
y3 = Card('Qh')
y4 = Card('Qs')
equity(Hand([y1, y2]), Hand([y3, y4]), 10000)
Programming homework and newbie help thread Quote
02-26-2015 , 08:58 AM
Quote:
Originally Posted by Barrin6
Right but that's the same as log(1000) / log (2)?

x = log2 1000 is the same as x = log 1000/ log 2? No?

Actually yea, that both comes out to 9.96.

She did however say that in class we can simplify log2(N) as log(N) but doesn't that changes the number quite a bit?
Big O is not about the constants, but asymptotic behavior.

http://en.wikipedia.org/wiki/Big_O_notation
Programming homework and newbie help thread Quote
02-26-2015 , 11:14 AM
Quote:
Originally Posted by candybar
Big O is not about the constants, but asymptotic behavior.

http://en.wikipedia.org/wiki/Big_O_notation
Binary Search
Quote:
Average performance
log2(N)−1 is the expected number of probes in an average successful search, and the worst case is log2(N), just one more probe.[citation needed] If the list is empty, no probes at all are made. Thus binary search is a logarithmic algorithm and executes in O(log N) time. In most cases it is considerably faster than a linear search. It can be implemented using iteration, or recursion. In some languages it is more elegantly expressed recursively; however, in some C-based languages tail recursion is not eliminated and the recursive version requires more stack space.
I think Barrin6 understood that the big O notation represented the limiting factor. His question was directed at interpreting the limiting factor in completing a binary search IE the magnitude of the limiting factor. Could be wrong.
Programming homework and newbie help thread Quote
02-26-2015 , 01:35 PM
Quote:
Originally Posted by Barrin6
Right but that's the same as log(1000) / log (2)?

x = log2 1000 is the same as x = log 1000/ log 2? No?

Actually yea, that both comes out to 9.96.

She did however say that in class we can simplify log2(N) as log(N) but doesn't that changes the number quite a bit?

it's just a simplification in notation. where k is an arbitrary constant >= 2, O(k^n) < O(n^k) < O(n log n) < O(n) < O(log n) < O(1) regardless of what the base of the log is (there are some exceptions at the extremes) so you can just drop the log base. it's a way to quickly assess your algorithm and compare it to others in the worst-case, as opposed to an exact science. in practice, better big-O doesn't always mean it's a better algorithm (space considerations, and the fact that worst-case isn't necessarily the most important factor).

in practice, yeah binary search has to have a base 2 which is given away by the 'bi' in binary, so the base does matter. compare to something like a B-tree which benefits from having a larger branching factor.

this is a pretty good link I used when studying for my algorithms course: http://bigocheatsheet.com/

Last edited by sthief09; 02-26-2015 at 01:41 PM.
Programming homework and newbie help thread Quote
02-26-2015 , 02:27 PM
Quote:
Originally Posted by adios
I think Barrin6 understood that the big O notation represented the limiting factor. His question was directed at interpreting the limiting factor in completing a binary search IE the magnitude of the limiting factor. Could be wrong.
Um...

Quote:
Originally Posted by Barrin6
Question about big O for binary search.

From what I understand, the Big O for worst case scenario is O(log2N) where the 2 is sub.

So for a 1000 items it would be:
2^x = 1000
xlog 2 = log 1000 //me taking log of both sides
x = log1000/log2
Where x is the number of comparisons for 1000 items.

Am I understanding this correctly?
No.

What sthief09 said basically. I'd add that in practice, what are generally assumed to be constant operations for algorithmic analysis rarely are on real systems.
Programming homework and newbie help thread Quote
02-27-2015 , 01:13 AM
Hi guys

I want to create a ridiculously basic version of an online poker room using java just to improve my skills in developing distributed and concurrent systems, what are the core concepts, technical skills and resources I will need?

Thanks, any tips would be really helpful
Programming homework and newbie help thread Quote
02-27-2015 , 01:38 AM
Quote:
Originally Posted by sthief09
it's just a simplification in notation. where k is an arbitrary constant >= 2, O(k^n) < O(n^k) < O(n log n) < O(n) < O(log n) < O(1) regardless of what the base of the log is (there are some exceptions at the extremes) so you can just drop the log base. it's a way to quickly assess your algorithm and compare it to others in the worst-case, as opposed to an exact science. in practice, better big-O doesn't always mean it's a better algorithm (space considerations, and the fact that worst-case isn't necessarily the most important factor).

in practice, yeah binary search has to have a base 2 which is given away by the 'bi' in binary, so the base does matter. compare to something like a B-tree which benefits from having a larger branching factor.

this is a pretty good link I used when studying for my algorithms course: http://bigocheatsheet.com/
Quote:
Originally Posted by Barrin6
Question about big O for binary search.

From what I understand, the Big O for worst case scenario is O(log2N) where the 2 is sub.

So for a 1000 items it would be:
2^x = 1000
xlog 2 = log 1000 //me taking log of both sides
x = log1000/log2
Where x is the number of comparisons for 1000 items.

Am I understanding this correctly?
hmmm...

My attempt at making this constructive, knowing x often does have value even though it is a scaler quantity IE it has no engineering units.

Last edited by adios; 02-27-2015 at 02:08 AM.
Programming homework and newbie help thread Quote
02-27-2015 , 02:09 AM
Big O isn't so precise.

Take O(1,000,000n) > O(999,999n). The difference is miniscule. We can also say that O(1,000,000n) > O(n), which is true from an arithmetic perspective, but where between 999,999 and 1 do you draw the line between "big" and "small?" You don't and you could think of it as a derivative, which is why it is called "order of growth."
Programming homework and newbie help thread Quote
02-27-2015 , 05:09 AM
The definition is perfectly precise, nothing "fuzzy" about it.

O(10000000 * n) = O(n)
O(n^2.00000001) > O(n^2)
Programming homework and newbie help thread Quote
02-27-2015 , 10:07 AM
Quote:
Originally Posted by adios
My attempt at making this constructive, knowing x often does have value even though it is a scaler quantity IE it has no engineering units.
Constants are important, it's just that you can't go from O(log2(N)) to a constant, which is what he tried to do. Big O also only gives you an asymptotic upper bound. So any algorithm that is O(n) can also be said to be O(n log n), O(n^3), O(2^n) and so on, though for obvious reasons, you usually give the lowest upper bound you can. If a given asymptotic upper bound is also the asymptotic lower bound, you can use the big Theta notation, instead of the big O.
Programming homework and newbie help thread Quote
02-27-2015 , 09:22 PM
Quote:
Originally Posted by plexiq
The definition is perfectly precise, nothing "fuzzy" about it.

O(10000000 * n) = O(n)
O(n^2.00000001) > O(n^2)
I was comparing constants.

I guess a better example is in order:

what is the run-time of n^2 + 1000

let's do some math:

set n = 2

2^2 + 1000
2^2 + log2(1000)
2^2 + 2^10
n^2 + n^10
n^12

so the complexity is O(n^12)


The only thing we are trying to think about is the change of slope as n -> infinity. The 1000 doesn't matter in the above example because that is nothing more than y-intercept and has no effect on the slope of the function.

Doing a bunch of arithmetic calculation can lead to mistakes. The graphs of n^2 and N^2 + 1000 look the same aside from the up-shift: http://www.wolframalpha.com/input/?i=x+^+2+and+x^2+%2B+1000

So, yes, the slope changes with the exponent, but the only term that matters is the leading term.
Programming homework and newbie help thread Quote
02-27-2015 , 09:56 PM
Quote:
Take O(1,000,000n) > O(999,999n). The difference is miniscule. We can also say that O(1,000,000n) > O(n), which is true from an arithmetic perspective, but where between 999,999 and 1 do you draw the line between "big" and "small?" You don't and you could think of it as a derivative, which is why it is called "order of growth."
O(1,000,000n) = O(999,999n) = O(n)

Guess your ">" part confused me. In Big O these are all equal O(n), there is no difference. But after re-reading, I guess that's basically what you were saying anyway.
Programming homework and newbie help thread Quote
03-02-2015 , 01:31 AM
Quote:
Originally Posted by POW
Hi guys

I want to create a ridiculously basic version of an online poker room using java just to improve my skills in developing distributed and concurrent systems, what are the core concepts, technical skills and resources I will need?

Thanks, any tips would be really helpful
Client/Server programming.
Programming homework and newbie help thread Quote
03-05-2015 , 03:34 PM
really getting annoyed with teachers who refuse to teach, but would rather just show off how smart they are.

doing late assignments because the online layout is so tremendously horrible that i never know what's due when, and we had an assignment to do a simple array reverse function. The kicker: no using array notation, use pointers only.

Now, we've covered pointers a fair amount last semester in the intro to C++ class. I felt pretty comfortable with them, even a bit adept.

But this topic is not in our book at all. Nor is it something that's ever been mentioned in class, of which I haven't missed one. Nor is there any example or explanation on our course site for how to do this, or even where to begin.

Somehow, I made it work. I have no clue why the two main things I tried previously didn't work, but I have a working product, so to speak.

So I guess the lesson here is that we're not supposed to be learning anything, just googling our asses off every week and hoping we get lucky enough to figure out whatever problem he's very proud of this time.

For reference:

Code:
char temp[15];
	int i;
	for (i = 0; *(old + i) != NULL; i++)
	{
		*(temp + i) = *(old + i);
	}
	*(temp + i) = '\0';
	i--;
	for (int k = 0; i >= 0; k++, i--)
	{
		*(old + k) = *(temp + i);
	}
In the last for loop, if i used 'i>0' instead of >=, it kept coming up with weird combinations of things that I'm not entirely sure why.

Guess it doesn't matter, cuz it works. = /
Programming homework and newbie help thread Quote
03-05-2015 , 03:52 PM
Quote:
Originally Posted by Anais
really getting annoyed with teachers who refuse to teach, but would rather just show off how smart they are.

doing late assignments because the online layout is so tremendously horrible that i never know what's due when, and we had an assignment to do a simple array reverse function. The kicker: no using array notation, use pointers only.

Now, we've covered pointers a fair amount last semester in the intro to C++ class. I felt pretty comfortable with them, even a bit adept.

But this topic is not in our book at all. Nor is it something that's ever been mentioned in class, of which I haven't missed one. Nor is there any example or explanation on our course site for how to do this, or even where to begin.

Somehow, I made it work. I have no clue why the two main things I tried previously didn't work, but I have a working product, so to speak.

So I guess the lesson here is that we're not supposed to be learning anything, just googling our asses off every week and hoping we get lucky enough to figure out whatever problem he's very proud of this time.

For reference:

Code:
char temp[15];
	int i;
	for (i = 0; *(old + i) != NULL; i++)
	{
		*(temp + i) = *(old + i);
	}
	*(temp + i) = '\0';
	i--;
	for (int k = 0; i >= 0; k++, i--)
	{
		*(old + k) = *(temp + i);
	}
In the last for loop, if i used 'i>0' instead of >=, it kept coming up with weird combinations of things that I'm not entirely sure why.

Guess it doesn't matter, cuz it works. = /
Are you reversing a string or an array? Strings are null-terminated but character arrays can contain whatever. Also, what happens when the array has more than 15 elements?
Programming homework and newbie help thread Quote
03-05-2015 , 04:00 PM
reversing a char array

i just picked 15 randomly because professor gives no direction whatsoever.

example: here's the instructions given in one assignment as a comment, which was never discussed

Code:
//  CHANGE the value
just noting that the value needs changed. To what? Only god and the professor knows!
Programming homework and newbie help thread Quote
03-05-2015 , 04:40 PM
degrees exist to prove you know how to jump through hoops, so you arent learning to program, you are demonstrating your hoop jumping ability, if you accept that it might make the whole experience more tolerable. I mean never has this born more true than now. You can learn absolutely everything you will learn getting your degree online for free, and in much less than 4 years.
Programming homework and newbie help thread Quote
03-05-2015 , 04:58 PM
Quote:
Originally Posted by Anais
The kicker: no using array notation, use pointers only.
Also, I think you're misunderstanding what he means by this.
Programming homework and newbie help thread Quote
03-05-2015 , 05:09 PM
Quote:
Originally Posted by Alobar
degrees exist to prove you know how to jump through hoops, so you arent learning to program, you are demonstrating your hoop jumping ability, if you accept that it might make the whole experience more tolerable. I mean never has this born more true than now. You can learn absolutely everything you will learn getting your degree online for free, and in much less than 4 years.
I already did that once!

Quote:
Originally Posted by candybar
Also, I think you're misunderstanding what he means by this.
I assume it means no using 'old[i]' type stuff
Programming homework and newbie help thread Quote
03-05-2015 , 06:37 PM
Quote:
Originally Posted by Anais
I assume it means no using 'old[i]' type stuff
I don't think he's saying you should avoid the syntactic form old[i] by replacing it with its equivalent, *(old + i), which is pointless. I'm pretty sure he's saying there's some other way to do it that doesn't rely on array indexing altogether and you should do that instead. For example, you can increment the pointer itself as you move instead of incrementing the index and recomputing the pointer by adding to the first pointer.

You're probably right about your teacher not knowing what he's doing, btw.
Programming homework and newbie help thread Quote

      
m