JoshuaBurleson 23 Posting Whiz

fyi, there is no elseif in python...

JoshuaBurleson 23 Posting Whiz
file1:
/users/ux454500/radpres.tar
/paci/ucb/ux453039/source/amr.12.20.2002.tar~
/paci/ucb/ux453039/source/amr.1.25.2003.htar.idx
/paci/ucb/ux453039/source/amr.1.18.2003.htar.idx

file2:
DIRECTORY /paci/ucb/ux453039/.
FILE /paci/ucb/ux453039/.ktb_ux453039 05/31/2006 17:52:04 09/01/2007 14:25:33
FILE /paci/ucb/ux453039/source/amr.12.20.2002.tar~ 03/10/2005 20:56:50 09/02/2007 10:35:41
FILE /paci/ucb/ux453039/source/amr.1.25.2003.htar.idx 02/23/2007 14:20:15 08/27/2007 14:53:48
FILE /paci/ucb/ux453039/bhsf1.0000.out 02/23/2007 14:20:13 08/27/2007 14:53:48
FILE /users/ux454500/AIX.mpCC.DEBUG.ex 02/23/2007 14:20:13 02/28/2007 14:47:55
DIRECTORY /paci/ucb/ux453039/runs/bondi

file3:
DIRECTORY /paci/ucb/ux453039/.
FILE /paci/ucb/ux453039/.ktb_ux453039 05/31/2006 17:52:04 09/01/2007 14:25:33
FILE /paci/ucb/ux453039/bhsf1.0000.out 02/23/2007 14:20:13 08/27/2007 14:53:48
FILE /users/ux454500/AIX.mpCC.DEBUG.ex 02/23/2007 14:20:13 02/28/2007 14:47:55
DIRECTORY /paci/ucb/ux453039/runs/bondi

and your effort on the code? Please read the forum rules, or for a simplified version; pytony's signature.

JoshuaBurleson 23 Posting Whiz

Also, I tried this with a file someone else posted here a couple days ago, it had a different format, but I feel the idea here is the same, the way I broke it down is just different because of the format:

File:
115     139-28-4313     1056.30

135     706-02-6945      -99.06

143   595-74-5767     4289.07

155     972-87-1379     3300.26
#codes
def extract_second(file):
    col_2=[]
    with open(file) as f:
        for line in f:
            chars=[]
            line=line.split(' ')
            for char in line:
                if char not in ['',' ']:
                    chars.append(char)
            col_2.append(chars[1])
    return col_2



def extract_col(file,col):
    columns=[]
    with open(file) as f:
        for line in f:
            chars=[]
            line=line.split(' ')
            for char in line:
                if char not in ['',' ']:
                    chars.append(char)
            columns.append(chars[col])
    return columns
#results
>>>extract_second('help.txt')
['139-28-4313', '706-02-6945', '595-74-5767', '972-87-1379']
>>>
>>>extract_col('help.txt',0)
['115', '135', '143', '155']

not sure if that helps at all, hope it does. And this worked fine with what I had of yours but it could be much cleaner, I was just messing around with it.

def extract_col(file,col):
    column=[]
    with open(file) as f:
        for line in f:
            chars=[]
            line=line.split('\t')
            for char in line:
                if char not in ['',' ']:
                    chars.append(char)
            chars=' '.join(chars)
            chars=chars.split()
            column.append(chars[col])
    return column

output

extract_col('help2.txt',4)
['pph2_prob', '0.999', '0.999', '0.997']
JoshuaBurleson 23 Posting Whiz

Yes that probably wasn't the best example to use, I wanted to show him how to do what he was trying to do with his for loop, but yes bigredaltoid pytony is quite right [::-1] makes a reversed copy.

Tony, you used to teach python, since reversed(word) isn't really a copy of the word reversed, that would likely work for his professor, correct?

JoshuaBurleson 23 Posting Whiz

You were thinking in the right direction, you just weren't actually doing anything: I'll give you heavy help on one of them and the idea should become quite clear for all of them.

>>> word=input('word: ')
word: hello
>>> word3=''
>>> for letter in word[::-1]:    #which could also be "for letter in reversed(word):"
	word3+=letter
>>>word3
'olleh'

should be able to do it in 9 lines or less.

Also, tell your professor it's far enough into the semester that you should be farther along than string concatenation by now...I learned the majority of what I know in about a month and a half, of course I wasn't stuck in a class for it. Good luck!

JoshuaBurleson 23 Posting Whiz

:) well just so ya know there is a random module with things like shuffle.

import random
f=open('names.txt','r')
names=f.readlines()
f.close()
selected_names=set()
while len(selected_names)<5:
   random.shuffle(names)
   indx=random.randint(0,len(names)-1)
   selected_names.add(names[indx])

a set will get rid of any duplicates. but you could also do a "if key not in list" kind of thing:

selected_names=[]
while len(selected_names)<5:
   random.shuffle(names)
   indx=random.randint(0,len(names)-1)
   if names[indx] not in selected_names:
      selected_names.append(names[indx])
   else:
      pass
JoshuaBurleson 23 Posting Whiz

Show us the code you have so far, you need to show effort around here.

JoshuaBurleson 23 Posting Whiz

what's your pseudocode algorithm? I just want to better understand EXACTLY what you're trying to do.

JoshuaBurleson 23 Posting Whiz

here's an interesting article on the subject "I didn't even know about CubicWeb before it" http://www.itworld.com/software/192113/pillars-python-six-python-web-frameworks-compared

JoshuaBurleson 23 Posting Whiz

Here look at this and look at the code, in fact read what the code is doing step-by-step and look at the output to see if that is what it's doing. Then you'll find what exactly your problem is and we can help you better, I changed the list to make it easier on you.

from string import *

d = dict()
l = []
for i in range(ord('a'),ord('z')+1):
	d[i] = chr(i)
def rotate_word(word,n):
	global l
	for i in range(0,len(word)):
		k = ord(word[i]) + n
		if k > ord('z'):
			k %= ord('z')
		elif k < ord('a'):
			k = k % ord('a') + ord('z') - ord('a') + 1 
		l.append(chr(k))
	return "".join(l)
wordlist = []
c_wordlist = []
r_wordlist = []
fin = ['my','friend']
for word in fin:
    word = word.strip()
    wordlist.append(word)
    c_wordlist.append(word)
    wordlist.sort()
    c_wordlist.sort()
for i in wordlist:
    print(i)
    r_wordlist.append(rotate_word(i,7))
print(r_wordlist[1])	
for word in wordlist:
        for i in r_wordlist:
            print(rotate_word(i,7))
            if i == rotate_word(word,7):
                    print( i," ",word,'\n')

output:

friend
my
myplukt
myplukttwsr
myplukttwsrmypluktwsr'
myplukttwsrmypluktwsr'mypluktwsr
myplukttwsrmypluktwsr'mypluktwsrttwsr'
JoshuaBurleson 23 Posting Whiz

show us the error

JoshuaBurleson 23 Posting Whiz

come on now, obviously you have to assign the variable to a value...

>>> s=10
>>> 
>>> int(s)
10
>>> print(s)
10
>>> s+3
13

but that only answers part of it, first you have to assign s to a string value, HINT: this is done by surrounding the value with '' or "". note that above s was associated with an integer value to begin with, not a string value. Also, you should post what you come up with as a courtesy to show that you put in effort, don't forget to mark threads solved either.

JoshuaBurleson 23 Posting Whiz

I feel like it's more a matter of it being explicit copying than it being implicit pointers, review the zen of python. Don't forget to mark the thread solved etc. Happy we could help.

JoshuaBurleson 23 Posting Whiz

Because you've appended a pointer to that list, so when b changes the pointer sees the change. However if you make a COPY it has its own list. Consider the following interactive experiment:

>>> f=['bob','jack']
>>> d=['bill']
>>> d.append(f)
>>> d
['bill', ['bob', 'jack']]
>>> f.pop()
'jack'
>>> f
['bob']
>>> d
['bill', ['bob']]
>>> f.append('jack')
>>> f
['bob', 'jack']
>>> g=f[:]
>>> g
['bob', 'jack']
>>> f.pop()
'jack'
>>> f
['bob']
>>> g
['bob', 'jack']

and of course:

>>> d.append(g)
>>> d
['bill', ['bob', 'jack']]
>>> f
['bob']
>>> f.append('cow')
>>> f
['bob', 'cow']
>>> g
['bob', 'jack']
>>> d
['bill', ['bob', 'jack']]
JoshuaBurleson 23 Posting Whiz

CLOSE THAT FILE!!! Also, did you notice the stray else at the end?

JoshuaBurleson 23 Posting Whiz

I just finished a program

Well actually you copied the program out of the book, which with no offense to the author, isn't the greatest. I've found a large amount of the code in that book to be a bit buggy, or unclear. The way I got over that was to try to write codes that used the mechanics trying to be taught. Here, try this: write a program that takes a password and if the password is correct prints the password in a Text box, otherwise it prints the number of attempts so far in the Text box. That will be your own original code and it'll probably be easier to see where things go wrong in that as opposed to Michael Dawson's code.

JoshuaBurleson 23 Posting Whiz

Uh oh he's using the same book I was using, lol.

This worked fine for me:

from tkinter import *

class Application(Frame):
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()
        
    def create_widgets(self):
        self.bttn1 = Button(self, text ="I do nothing!")
        self.bttn1.grid()
        self.bttn2 = Button(self, text ="Me too.")
        self.bttn2.grid()
        self.bttn3 = Button(self, text ="Same here..")
        self.bttn3.grid()
        
    
root = Tk()
root.title("Lazy buttons")
root.geometry("200x100")
app = Application(root)
root.mainloop()

your issue was primarily sloppiness, pay attention to your code, you misspelled alot and forgot to call a new instance of events like grid which should've been grid()<--() is important.

Also make sure you're using python 3

JoshuaBurleson 23 Posting Whiz

Choose some prep up from tasks from beginners sticky thread of Vegaseat, maybe it hurts your pride, but I warmly recommend it. Or you can do math code for projecteuler.net (I am tonyjv there, inactive for some months).

How should I invoke another classes methods without using the instance?

JoshuaBurleson 23 Posting Whiz

I'm working on those instance referring classes, I'm just not sure how to access methods otherwise, I guess my learning material is poor. Whenever I try to refer to another classes methods without the instance I get an error claiming the Class has no such method.

JoshuaBurleson 23 Posting Whiz

if you return depth from this function, although it's not a global variable, can it still be used elsewhere in the code? I've never seen the function being called to show the value from it as you did at the end.
also, ouch, my ego :-o

JoshuaBurleson 23 Posting Whiz

Hi
I thought iI would try to teach myself how to program, so sorry if this has been asked before but I could find it.
What I am trying to do is limit an input to of an int to 50 or less with out the program throwing up an error. This is what i have so far :-

#start of input loop
while True:
try:
deep = int(raw_input('Enter Depth in meters :- ',))
break
except ValueError:
print 'Enter whole meters only!(round up if needed!)'
#end of loop

I want deep <= 50 and if it not to loop back to the input line.
Thanks

Ali I see you messed up with the code button, just hit it once and

'you\'ll be able to' input('your code here: ')

this will make it easier to read. Hope we were able to help you.

JoshuaBurleson 23 Posting Whiz

preferred method:

okay=False
depth=0
def dcheck():
    global depth
    global okay
    while not okay:
        try:
            depth=int(input('Enter depth in range(0,50): '))
            if depth in range(0,51):
                print(depth)
                okay=True
                return okay
            else:
                print('Invalid Depth')
                okay=False
        except:
            print('Invalid input')
    
dcheck()
TrustyTony commented: Common.... terrible code, to be honest. -3
JoshuaBurleson 23 Posting Whiz

okay, I understand, I've just yet to use the yield function. Is it essentially the same as return? Also, how would it be possible to be done otherwise?

JoshuaBurleson 23 Posting Whiz

@Gribouillis how does it give more than one attempt after the value error was raised with yours? I'm just curious, I've never seen it that way before.

JoshuaBurleson 23 Posting Whiz

my code only allows the user to mess up by entering an incorrect value once, how would you make it more?

JoshuaBurleson 23 Posting Whiz

also, I would use input instead of raw_input()

JoshuaBurleson 23 Posting Whiz

I would do something like:

depth=int(input('Depth: '))
def depther():
    global depth
    try:
        if depth <=50 and depth>0:
            print(depth)
        else:
            while depth>50 or depth<0:
                print('Incorrect range')
                depth=int(input('Depth: '))
            print(depth)
    except:
        print('Invalid input')
        depth=int(input('Depth: '))
        if depth <=50 and depth>0:
            print(depth)
        else:
            while depth>50 or depth<0:
                print('Incorrect range')
                depth=int(input('Depth: '))
            print(depth)

I defined depth test as a function so it can be reused. Also I used except to cover any error, you may not wish to do this, it's just my preference in cases like this. Now that you know this how do you suppose you would prevent the user from entering a negative depth?

JoshuaBurleson 23 Posting Whiz

honestly I'd package the python installer with it or a link to python with which version you're using, everybody has the Java runtime environment on their computer so having python shouldn't be a big deal.

JoshuaBurleson 23 Posting Whiz

utilizing modules like that may be a little above your "pay-grade" at the moment, I don't mean that offensively, I'd just stick with running the script. I'm not sure why you want to turn it into an .exe right now anyways, any reason?

JoshuaBurleson 23 Posting Whiz

never used PIL, but sounds legit. There you go @Thropian, get back to us with how it turns out.

JoshuaBurleson 23 Posting Whiz

Just so you know it's considered polite to mark the thread as solved so people can use it for future reference, and I'm sure pyTony wouldn't mind an upvote for his help if you feel it's in order.

JoshuaBurleson 23 Posting Whiz

First of all I would personally use pygame for that and livewires(just because) and I would think you'd need to have those parts of the image as separate images, place them on the frame so that they appear to be one image, then you could manipulate them as sprites individually.

JoshuaBurleson 23 Posting Whiz

Gribouillis is right, using classes and creating instances would dramatically cut down on bugs like whether the variable your calling is within global scope or not as it would eliminate the need for several global variables. Just in case you're very new and not aware, to utilize a global variable within a function you need to declare that it is of global scope prior to utilizing it. i.e.

for n in xrange(N):
    global E
    rho = G(Evolve_rho1(rho))
    m = momentum(Evolve_m1(m))
    E = Energy(Evolve_E1(E))
    v_rho = rho_v(Evolve_rho_v(rho))
    v_m = m_v(Evolve_mv(m))
    v_E = E_v(Evolve_Ev(E))
JoshuaBurleson 23 Posting Whiz

Just so you know, I'm also a beginner in python, and programming in general. So I used your assignment to help me with what I'm learning, Classes and methods (non-private for now). I played around a little with the idea of that and here's what I have now.

class Starship(object):
    hp=100
    fuel=100
    ammo=100
    traveled=0
    killed=0

    def __init__(self, name):
        self.name=name
        print('\nAttention Captain of Starship', self.name,'\nit\'s time to make a move!')
    def fireWeapon(self, Enemy):
        try:
            distance=int(input('\nHow far is your target?: '))
            if distance < 10:
                Enemy.hurt(50)
            elif distance > 10 and distance < 51 :
                Enemy.hurt(30)
            elif distance > 50 and distance < 76:
                Enemy.hurt(15)
            else:
                print('Lasers will not do damage at that range')
            Starship.ammo-= 1
            print('\n',Starship.ammo,'percent power left in the lasers')
            print('\nShields at',Starship.hp,'percent captain!')
        except:
            print('Invalid Entry')

    def move(self):
        try:
            lyrs=int(input('How many units would you like to travel, 1-100?: '))
            import random
            obstacle= random.randint(1,101)
            if obstacle != lyrs:
                print('Moved', lyrs,'lightyears')
            else:
                print('There is an enemy in your way!')
                Decisions.__init__()
                
            Starship.fuel-= lyrs//10
            Starship.traveled += lyrs
            return Starship.traveled, Starship.fuel
        except:
           print('\n Invalid Selection')


class Enemy(object):
    enemyhp=100
    damage1=0

    def __init__(self):
        print('I am the enemy!')
        
    def lifeCheck():
        if Enemy.enemyhp< 1:
            print('\n\nEnemy annihalated!!!\n')
            Starship.killed += 1
        else:
            print('\nEnemy shields at', Enemy.enemyhp, 'percent captain!\n')
            print('\nThe enemy is firing back!')
            import random
            chance=random.randint(1,3)
            if chance==1:
                print('\n That was close but the enemy missed!')
            else:
                import random
                attackdamage=random.randint(1,51)
                Starship.hp-=attackdamage
                print('Shit! They got us captain!')
        return Enemy.enemyhp, Starship.killed


    def hurt(damage):
        Enemy.damage1 += damage
        Enemy.enemyhp=Enemy.enemyhp-Enemy.damage1
        Enemy.lifeCheck()

    def location():
        import random
        location=random.randint(1,101)

class Decisions(object):
    def __init__(self):
        choice=input('\nenter your decisions\n1. Attack\n2. Flee\nChoice: …
TrustyTony commented: Only little bit to go: http://en.wikipedia.org/wiki/Star_Trek_%28text_game%29 +13
JoshuaBurleson 23 Posting Whiz

in case you aren't familiar with -= it is the equivalent of saying var = var - int

JoshuaBurleson 23 Posting Whiz

as this is your first post I should remind you it's polite, but not required to reply with your solution or any further questions. To hit "mark thread solved" for people with similar problems in the future. And, no one minds up voting if you find it appropriate, happy coding!

JoshuaBurleson 23 Posting Whiz

and have you tried something like:

def moveForward(fuel):
    path = input("How many feet would you like to move FOREward?")
    obstacle = input("How many feet away is your nearest obstacle?")

    if path - obstacle == path:
        print "You have moved forward",path,"feet."
        fuel-= path
        print('You have', fuel,'units of fuel left')
        return fuel

for each section or possibility?

JoshuaBurleson 23 Posting Whiz

well first of all what is going wrong when you try to run it?