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

03-05-2015 , 07:11 PM
I'm sure he's a great programmer, can do things I couldn't even imagine

but **** all is he terrible at teaching those things to other human beings
Programming homework and newbie help thread Quote
03-05-2015 , 10:28 PM
Quote:
Originally Posted by Anais
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!
Code:
#include <algorithm>    // std::reverse
#include <string>
#include <string.h>

[void reverse( char * pcReverseIt )
{
	if (!pcReverseIt )
	{
		return;
	}
	std::string s;

	std::reverse_copy(pcReverseIt, (pcReverseIt + strnlen(pcReverseIt,s.max_size())), s.begin());

	strcpy(pcReverseIt, s.c_str());
}
Since it is C++ why not use the standard library it is using pointers without the array notation. Probably not what your prof is looking for but who knows.
Programming homework and newbie help thread Quote
03-06-2015 , 03:13 AM
Quote:
Originally Posted by Anais
I'm sure he's a great programmer, can do things I couldn't even imagine
I would take the other side of that bet.
Programming homework and newbie help thread Quote
03-06-2015 , 11:06 AM
Quote:
Originally Posted by adios
Since it is C++ why not use the standard library it is using pointers without the array notation. Probably not what your prof is looking for but who knows.
He's indicated before that if he doesn't have a library included in an assignment, we're not to add it, so that's out
Programming homework and newbie help thread Quote
03-09-2015 , 08:10 AM
Hey I got the following recursive function f(a,b)

f(a,a) = f(a,1) = 1 ,
f(a,b) = 0 if a< b

f(a,b) = f(a-b,b) + f(a-1,b-1)

One of the questions was to give a simple expression to calculate p(2a,a).

That means that the first expression is 1, but what`s the second expression?
Programming homework and newbie help thread Quote
03-09-2015 , 08:22 AM
I guess you already have
f(2a,a) = 1 + f(2a-1,a-1)

now you can use the rule again on
f(2a-1,a-1)
which gives
f(2a-1,a-1) = f(a,a-1) + f(2a-2, a-2)

I think if you keep doing this long enough you'll get a 1 as the second argument of f and you can use the rule f(a,1)=1

Last edited by Mr.mmmKay; 03-09-2015 at 08:35 AM.
Programming homework and newbie help thread Quote
03-09-2015 , 08:32 AM
lol at that having anything at all to do with programming. Academic comp sci is just the worst.
Programming homework and newbie help thread Quote
03-09-2015 , 08:51 AM
That may be my favorite thing posted in this forum ever, chris
Programming homework and newbie help thread Quote
03-09-2015 , 09:11 AM
The **** thing about comp sci is that it's both an academic and an applied discipline, yet the distinction isn't recognised. 99% of people studying computer science want to learn the applied discipline, yet 99% of people teaching it teach the academic version. The disconnect is enormous. I'm not sure what the situation is now, but I studied at the University of Adelaide, which is the most prestigious university in this city, but the computer science degree was hopeless. 20 years out of date. I've written before about how we spent half a semester learning COBOL before finally getting onto SQL. One of my lecturers - who avoided students seeking help like they had leprosy - had on his resume that he had created his own programming language. Unless your name is Guido van Rossum or Yukihiro Matsumoto, that isn't a brag. It marks you out as someone who has spent their life on useless pursuits nobody cares about.

jmakin's current situation, where he has to write 300 pages of documentation for some fictitious assignment, is frankly farcical. Real engineering degrees have industry placements in their final year. I know nobody wants to babysit pre-grads, but my God, can we get something sorted out so that people actually understand real-world work. When a friend of mine got his first job, he was shortlisted down to 16, whereupon the employer sat the shortlist at computers and made them write programs in Java. Because them having a computer science degree was no guarantee they could actually write code. Like when you think about it, how is the fact that there are CS graduates who can't solve FizzBuzz tolerated? In what universe is that OK? I'd submit that the emphasis on solving abstract recursive problems with no time limit - as opposed to real-world programming problems under real-world conditions - is an issue.
Programming homework and newbie help thread Quote
03-09-2015 , 09:19 AM
This is the dude in question.

Quote:
I am a Senior Lecturer in Computer Science at The University of Adelaide. I am also a Chartered Member of the British Computer Society, a Chartered Engineer, a Chartered Scientist and a member of the ACM. I hold a PhD from St Andrews University in Scotland, for my work in Persistent Object Systems. During this time I was a co-designer and implementor of the orthogonally persistent programming language Napier88 which supports strong typing, parametric polymorphism, a dynamically callable compiler and an integrated persistent run-time environment. My research interests now extend to the computer systems aspects of bioinformatics and to applications of general purpose programmable graphics cards.
Translation: For some reason I was able to convince people to pay me to do useless things, because academia. If you would like, I will pass my useless knowledge on to you.
Programming homework and newbie help thread Quote
03-09-2015 , 10:19 AM
Quote:
Originally Posted by ChrisV
The **** thing about comp sci is that it's both an academic and an applied discipline, yet the distinction isn't recognised. 99% of people studying computer science want to learn the applied discipline, yet 99% of people teaching it teach the academic version.
I'd prefer that they teach just the theory. Because when they try to teach practice,

Quote:
jmakin's current situation, where he has to write 300 pages of documentation for some fictitious assignment, is frankly farcical.
This happens. I'm sure the professor is teaching this because it was the practice of software engineering as they understand it.

Quote:
I'd submit that the emphasis on solving abstract recursive problems with no time limit - as opposed to real-world programming problems under real-world conditions - is an issue.
I think it's better to teach properly seemingly useless topics like recursive functions than to teach poorly seemingly useful topics like software development methodologies and real-world software engineering.

The practice of software engineering has evolved far too quickly and varies too much from one situation to another for it to be taught properly in schools. The theory that was taught 20 years ago is still extremely useful, but whatever "software engineering practices" that were taught 20 years ago likely has little relevance today. Professors don't also magically get to have insight into cutting edge practice. They lag considerably because it takes a long time for good practices to be properly understood, documented standardized and widely accepted.

What we think we know about good software engineering practices barely qualifies as knowledge - it's the equivalent of medieval medicine. There's very little in that body of knowledge that we're confident will withstand the test of time.
Programming homework and newbie help thread Quote
03-10-2015 , 08:47 AM
Quote:
Originally Posted by ChrisV
This is the dude in question.



Translation: For some reason I was able to convince people to pay me to do useless things, because academia. If you would like, I will pass my useless knowledge on to you.
Napier88
Quote:
Napier88 is an orthogonally persistent programming language that was designed and implemented at the University of St Andrews, Scotland. The primary designer was Ron Morrison, whose initial designs were extended and implemented by Fred Brown, Richard Connor, and Al Dearle. Napier88 was ahead of its time in many ways, and was the first robustly implemented language to combine a polymorphic type system with orthogonal persistence. The language was robustly implemented and released to users from both industry and academia; up to 1,000 registered users were recorded in due course. The language, however, was only intended to provide a proof of concept for an experiment in persistent programming; some time after 1989 (the year the first implementation was in fact released) the group's interests moved on and the language was no longer maintained.

Its influence lives on in various other systems. The CORBA type is distinctly recognisable in Napier88's type; Microsoft's CLR uses a similar polymorphic architecture, and Java's parametric types solve some of the same problems of uninstantiated types escaping from their static scope.
So his academic work were precursors to future technological innovation in software development and you are denigrating his work? Should we have a debate on how academic research has been vital and essential to advancing the state of the art in Computer Science and continues to do so?

I basically agree with candybar. There is this sort of yin and yang revolving around teaching theory and practice in software development. I think a university level education should emphasize theory a way lot more than it emphasizes the practice of developing software.

In another thread daveT (I really enjoy daveT's posts btw) sort of took me to task on my endorsing boot camps as a viable alternative to a university education. Seemingly boot camps are all about emphasizing practice a lot more than theory. That is fine but I think it is fair to say that for a significant number of developers learning the practice in software stimulates a great interest in the theory and thus a university education conceivably could happen subsequently.

Last edited by adios; 03-10-2015 at 09:06 AM.
Programming homework and newbie help thread Quote
03-10-2015 , 08:59 AM
So 1,000 people tried out this guy's work, and he's assuming they all worked for Microsoft and Sun Microsystems?

He's implicitly making some post hoc ergo propter hoc fallacy up in there imo

I don't image all academic work is amazing and leads to advances in the industry. And I doubt many researchers or professors would have the balls to claim it does.
Programming homework and newbie help thread Quote
03-10-2015 , 09:14 AM
I think that's bollocks on any number of levels:

- The language was not cutting edge: "was the first robustly implemented language to combine a polymorphic type system with orthogonal persistence" - but not the first to do either of those things separately.

- That future languages implemented things similarly does not imply they were "influenced" by Napier88; there are a finite number of ways to implement things in computer science.

- Even if I concede that Napier88 was a useful enterprise, which I don't, you're not anywhere near attacking my main point, which is that 99% of people taking computer science don't want to invent exciting new languages, and that 99% of people teaching computer science are versed in academic comp sci but 99% of people learning it want to learn applied skills.

-----

candyman:

Quote:
The practice of software engineering has evolved far too quickly and varies too much from one situation to another for it to be taught properly in schools. The theory that was taught 20 years ago is still extremely useful, but whatever "software engineering practices" that were taught 20 years ago likely has little relevance today.
OK, but computer science is hardly unique in this; how houses are built now bears little relation to how they were built a few decades ago. What this proves isn't that programming is uniquely unteachable but exactly what I was saying, which is that it's an applied discipline that ought to be taught by field placements, apprenticeships and so forth.

Edit: Agreed that people like jmakin's professor shouldn't be teaching applied CS, that's once again my whole point, that students need to learn from people who actually work in the field.
Programming homework and newbie help thread Quote
03-10-2015 , 10:20 AM
Quote:
Originally Posted by ChrisV
The language was not cutting edge: "was the first robustly implemented language to combine a polymorphic type system with orthogonal persistence" - but not the first to do either of those things separately.

- That future languages implemented things similarly does not imply they were "influenced" by Napier88; there are a finite number of ways to implement things in computer science.
Agree with both of these, but there's value in trying things out even if they don't result in anything substantial. In academia, very few people will stumble upon something useful, but if no one tries, no one will.

Quote:
OK, but computer science is hardly unique in this; how houses are built now bears little relation to how they were built a few decades ago.
This is why "contemporary house building" is not a popular course of study in universities around the world.

Quote:
which is that it's an applied discipline that ought to be taught by field placements, apprenticeships and so forth.
Which academic department works like this? Do economics departments send their students to do apprenticeships in banks and corporate finance departments, because that's what most econ students end up doing? Do English departments send their students to do apprenticeships with advertising agencies or newspapers or fastfood restaurants or wherever English majors go after school? Nothing stops students from doing internships or learning on the job, but schools are supposed to teach academic knowledge.

Quote:
Agreed that people like jmakin's professor shouldn't be teaching applied CS, that's once again my whole point, that students need to learn from people who actually work in the field.
The problem is that people who work in the field are even more unqualified to teach and hardly able or willing at all. Some people are taught in school and others are self-taught, but I've never met a programmer who said they learned how to program from coworkers or bosses. Also, if you're saying, we, as industry programmers, are responsible for teaching, then why are you blaming schools at all? We can teach new hires regardless of what schools do. This is how it works in almost all industries.

I think most people who complain about what gets taught in CS programs have it completely backwards. Consider the following list:

http://www.ox.ac.uk/admissions/under...ourses-listing

Which area of study do you think corresponds as well as Computer Science does to what graduates do in the real world? For a subject area that is not explicitly vocational, computer science is almost unique in that the theory taught is an extremely important part of what the graduates will go on to do in their career. In fact it's because CS departments do such an amazing job of preparing the students for jobs that they get the flak for not doing even more. Companies too often get students that are ready to contribute at a high level immediately out of school that they get to whine about the others who are not ready. In most areas, no one's ready out of school.
Programming homework and newbie help thread Quote
03-10-2015 , 12:47 PM
Quote:
Originally Posted by Anais
So 1,000 people tried out this guy's work, and he's assuming they all worked for Microsoft and Sun Microsystems?

He's implicitly making some post hoc ergo propter hoc fallacy up in there imo

I don't image all academic work is amazing and leads to advances in the industry. And I doubt many researchers or professors would have the balls to claim it does.
Quote:
Originally Posted by ChrisV
I think that's bollocks on any number of levels:

- The language was not cutting edge: "was the first robustly implemented language to combine a polymorphic type system with orthogonal persistence" - but not the first to do either of those things separately.

- That future languages implemented things similarly does not imply they were "influenced" by Napier88; there are a finite number of ways to implement things in computer science.

- Even if I concede that Napier88 was a useful enterprise, which I don't, you're not anywhere near attacking my main point, which is that 99% of people taking computer science don't want to invent exciting new languages, and that 99% of people teaching computer science are versed in academic comp sci but 99% of people learning it want to learn applied skills.

-----

candyman:



OK, but computer science is hardly unique in this; how houses are built now bears little relation to how they were built a few decades ago. What this proves isn't that programming is uniquely unteachable but exactly what I was saying, which is that it's an applied discipline that ought to be taught by field placements, apprenticeships and so forth.

Edit: Agreed that people like jmakin's professor shouldn't be teaching applied CS, that's once again my whole point, that students need to learn from people who actually work in the field.
Ddi you guys here of this language Smalltalk?
Quote:
There are a large number of Smalltalk variants.[3] The unqualified word Smalltalk is often used to indicate the Smalltalk-80 language, the first version to be made publicly available and created in 1980.

Smalltalk was the product of research led by Alan Kay at Xerox Palo Alto Research Center (PARC); Alan Kay designed most of the early Smalltalk versions, which Dan Ingalls implemented. The first version, known as Smalltalk-71, was created by Ingalls in a few mornings on a bet that a programming language based on the idea of message passing inspired by Simula could be implemented in "a page of code."[1] A later variant actually used for research work is now known as Smalltalk-72 and influenced the development of the Actor model. Its syntax and execution model were very different from modern Smalltalk variants.

....

Influences

Smalltalk was one of many object-oriented programming languages based on Simula.[8] Smalltalk was also one of the most influential programming languages. Virtually all of the object-oriented languages that came after—Flavors,[9] CLOS, Objective-C, Java,[10][11] Python, Ruby,[12] and many others—were all influenced by Smalltalk. Smalltalk was also one of the most popular languages with the Agile Methods, Rapid Prototyping, and Software Patterns[13] communities. The highly productive environment provided by Smalltalk platforms made them ideal for rapid, iterative development.

Smalltalk emerged from a larger program of ARPA funded research that in many ways defined the modern world of computing. In addition to Smalltalk working prototypes of things such as hypertext, GUIs, multimedia, the mouse, telepresence, and the Internet were developed by ARPA researchers in the 1960s.[14][15] Alan Kay (one of the inventors of Smalltalk) also described a tablet computer he called the Dynabook which was essentially a design for an iPad.[16]

Smalltalk environments were often the first to develop what are now common object-oriented software design patterns. One of the most popular is the Model–view–controller pattern for User Interface design. The MVC pattern enables developers to have multiple consistent views of the same underlying data. It's ideal for software development environments, where there are various views (e.g., entity-relation, dataflow, object model, etc.) of the same underlying specification. Also, for simulations or games where the underlying model may be viewed from various angles and levels of abstraction.[17]

In addition to the MVC pattern the Smalltalk language and environment were tremendously influential in the history of the Graphical User Interface (GUI) and the What You See Is What You Get (WYSIWYG) user interface, font editors, and desktop metaphors for UI design. The powerful built-in debugging and object inspection tools that came with Smalltalk environments set the standard for all the Integrated Development Environments, starting with Lisp Machine environments, that came after.[18]
Object-oriented programming
Main article: Object-oriented programming

As in other object-oriented languages, the central concept in Smalltalk-80 (but not in Smalltalk-72) is that of an object. An object is always an instance of a class. Classes are "blueprints" that describe the properties and behavior of their instances. For example, a GUI's window class might declare that windows have properties such as the label, the position and whether the window is visible or not. The class might also declare that instances support operations such as opening, closing, moving and hiding. Each particular window object would have its own values of those properties, and each of them would be able to perform operations defined by its class.

A Smalltalk object can do exactly three things:

Hold state (references to other objects).
Receive a message from itself or another object.
In the course of processing a message, send messages to itself or another object.

The state an object holds is always private to that object. Other objects can query or change that state only by sending requests (messages) to the object to do so. Any message can be sent to any object: when a message is received, the receiver determines whether that message is appropriate. Alan Kay has commented that despite the attention given to objects, messaging is the most important concept in Smalltalk: "The big idea is 'messaging'—that is what the kernel of Smalltalk/Squeak is all about (and it's something that was never quite completed in our Xerox PARC phase)."[19]

Smalltalk is a "pure" object-oriented programming language, meaning that, unlike Java and C++, there is no difference between values which are objects and values which are primitive types. In Smalltalk, primitive values such as integers, booleans and characters are also objects, in the sense that they are instances of corresponding classes, and operations on them are invoked by sending messages. A programmer can change or extend (through subclassing) the classes that implement primitive values, so that new behavior can be defined for their instances—for example, to implement new control structures—or even so that their existing behavior will be changed. This fact is summarized in the commonly heard phrase "In Smalltalk everything is an object", which may be more accurately expressed as "all values are objects", as variables are not.

Since all values are objects, classes themselves are also objects. Each class is an instance of the metaclass of that class. Metaclasses in turn are also objects, and are all instances of a class called Metaclass. Code blocks—Smalltalk's way of expressing anonymous functions—are also objects.[20]
Reflection

Reflection is a term that computer scientists apply to software programs that have the capability to inspect their own structure, for example their parse tree or datatypes of input and output parameters. Reflection was first primarily a feature of interpreted languages such as Smalltalk and Lisp. The fact that statements are interpreted means that the programs have access to information created as they were parsed and can often even modify their own structure.

...
I would say that smalltalk was a revolutionary type language in what stemmed from it. It didn't really get that much use in production as far as the influence it had on subsequent software development was vast and extensive.

Oh yeah what does this have to do with Napier88:
Quote:
A Layered Persistent Architecture for Napier88
Cached

Download as a PDF

Download Links

[www.cs.adelaide.edu.au]

Save to List
Add to Collection
Correct Errors
Monitor Changes

by A. L. Brown , A. Dearle , R. Morrison , D. S. Munro , J. Rosenberg , North Haugh , Ky Ss , South Australia
Citations: 14 - 9 self

Summary
Active Bibliography
Co-citation
Clustered Documents
Version History

BibTeX

@MISC{Brown_alayered,
author = {A. L. Brown and A. Dearle and R. Morrison and D. S. Munro and J. Rosenberg and North Haugh and Ky Ss and South Australia},
title = {A Layered Persistent Architecture for Napier88},
year = {}
}
Bookmark
citeulike Connotea Bibsonomy Del.icio.us Digg Reddit
OpenURL

Abstract

In recent years a range of single programming language systems have been developed that are supported by a persistent store. Examples of such systems include Argus, Galileo, PS-algol and Smalltalk. Although each of these systems is based on a subtly different concept of persistence a common approach is to utilise a layered architecture. This paper presents the design of one such layered architecture that can be used to support a persistent object store where the protection is enforced by a high level type system. The architecture has been used to construct the persistent programming system for Napier88 and is powerful enough to support languages with similar type systems. 2 1 Introduction In recent years a range of single programming language systems have been developed that are supported by a persistent store[atk82,atk83b,ros83,bro85,that86,bro89]. Examples of such systems include Argus[lis84], Galileo[alb85a], PS-algol[psa88] and Smalltalk[gol83]. Although each of these s...
Citations
1335 Smalltalk-80: the language and its implementation - Goldberg, Robson - 1983
1334 The C Programming Language - Kernighan, Ritchie - 1988
375 Recursive functions of symbolic expressions and their computation by machine, part i - McCarthy - 1960
130 The Programming Language Pascal - Wirth - 1971
93 R.Orsini: Galileo: a strongly typed, interactive conceptual language - Albano - 1985
87 Garbage Collection of Linked Data Structures - Cohen - 1981
82 Physical Integrity in a Large Segmented Database", Association for Computing - Lorie - 1977
71 A fast storage allocator - Knowlton - 1965
51 Persistent Object Stores - Brown - 1988
46 Virtual memory, processes, and sharing in multics - Daley, Dennis - 1968
44 The CPOMS persistent object management system - Brown, Cockshott - 1986
29 MONADS-PC: A Capability Based Workstation to Support Software Engineering - Rosenberg, Abramson - 1985
25 The Persistent Abstract Machine - Brown, Connor, et al. - 1988
I think it is safe to say that smalltalk was the catalyst for a lot of other research ideas. To reiterate candybar's point, research by it's very nature is going to result in failure, dead ends, what have you. But when research does "bare fruit" so to speak it can be and often is termendously impactful. Seriously I think you guys are being way too narrow minded. Perhaps the software industry has matured to the point where a course in the short history of software development would be a good thing to gain a better perspective.
Programming homework and newbie help thread Quote
03-10-2015 , 01:15 PM
You're making a fallacious argument. When I say that one guy made a thing that few people know about and even fewer people used and as such had a limited possible impact, I'm not saying all academic endeavors are this way.
Programming homework and newbie help thread Quote
03-10-2015 , 05:38 PM
More to the point, the existence of useful academic CS does not imply that those academics should be teaching the masses to program, any more than medical researchers should teach people to be family doctors. And doctors, by the way? Taught on placements. Because its a practical discipline that you cant just learn in classrooms.
Programming homework and newbie help thread Quote
03-10-2015 , 06:14 PM
Don't know how this thread turned into a debate on pedagogical methods.

Anyway, continuing in the gambling vein, I have moved on from poker to blackjack. over the past couple weeks I've cobbled together an interactive blackjack game. It turned out to be a good exercise in flow control and gave me some practice using objects.

I got a little impatient at the end. For example, I should probably break up the playHand function into more subfunctions, and I should probably write some other functions for the more repetive bits of code (printing results and chip counts). But it feels good to get something nontrivial working.

Feel free to point out what I could do better.

Code:
import random
import string

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]
DECKS_IN_SHOE = 6
VALUES_DICT = dict(zip(VALUES, range(13)))
BANKROLL = 1000
MIN_BET = 5
MAX_HANDS = 4

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(object):
    def __init__(self):
        self.c = []
        self.r = []
        self.v = []
        self.s = []
    def addCard(self, card):
        self.c.append(card)
        self.r.append(card.rank())
        self.v.append(card.value())
        self.s.append(card.suit())
    def cards(self):
        return self.c
    def ranks(self):
        return self.r
    def values(self):
        return self.v
    def suits(self):
        return self.s
    def __str__(self):
        if len(self.c) == 0:
            return '<>'
        name = '<'
        for c in self.c:
            name += str(c) + ','
        return name[0:-1] + '>'
class BlackjackHand(Hand):
    def __init__(self, bet = 0, chips = 0):
        Hand.__init__(self)
        self.b = bet
        if bet != 0:
            chips.add(-bet)
        self.comp = False
        self.result = ''
    def bet(self):
        return self.b
    def score(self):
        scores = []
        for c in self.values():
            if c in range(8):
                scores.append(c + 2)
            elif c in range(8,12):
                scores.append(10)
            else:
                scores.append(11)
        while sum(scores) > 21 and 11 in scores:
            scores[scores.index(11)] = 1
        return sum(scores)
    def addBet(self, bet, chips):
        self.b += bet
        chips.add(-bet)
    def complete(self, status = False):
        if status:
            self.comp = True
        return self.comp
    def getResult(self):
        return self.result
    def addResult(self, result):
        self.result = result
    def upcard(self):
        return self.cards()[1]
class Chips(object):
    def __init__(self, money):
        self.m = money
    def value(self):
        return self.m
    def add(self, amount):
        self.m += amount
    def __str__(self):
        return str(self.m)
class Shoe(object):
    def __init__(self, number, deck = FULL_DECK):
        self.c = [Card(c) for c in deck] * number
        self.n = number
    def cards(self):
        return self.c
    def deal(self, announce = True):
        newCard = self.c.pop(random.randrange(len(self.c)))
        if announce:
            print 'The next card is', newCard
        return newCard
    def __str__(self):
        return str(self.n) + ' deck shoe'

def getYesNo():
    while True:
        choice = raw_input('(Enter Y or N): ')
        if choice.upper() in ('Y', 'N'):
            return choice.upper()
        else:
            print choice, 'is not a valid choice.'

def startGame(BANKROLL, DECKS_IN_SHOE):
    chips = Chips(BANKROLL)
    shoe = Shoe(DECKS_IN_SHOE)
    print 'Welcome to the blackjack table.'
    print 'You have', chips.value(), 'chips.'
    return chips, shoe

def continuePlaying(chips, MIN_BET):
    while True:
        choice = raw_input('(Enter bet for next hand or 0 to quit): ')
        try:
            bet = int(choice)
        except ValueError:
            print 'Bet amount must be a positive integer.'
            continue
        if bet >= 0 and bet <= chips.value() and bet % MIN_BET == 0:
            return bet
        elif bet < 0:
            print 'Bet amount must be positive.'
        elif bet > chips.value():
            print 'The maximum amount that you can bet is', chips.value()
        else:
            print 'You must bet in increments of', MIN_BET

def newHand(bet, chips, shoe):
    dealerhand = BlackjackHand()
    hand = BlackjackHand(bet, chips)
    for i in range(2):
        for h in (hand, dealerhand):
            h.addCard(shoe.deal(False))
    print 'Your hand is:', hand
    print 'Your score is:', hand.score()
    if hand.score() == 21:
        print 'You have blackjack!'
    print "Dealer's upcard is:", dealerhand.cards()[1]
    return dealerhand, hand

def insurance(dealerhand, hand, chips):
    if dealerhand.ranks()[1] == 'A':
        print "Dealer's upcard is an Ace."
        print 'Would you like insurance?'
        choice = getYesNo()
        if choice == 'Y':
            half = hand.bet()/2.0
            chips.add(-half)
            print 'Buying insurance for', half
            print 'You have', chips.value(), 'chips remaining.'
        else:
            print 'You have chosen not to purchase insurance.'
        print 'Dealer is checking for blackjack ...'
        if dealerhand.score() == 21:
            hand.complete(True)
            print 'Dealer has blackjack!'
            if choice == 'Y':
                print 'You win', 2*half, 'on your insurance bet of', half    
                chips.add(3*half)
            print 'You lose your bet of', hand.bet(), 'on your hand'
            print 'You have', chips.value(), 'chips remaining.'
        else:
            print 'Dealer does not have blackjack.'
            if choice == 'Y':
                print 'You lose your insurance bet of', half
    return hand.complete()

def checkBlackjack(dealerhand, hand, chips):
    if dealerhand.ranks()[1] in 'TJQK':
        print 'Checking for dealer blackjack.'
        if dealerhand.score() == 21:
            print 'Dealer has blackjack!'
            if hand.score() == 21:
                hand.addResult('push')
                chips.add(hand.bet())
                print 'Result of hand is push.'
                print 'Your bet of', hand.bet(), 'is returned.'
            else:
                hand.addResult('lose')
                print 'You lose your bet of', hand.bet(), 'on your hand'
            print 'You have', chips.value(), 'chips remaining.'
            hand.complete(True)
        else:
            print 'Dealer does not have blackjack.'
    if hand.score() == 21 and dealerhand.score() != 21:
        hand.addResult('win')
        print 'You win', 1.5*hand.bet(), 'on your bet of', hand.bet()
        chips.add(2.5*hand.bet())
        print 'You have', chips.value(), 'chips remaining.'
        hand.complete(True)
    return hand.complete()

def surrender(hand, chips):
    print 'Would you like to surrender?'
    choice = getYesNo()
    if choice == 'Y':
        hand.addResult('surrender')
        hand.complete(True)
        half = hand.bet()/2.0
        #print half
        chips.add(half)
        print 'Hand is surrendered and', half, 'of your bet of', hand.bet(),
        print 'is returned to you.'
        print 'You have', chips.value(), 'chips remaining.'
    else:
        print 'You have chosen not to surrender.'
    return hand.complete()

def equal_values(hand):
    if hand.ranks()[0] == hand.ranks()[1]:
        return True
    elif hand.ranks()[0] in 'TJQK' and hand.ranks()[1] in 'TJQK':
        return True
    return False

def allowSplit(hands, index, chips, MAX_HANDS):
    if len(hands) >= MAX_HANDS:
        return False
    if not equal_values(hands[index]):
        return False
    if hands[index].ranks()[0] == 'A' and len(hands) > 1:
        return False
    if chips.value() < hands[index].bet():
        return False
    print 'Would you like to split your hand?'
    choice = getYesNo()
    if choice == 'N':
        return False
    else:
        return True

def split(hands, chips, shoe, index):
    order = ['first', 'second', 'third', 'fourth']
    chips.add(hands[index].bet())
    s1, s2 = BlackjackHand(), BlackjackHand()
    for s, i in [(s1, 0), (s2, 1)]:
        s.addBet(hands[index].bet(), chips)
        s.addCard(hands[index].cards()[i])
    print 'Splitting', hands[index], 'into', s1, 'and', s2
    s1.addCard(shoe.deal())
    print 'Your', order[index], 'hand is now', s1, 'and your score is now',
    print s1.score()
    hands[index] = s1
    hands.append(s2)
    if s1.ranks()[0] == 'A':
        s2.addCard(shoe.deal())
        print 'Your', order[index + 1], 'hand is now', s2,
        print 'and your score is now', s2.score()
        s1.complete(True)
        s2.complete(True)

def doubleDown(hand, chips, shoe):
    ddStatus = False
    print 'Would you like to double down on', hand, '?'
    choice = getYesNo()
    if choice == 'Y':
        if chips.value() == 0:
            print "You can't double down because you don't have any", 
            print 'more chips.'
        else:
            add = min(hand.bet(), chips.value())
            print 'Doubling down for', add
            hand.addBet(add, chips)
            print 'Total bet on', hand, 'is', hand.bet(),
            print 'and you have', chips.value(), 'chips remaining.'
            hand.addCard(shoe.deal())
            print 'Your hand is now', hand, 'and your score is now', 
            print hand.score()
            if hand.score() > 21:
                hand.addResult('bust')
                print 'Sorry, you bust.'
                print 'You lose your bet of', hand.bet()
                print 'You now have', chips.value(), 'chips'
            hand.complete(True)
    else:
        print 'You have declined to double down.'
    return hand.complete()

def hit(hand, chips, shoe):
    stand = False
    while True:
        print 'Would you like another card?'
        choice = getYesNo()
        if choice == 'Y':
            hand.addCard(shoe.deal())
            print 'Your hand is now', hand, 'and your score is now',
            print hand.score()
            if hand.score() > 21:
                hand.addResult('bust')
                print 'Sorry, you bust.'
                print 'You lose your bet of', hand.bet()
                print 'You now have', chips.value(), 'chips'
        else:
            stand = True
            print 'You have chosen to stand pat with', hand
        if stand or hand.score() > 21:
            break

def playHand(bet, chips, shoe, MAX_HANDS):
    hands = []
    index = 0
    dealerhand, playerhand = newHand(bet, chips, shoe)
    hands.append(playerhand)
    if not insurance(dealerhand, playerhand, chips):
        if not checkBlackjack(dealerhand, playerhand, chips):
            surrender(playerhand, chips)
    while True:
        if hands[-1].complete():
            break
        if len(hands[index].cards()) == 1:
            order = ['first', 'second', 'third', 'fourth']
            hands[index].addCard(shoe.deal())
            print 'Your',  order[index], 'hand is now', hands[index], 
            print 'and your score is now', hands[index].score()
        if allowSplit(hands, index, chips, MAX_HANDS):
            split(hands, chips, shoe, index)
        if hands[index].complete():
            continue
        if doubleDown(hands[index], chips, shoe):
            continue
        hit(hands[index], chips, shoe)
        hands[index].complete(True)
        index += 1
    print "Dealer's hand is", dealerhand,
    print "and dealer's score is", dealerhand.score()
    if '' in [h.getResult() for h in hands]:
        while dealerhand.score() < 17:
            dealerhand.addCard(shoe.deal())
            print "Dealer's hand is now", dealerhand, "and dealer's score is now",
            print dealerhand.score()
        if dealerhand.score() <= 21:
            print 'Dealer stands pat with', dealerhand
        else:
            print 'Dealer busts.'
        for hand in hands:
            if hand.getResult() == '':
                if hand.score() > dealerhand.score() or dealerhand.score() > 21:
                    hand.addResult('win')
                    print 'You win', hand.bet(), 'on your bet of', hand.bet()
                    chips.add(2*hand.bet())
                elif hand.score() == dealerhand.score():
                    hand.addResult('push')
                    chips.add(hand.bet())
                    print 'Result of hand is push.'
                    print 'Your bet of', hand.bet(), 'is returned.'
                else:
                    hand.addResult('lose')
                    print 'You lose your bet of', hand.bet(), 'on your hand'
        print 'You now have', chips.value(), 'chips.'
                
def main():
    chips, shoe = startGame(BANKROLL, DECKS_IN_SHOE)
    shoe_length = len(shoe.cards())
    while True:
        bet = continuePlaying(chips, MIN_BET)
        if bet == 0:
            break
        playHand(bet, chips, shoe, MAX_HANDS)
        if len(shoe.cards()) < max(shoe_length/4.0, 16):
            shoe = Shoe(DECKS_IN_SHOE)
            print 'Shuffling shoe.'
        if chips.value() <= 0:
            print 'Try again when you have more money.'
            break
    print 'Thanks for playing!'
    
main()
Programming homework and newbie help thread Quote
03-10-2015 , 06:46 PM
Quote:
Originally Posted by ChrisV
More to the point, the existence of useful academic CS does not imply that those academics should be teaching the masses to program, any more than medical researchers should teach people to be family doctors. And doctors, by the way? Taught on placements. Because its a practical discipline that you cant just learn in classrooms.
Everyone learns on the job. Doctors aren't any different - it's just that their learning on the job is systematically tracked to satisfy licensing requirements. Not sure what your point is - exactly what are you advocating that others do? In medicine, you have to take a ton of classes taught by academics to get to the point where you're learning by working with a real human patient. In programming, there are no gatekeepers and you can learn by doing or on the job or whatever without taking any class whatsoever. It just happens to be that CS departments are popular because students prefer to learn from academics.
Programming homework and newbie help thread Quote
03-10-2015 , 07:43 PM
Actually planning on doing a blackjack game sometime in the near future for ****s and giggles, mostly because hand comparisons seem much simpler than poker or hold em
Programming homework and newbie help thread Quote
03-10-2015 , 10:24 PM
Quote:
Originally Posted by econophile
Feel free to point out what I could do better.

Code:
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(object):
    def __init__(self):
        self.c = []
        self.r = []
        self.v = []
        self.s = []
    def addCard(self, card):
        self.c.append(card)
        self.r.append(card.rank())
        self.v.append(card.value())
        self.s.append(card.suit())
    def cards(self):
        return self.c
    def ranks(self):
        return self.r
    def values(self):
        return self.v
    def suits(self):
        return self.s
    def __str__(self):
        if len(self.c) == 0:
            return '<>'
        name = '<'
        for c in self.c:
            name += str(c) + ','
        return name[0:-1] + '>'
class BlackjackHand(Hand):
    def __init__(self, bet = 0, chips = 0):
        Hand.__init__(self)
        self.b = bet
        if bet != 0:
            chips.add(-bet)
        self.comp = False
        self.result = ''
    def bet(self):
        return self.b
    def score(self):
        scores = []
        for c in self.values():
            if c in range(8):
                scores.append(c + 2)
            elif c in range(8,12):
                scores.append(10)
            else:
                scores.append(11)
        while sum(scores) > 21 and 11 in scores:
            scores[scores.index(11)] = 1
        return sum(scores)
    def addBet(self, bet, chips):
        self.b += bet
        chips.add(-bet)
    def complete(self, status = False):
        if status:
            self.comp = True
        return self.comp
    def getResult(self):
        return self.result
    def addResult(self, result):
        self.result = result
    def upcard(self):
        return self.cards()[1]
class Chips(object):
    def __init__(self, money):
        self.m = money
    def value(self):
        return self.m
    def add(self, amount):
        self.m += amount
    def __str__(self):
        return str(self.m)
class Shoe(object):
    def __init__(self, number, deck = FULL_DECK):
        self.c = [Card(c) for c in deck] * number
        self.n = number
    def cards(self):
        return self.c
    def deal(self, announce = True):
        newCard = self.c.pop(random.randrange(len(self.c)))
        if announce:
            print 'The next card is', newCard
        return newCard
    def __str__(self):
        return str(self.n) + ' deck shoe'
The first thing that jumps out at me is the use of one-letter variable names. You should almost never use those except for cases like x, y, z in coordinates, etc. Use meaningful names for everything.
Programming homework and newbie help thread Quote
03-10-2015 , 11:55 PM
Quote:
Originally Posted by econophile
Don't know how this thread turned into a debate on pedagogical methods.

Anyway, continuing in the gambling vein, I have moved on from poker to blackjack. over the past couple weeks I've cobbled together an interactive blackjack game. It turned out to be a good exercise in flow control and gave me some practice using objects.

I got a little impatient at the end. For example, I should probably break up the playHand function into more subfunctions, and I should probably write some other functions for the more repetive bits of code (printing results and chip counts). But it feels good to get something nontrivial working.

Feel free to point out what I could do better.
I think a lot, maybe all, of the methods belong in a class, call it BlackJack that takes bankroll, decks as args?, with state of the game being variables of the class as well.
Programming homework and newbie help thread Quote
03-11-2015 , 09:47 AM
Quote:
Originally Posted by Benholio
The first thing that jumps out at me is the use of one-letter variable names. You should almost never use those except for cases like x, y, z in coordinates, etc. Use meaningful names for everything.
Yeah, that's good advice. I was running into errors when I had used the same name for a data attribute (e.g., self.values) and a method (e.g., values()). So I switched the names of a lot of the data attributes to single letters. But I guess a better solution would be to name the methods something like getValues() so that I can still use a descriptive name for the attribute.
Programming homework and newbie help thread Quote
03-11-2015 , 09:53 AM
Quote:
Originally Posted by anfernee
I think a lot, maybe all, of the methods belong in a class, call it BlackJack that takes bankroll, decks as args?, with state of the game being variables of the class as well.
My previous programming experience has all been procedural, so OOP is new to me. The textbook I've been using introduced the concept, but didn't really make it clear to me when and when not to use objects.

When I was putting this program together, it did seem more convenient to define methods for things like cards and hands. And cards, hands, chips, and shoes all made sense to me to think of as objects. But I hadn't considered thinking of the game itself as an object. (Although now that you mention it I have an idea of how that might work.)

Is the general philosophy of OOP to make as many things objects as possible? Why is this preferred to the "procedural" approach?
Programming homework and newbie help thread Quote

      
m