griswolf 304 Veteran Poster

My very first thought is that what you want to do is extremely annoying: You're grabbing the keystream away from the user right while the user is still typing. That's why word processors typically don't do that; they simply mark the (probable) error and let the user do the correction later. I have a "kitchen timer" app that pops up a modal dialog when it goes off, but that dialog accepts keystrokes to set a "pause" time. If I'm typing when it pops up, it steals my input which is extremely annoying twice: Not only does it maybe get set to some pause value and restarted, but the email (or Daniweb comment) that I'm typing into gets whatever is left. Bleaugh.

The other model to think about is how texting apps work: As you type, it displays the word(s) you are probably working on and lets you choose or take the default with a specific keystroke or gesture. This too doesn't back up: It just jumps forward in a manner dependent on the user's actions.

Can you rethink what your intention is?

griswolf 304 Veteran Poster

Pick a programming language. One language. Python is a good choice, but there are many other good choices. Then do some tutorials in that language. When you get stuck, ask (here) for help with what you ran up against. Be sure to show what work you have done.

griswolf 304 Veteran Poster
  1. You need to understand the with statement at my lines 5 and 8: not more important than def, but less likely to be covered in an intro course.

  2. You need to understand how to read the python manual: http://docs.python.org/index.html so as to make best use of the library features. You tried to use randint which is not best suited to this problem. It is mostly a matter of searching and then reading more than just a little bit.

  3. I don't understand "close". I suspect you're using Python in an environment other than the command line. I just use the command line so I'm not the person to ask about how to deal with your environment.

  4. In passing, the Python style guide: Indentation calls for using 4 spaces per indent level. It is very good to just grit your teeth and follow the style guide even if you have a different preference: It is practical, well thought out, everybody understands how to read it (and code reading happens much more than code writing). In particular, because tabs and spaces look the same on the screen, don't ever mix them, but to conserve screen space (width) do prefer spaces alone. Your editor will have a setting to help make that happen.

griswolf 304 Veteran Poster

This is not the most efficient or tight code, but it works. In particular, the function populate(...) could be shorter. In a real world situation populate() should raise a useful error if the files aren't found or aren't as expected (many more lines of code)

I have also deliberately made the output print incorrectly unless you are using Python 3. Note also that raw_input would be incorrect with Python 3.

I've broken the work into two functions and a driver loop. This is typical style for interactive programs; though usually the driver loop is also in its own function which is called from the bottom of the file.

import random
def populate(first_file_name, last_file_name):
    first_names = []
    last_names = []
    with open(first_file_name,'r') as f:
        for line in f:
            first_names.append(line.strip())
    with open(last_file_name,'r') as f:
        for line in f:
            last_names.append(line.strip())
    return first_names, last_names

def print_random_name(first_names,last_names):
    if not first_names:
        first_names = ['Henry']
    if not last_names:
        last_names = ['Jones']
    print(random.choice(first_names), random.choice(last_names))

first_names, last_names = populate('fname.txt','lname.txt')

response = 'y'
while response == 'y':
    print_random_name(first_names,last_names)
    response = raw_input('Print another? ').lower()[0]
griswolf 304 Veteran Poster

I see no need to make the deep copy. Pick an attr, save its value, try to change it, then if it changed, put back the original.

But I'm with lrh9: A function that does two different things is an odd duck: The code that calls it cannot depend on the return value to be what it expects. Why not always return a mutated copy rather than only sometimes?

griswolf 304 Veteran Poster

you use the * operator on the list: attr_gen = attrgetter(*my_list)

griswolf 304 Veteran Poster

If you want to convert lists (tuples) to strings using the same string between each item, such as ZZucker suggests, you should use the join method on a string, as for instance:

my_list = ['one', 'two', 'three', 'the end']
print('\n'.join(my_list))

which results in this output:

one
two
three
the end
griswolf 304 Veteran Poster

If you need to write your own instead of using strftime/strptime, the right answer is probably regular expressions

Regular expression syntax is tricky if you don't already know it (and sometimes, if you do).

import re
timeS = r'(?P<hour>[01]?\d):(?P<minute>[0-5]\d) *((?P<am>[Aa]\.?[Mm].?)|(?P<pm>[Pp]\.?[Mm]\.?))
timeRE = re.compile(timeS)
# ... get somestring "some how"
m = timeRE.match(somestring)
# now look at m.groups, being careful to cope with failure modes

Beware that this regex will pass bad strings such as "19:18 pm" or "12:15 xx" and will not accept a valid time 24 hour time such as "22:23" (easy to fix in timeS if you want it).

BustACode commented: I have got to learn RedEx, as that looks like Chinese to me. +1
griswolf 304 Veteran Poster

The Python break key word is a way to break out of a loop. Just that. So, for instance

result=None
for i in range(1000000000): # really long loop
    result = check_item(i)
    if are_we_done_looking(i, result):
        break # so we don't have to finish the loop
if result:
    generate_report(result)
else:
    print("Useful result not found.")

Please go read an introduction to Python programming. For instance these, though there are probably hundreds.

griswolf 304 Veteran Poster

What you have shown so far will not run because indents matter in Python and your code shows none.

griswolf 304 Veteran Poster

Because Python has 2.x and 3.x versions, it is wise to mention the python version in the module comment or string

It would be nice of you to print a summary of the state of the game in the game loop. Such as print("Correct guesses: %s; Wrong guesses: %s"%(correct_guesses, wrong_guesses)) To avoid having duplicate code to accept the user's guess, I usually use a loop like this

prompt = "Guess a letter " # note the trailing space
while True:
  # display
  print(whatever)
  # ask
  answer = input(prompt)
  # analyze
  # 
  if [I]end_condition[/I]:
     break
  # get ready for next loop, for instance:
  prompt="correct prompt for this loop"

Your line 64 is redundant. Just the if/else is enough.

Usually, you don't require the user to end the game unless the "leave the game" condition is inside the game loop. Or unless the game is running inside a window that will close when the code stops.

the variable name wordTuple is misleading because it is not a tuple: word_from_tuple might make sense, but I would prefer to_guess , or target (I don't expect perfect English). Every variable should be a good name that you never have to think about how it is spelled or what it means. Standard Python naming prefers that classes be named in CamelCase; and that variables and functions should have words_separated_by_underbars. Note that good variable names are much better than comments for self-documenting code: The variable name is seen everywhere it is used, but …

griswolf 304 Veteran Poster

It means that the replace function expects a string (or string-like object) as the first parameter, but you passed it an integer. Line 17 should be board = board.replace(str(comp), "O") .

Note that the semicolons at lines 7, 12, 17 are not needed, though they are not illegal.

griswolf 304 Veteran Poster

A single line. OK then the code reads in the one line from the file, into a variable. Say list_as_string = f.readline() . Then you convert that string into an actual list: actual_list = eval(list_as_string.strip()) and finally, you deal with the list elements however you want. Perhaps

with open('output','w') as ofile
  ofile.write('\n'.join(actual_list)+'\n')

This will only work if

  • The data is in fact all on one line
  • The data is correctly formatted as the string representation of a list

Before you try to use this code, ask yourself if you understand it. If not, read about the with statement and string's join method

griswolf 304 Veteran Poster

First: Please learn to use the CODE button so your code has line numbers, indentation, etc. Very helpful.

Second, I am not sure of the actual format of the file 'temperature data extracted.dat' That is the key. You must deal with that exact format, whatever it is. I begin to think it is just one very long line, with commas and single quote marks in that line (as well as the "real" data). Is that true?

Third: You need to understand what you want, what you have, and what steps to take to convert from 'have' to 'want'. Just waving someone else's code at it is unlikely to work, much less work well.

Fourth and last: It is important when thinking, and when writing, to keep categories clear; A list is not a file is not a string. For example, thinking about a file while calling it a list leads to confusion for both yourself and your readers.

griswolf 304 Veteran Poster

The general opinion is that MySQL is accessible, easy to use. Postgresql is robust, more technical, harder to get started using. I've used both without any real trouble (but the Postgres one was set up and administered by someone else). MS SqlServer Express may be good for you if you are a Microsoft-only kind of programmer (I have no experience) Oracle Express may be good if you have Oracle background already... or want to learn how Oracle works (I have no experience). SqlLite is embeddable, very light weight, file-system based. Works great for medium and smaller projects with "normal" database requirements; but doesn't scale to seriously big data sets in my experience.

griswolf 304 Veteran Poster

Your question did not make it into the English language well enough to understand. Also: Please post your code (which should be short, if possible). Be sure to use the CODE button.

griswolf 304 Veteran Poster

Why a text file? If you simply want to preserve information from session to session, there are three ways

  1. What you suggested: Write the data to a text file
  2. Pickle , Python's object serializer module (actually: Use cPickle)
  3. Use a database

I recommend you use pickle. However if you choose to move ahead with option 1, note the "%r" formatting directive for example:

s = {'one':'uno', 2:'dos', 'cat': 'gato'}
print ("%r"%s)

You can then use the eval builtin function to recover the data. Beware of quote issues.

griswolf 304 Veteran Poster

Actually, the first option (keep track of pennies using a (long) integer) is a better choice almost always. If you use floats representing dollars, you are subject to rounding error even if being very careful. This is because a penny ($0.01 decimal) is in fact an infinite repeating binary fraction, but the register is finite, so there is always a little difference between the intended value and the value actually stored... and worked with in the next step which leads to more error, etc. Whereas if you just store an integer count of pennies, there is no rounding error, no fractions to deal with etc. You can get a nice string value (without commas) using this

def dollarStringFromPennies(p):
  stringpennies = '%d'%p
  return '$%s.%s'%(stringpennies[:-2],stringpennies[-2:]

If you want to make a class to handle all this, it is pretty easy, and you can even provide a __str__(self) method that does the above.

griswolf 304 Veteran Poster

lose the pause, and print the progress indicator at the bottom of the for loop. If that's too fast, keep a counter and print only on every Nth pass through the loop. You don't get a nice steady progression (assuming that the conversions are not equally lengthy), but you do get something that is at least a little bit useful. If you can figure out how, print <space> outside of the loop, then print <backspace>spinner where spinner is an array of these characters: |/-\

Salem commented: nice +17
griswolf 304 Veteran Poster
griswolf 304 Veteran Poster

Confused. Want wider, but not taller... but you are calling it the Y axis? Assuming you misspoke, will this do what you need? (There's a parallel method for the Y axis)

griswolf 304 Veteran Poster

OK, so what you really want is a Programming 101 class, and you have decided Python is a good option for the language (good choice, imo). Alas, I've been programming for (OMG) about 30 years, so I'm not really at all familiar with your situation. A quick web search using introduction to programming python turned up several options in the first page of results

I have not read or used any of these: Caveat emptor

griswolf 304 Veteran Poster

First, you need to use the CODE button to maintain indents when you paste your code (you also get code coloring and line numbers, also good things). With Python particularly indent matters. Here is what I think you meant:

#!/usr/bin/env python

import csv
import random
alpha = 'abcdefghijklmnopqrstuvwxyz'
e = range(0,99)
x = random.sample(alpha,14)
y = random.sample(e,14)

c = csv.writer(open("test2.csv", "wb"))
c.writerow([x])

cr = csv.reader(open("test2.csv","rb"))

for row in cr:
  print row[1], row[1]

print "How many rows?"
l = input()

k = 1

while k < int(l):
  c = csv.writer(open("test.csv", "wb"))
  c.writerow([y])
  cr = csv.reader(open("test.csv","rb"))

  for row in cr:
    k +=1
    print row[k], row[-k]

print "done" 

Second: You get that result because on line 31, the index is out of range (of course): Which in this case means that the length of the row is less than k.

I would also restructure the program so you don't have to keep opening the csv.reader over and over again; and you should close it after each open. I suspect that may be a root of your difficulty?

griswolf 304 Veteran Poster

You want datetime.date.strftime() (and follow the link for details)

griswolf 304 Veteran Poster

For what its worth, my own way to learn something is a little different than what you propose for yourself: I find a project (small, accessible) that fulfills some need of my own, and just start in doing it. The result is a useful tool if all goes well, but even if not, I learn quite a bit. You might be able to find a compromise: A tutorial that creates something you would like to have.

So, what small bit of software do you need? A rolodex tool? Something you can use to keep track of the time you spend on various aspects of your work? A tickler file / reminder service? Something like the Unix "fortune" command, but oriented to your own particular tastes? Maybe something numeric? Pick something that "a proficient programmer" could get done in a week or two, and just start. When you get stuck, ask Daniweb for help.

To make "ask Daniweb for help" work well, you do need to design your project so whatever your problem is can be summarized in a copule dozen (or fewer) lines of code. And, when you are asking about real-world problems (which this is: You want something that actually is helpful), it is important to mention the platform and version of Python that you are using.

Good luck.

griswolf 304 Veteran Poster

Well, there are two issues

  1. You can just do this with introductory level algebra, and you should.
  2. You have a variable OtherSub that is never initialized, and even if it were, you should be saying OtherSub += 1 at line 17 (I think you meant)

For option 1, If I understand correctly, there are only two terms: Fixed and Variable. You can say

Variable == .75 * (Fixed + Variable)
=> Variable == .75*Fixed + .75*Variable # distribute the multiplication
=> .25 Variable == .75 Fixed # subtract .75*Variable from both sides
=> Variable == 3*Fixed # multiply both sides by 4

I would skip option 2.

griswolf 304 Veteran Poster

please i need response !!!

That isn't our problem, but yours. If you want a response, you need to make it easier to respond. What is the exact nature of the trouble your code is in? Does it

  • have a syntax error? What, exactly?
  • not run?
  • not run as expected?
  • do what you expect, but that isn't what you want?
  • something else?

Please read [thread=366794]this thread[/thread] and particularly notice the headings Keep the code short and sweet! and Don't give away code!. The first is for you, the second is why people won't write your homework for you.

griswolf 304 Veteran Poster

I Suggest (strongly) that you work your way through a tutorial or two before you spend much time struggling in the deep end. Python is a very approachable language, but you really do need to get past the syntax and control flow things before you can be successful.
Very basic
Non-programmers start here
Official tutorial

Or Search for one you prefer

griswolf 304 Veteran Poster

... having problems getting it to compile and run.

It is always best if you give the exact compilation error message, so we don't have to guess what the problem might be. And, if you read the error message carefully, thinking about how a compiler author has to be generic, you may find that it is actually quite helpful in explaining what the compiler thinks went wrong. Of course after the first error, the compiler is confused anyway, so ignore the rest.

Just a word to the wise: Indenting your code is very helpful in keeping track of the levels of nesting. Your code apparently lacks that nice feature.

griswolf 304 Veteran Poster

Jython questions are good in this forum. However, you will need to be much more specific about your needs before we can be helpful. The best way to be specific is to tell us exactly what you need to do [B][I]and[/I][/B] to show us the code that you are trying to make work. See [post=1574021]This post[/post]. Be sure to use the CODE button.

griswolf 304 Veteran Poster

hmmm.

a = list(range(10))
a[::-2] = "ZYXWV"
print (a)

I had completely forgotten about the step option for slices.

Lardmeister commented: neat +10
Ene Uran commented: really interesting +13
griswolf 304 Veteran Poster

You probably want a script that looks more like this:

# do any initialization
while True:
  # prompt for user choice
  # clean up the choice: at least one non-white character, lower cased, 
  # if 'q': break
  # if something legal, look up the appropriate fortune (but see 'get' below)
  # otherwise, remind what is legal and continue

functions are very easy. You should work through the tutorial

I would get the fortunes from a dictionary like this:

fortune_dict = {
  '1': 'You will have an interesting life!',
  '2': 'You will have a VERY interesting life!'
  '3': 'You will have a boring life.'
}

Then I'd use get(user_choice, "You are very bad at following instructions") to extract the fortune from the dictionary.

griswolf 304 Veteran Poster

for my purposes (actually need to use some pseudo random things from time to time), I have been quite happy to simply
import random

Of course, if you want to write your own that's different.

The "bestest" random function I ever read about: Get bits from the microphone input. There may be no need to actually hook up a microphone: You are after noise, and the circuit may make enough noise on its own. However random.org does use actual input (atmospheric noise gotten by tuning radio receivers between stations). As you will find if you do some reading, this kind of TRNG (True Random Number Generator) has some good and bad features compared to a PRNG (Pseudo...).

griswolf 304 Veteran Poster

No, someone will not do that.

This forum is to help you do your work. It is not to do your work for you. See [thread=78060]These strong suggestions[/thread], particularly the last item.

vegaseat commented: them are good words +15
griswolf 304 Veteran Poster

The first thing I'd do to change your code is to make the loop while True: and then add if student_name.lower() == 'q': break That allows you to move the input for student name inside the loop (and that means you only write it once). Your inner loop can be a for loop, to avoid hand-incrementing the assignment number: for assignment_number in range(4): You can also use count += 1 to increment the count.

Aside: As you may see, I am a proponent of spelling out variable names in full. This comes from experience doing maintenance on code. Abbreviations are arbitrary. Why 'stdtn' and not 'stnum', for instance? The small amount of extra typing will save you months of looking things up over the course of a career. (IDEs do help with that, but why bother? Self documenting code is better code).

The other problem is the conditions: Only 1-D arrays. To manage that, you need to have a fixed number of either students or grades. You name the array of (fixed number items) any arbitrary way, such as student_[I]N[/I] or grade_[I]N[/I] . You then iterate, as your code shows, over the unfixed variable until done.

griswolf 304 Veteran Poster

You might want to use Counter

griswolf 304 Veteran Poster

You ask them.

Good but insufficient. You ask them in a carefully structured way.

The important questions for you are:

  1. What is the data?
  2. How do I access the data?
  3. What interactions are necessary?
  4. What is the expected outcome (for each interaction)?
  5. How can the expected outcome be verified?
  6. How will we know when we are done?

Hints:

  • You will save a lot of time if you insist on meeting with a single person who represents the customer for your project when you need clarification
    • That person ends up in meetings with the other customers, not you
    • You can grow a good working relationship with one person much easier than with many
  • Your concerns will often seem silly to the customer. Translate if possible.
  • The customer's concerns will often seem silly to you. Be diplomatic.
  • Ask very specific questions. They want "what I want". You have to explain it to the compiler.
BitBlt commented: Nicely put. +6
griswolf 304 Veteran Poster

I have not looked at this at all, beyond a quick 20 second scan of what they claim to offer, but it might be worth exploring: http://www.python-excel.org/

griswolf 304 Veteran Poster

Probably not the best thing to do, though it will apparently work.

Your second question indicates that you have a clue. Class attributes belong to the class itself, whereas instance attributes belong to an instance (of the class). So your lists are in the class: There is only one class "active". By accessing these lists through self, you are obscuring the facts. Legal, but in my opinion confusing.

I would prefer to put the empty lists into the class instance:

class Active(object):
    def __init__(self):
        super(Active,self).__init__()
        self.players = []
        self.goblins = []
        # etc
    def update_creature_list(self)
        self.creaturelist.extend(self.players)
        # etc

I think this is a better option. It allows you to have multiple "active" instances (perhaps to save for an "undo" option, or for some other reason) and it "just seems better to me".

griswolf 304 Veteran Poster

You need to think about the scope of variables. As a general rule, you don't want global variables (though global constants are much more acceptable) since the presence of global variables makes your program harder to understand ("where in the heck did that variable change value?")? As a result, most interactive games have a single container called the "game" or the "board" or "map" or whatever that holds information about the current state of the game: What objects exist, and their locations. The objects themselves know their own state.

In your main function, you create the "world" then enter the game loop: Pass it around to the various other functions which examine it, update it and return it to the main loop, which examines it, lets it report its state, and sends it off again.

griswolf 304 Veteran Poster

Go read Tony's post again, ignoring the Python syntax and looking just at the formula. You don't need anything more than int, I think. (Python operator // is "floor division", which is the normal way that C handles int division). Also go read the links in that thread.

griswolf 304 Veteran Poster

Hmm.

  • unjumble takes a string of characters and finds all the words (or sets of words) that use up all the letters. You need to read in the system dictionary to do it
  • signature takes a text and finds statistics about the text, treating it as just an array of characters. For instance, look for a count of all possible two, three, or four letter sequences (just count the ones you see, of course). You may find that author's signature are pretty consistent across their works, but other authors have different ones. I wonder who really wrote Shakespeare's plays...
  • statistics counts sentence length, phrases per sentence, phrase length, average word length, how many of each kind of punctuation, etc. Compare various authors. Can you correlate some of these measures with "readability"? With "pleasant reading" versus "technical reading"?
  • password creates memorable passwords that are also reasonably crack resistant. Use words from a specified dictionary, and interleave numbers, perhaps. If your input dictionary has different sections for different parts of speech, you can even automate creation of meaningless (syntactically correct) sentences.
  • rolodex uses a text file in some 'easy' format to keep track of related data (name, address, phone, email, birthday, relationship, ...). You only need a search facility; since add, edit, delete can happen in a text editor.
  • billable keeps track of your billable hours for various tasks. For a student, maybe this is called study-time. Keep track of start and stop times for each time segment (starting a new …
griswolf 304 Veteran Poster

Is this the formula found here?

Gribouillis commented: very good question +13
griswolf 304 Veteran Poster

mantissa: Look again. I was suggesting a class that could be used for dealing with very large floating point numbers. The mantissa is not a function but the 'digits' part of a floating point representation. (The exponent is the 'size' part and the sign is the sign). Follow and re-read the IEEE link for more detail.

how would i store them into an int: Any way that works. This is one of the essential parts of the code you propose to write. I have no interest in figuring out the details for you.

griswolf 304 Veteran Poster

It is best to ask a simple question (sometimes they escape from simplicity though) and when the question is either answered or does not matter any more, then mark the thread "solved". That is best because it makes it easier for other Daniweb users. Then, when you have a new question (or have waited more than a week or two), you start a new thread, and we are all better able to find that it is a new thread, and help you with that issue

griswolf 304 Veteran Poster

I think the task at the end of the chapter is for you to discover how to use input() to accept input from the keyboard, and then print "Game Over" and exit.

Think of Python as a little robot that does exactly and only what you tell it to do. If you want it to print something, you give it (part of) a script that says print("something") If you want it to accept input from the keyboard, you give it (part of) a script that says, for instance, user_input = input("Press the <Enter> key to exit.") and it will print that prompt and wait for the keyboard to get some input. You can check what the user entered by looking at the value of user_input but in this simple case, there's no need.

P.S. Please use the (CODE) button so we can see line numbers, code coloring and correct indentation.

Darion commented: thanks :)) +0
griswolf 304 Veteran Poster

Here is your problem:

choice = input("ENTER CHOICE: ")

Changing 'input' to 'raw_input' will solve your problem.

You must probably try this to know the difference:

>>> input( "Enter something: " )
5
5
>>> input( "Enter something else: " )
britanicus

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'britanicus' is not defined
>>>

input expects a valid python expression. Hence back in your case, when the user enters a number from 1 to 5, input evaluates it to integer 1 which is not in choice_menu.keys()

Your point is true only for Python version < 3.x Since OP doesn't tell us what version he uses, we can take a clue from print lines. His are in the 3.x style.

Lardmeister commented: good point +10
griswolf 304 Veteran Poster

Your syntax is just wrong in so many ways. Please visit the Python Tutorials or read the introduction to your Python book again.

griswolf 304 Veteran Poster

IMHO, you found Python easier because:

  • It is interpreted, which makes the compile/test/edit cycle faster
  • It was a tiny problem, so the execution speed did not matter
  • The OP doesn't know how to make best use of C++: Using the standard containers makes C++ almost as expressive as Python (and much faster to run)
  • Python had the advantage of not needing to be backward compatible with C

I do agree: Python is easier.

griswolf 304 Veteran Poster

If you think it would help, another option would be defining the equality operator as a macro.

#define is_equal_to ==

Ugh. You can do such things if you don't like the language, but in my opinion, you should use the language to its (and your) best advantage instead. For instance, does this make sense to you?

#define like {
#define yknow }
#define uh ;
#define whenever for
#define more ++
whenever (i=1 uh i < 5 uh more i) like cout << i << endl uh yknow

I thought not. Neither does any other gratuitous use of macros as syntactic sugar. Your "is_equal_to" took me two tries to type correctly, is 5.5 times longer then '==' and looks illegal to the trained programmer. I re-iterate: "Ugh!"

Ancient Dragon commented: agree completly +36