Hi,

I have created the following code to check a list and then determine which is true then update the variables associated with the correct if else statement. My problem is it doesn't update any of the variable even if true.

As you can see, the var ch should be the first one chosen and the appropriate variables updated.

Also, is there a more simplified way to check all these occurances? This seems a very long winded way of checking for an occurance.

def bbf(*args):
    '''receive updates to groups'''
    args = list(args)
    index=0
    for arg in args:
        args[index]+=1
        index +=1
    return tuple(args)

def main():
    c=m=b=e=t=s=f=o=0

    ch = ['Fname Sname',1,0,0,0,0]
    if ch[1:5] == [1,0,0,0,0]: 
        c,m,b,e,t = bbf(c,m,b,e,t)
    else:
        if ch[2:5] == [0,0,0,1]: 
            c,m,b,e,f = bbf(c,m,b,e,f)
        else:
            if ch[2:5] == [0,0,1,0]: 
                b,e,t,f,o = bbf(b,e,t,f,o)
            else:
                if ch[2:5] == [0,0,1,1]:
                    e,f,o = bbf(e,f,o)
               else:
                   if ch[2:5] == [0,1,0,0]: 
                       c,m,e,t = bbf(c,m,e,t)
                    else:
                        if ch[2:5] == [0,1,1,0]:
                            c,e,t,f,o = bbf(c,e,t*2,f,o)
                        else:
                            if ch[2:5] == [0,1,1,1]:
                                e,f,o = bbf(e,f,o)
                            else:
                                if ch[2:5] == [0,1,0,1]:
                                    e,f,o = bbf(e,f,o)
                                else:
                                    if ch[2:5] == [1,0,0,0]:
                                        c,m,e,t,s = bbf(c,m,e,t,s)
                                    else:
                                        if ch[2:5] == [1,1,0,0]:
                                            c,m,e,t = bbf(c,m,e,t*2)
                                        else:
                                            if ch[2:5] == [1,1,1,0]:
                                                e,t,f,o = bbf(e,t*2,f,o)
                                            else:
                                                if ch[2:5] == [1,1,1,1]:
                                                    e,f,o = bbf(e,f,o)
                                                else:
                                                    if ch[2:5] == [1,0,1,0]:
                                                        e,t,s,f,o = bbf(e,t,s,f,o)
                                                    else:
                                                        if ch[2:5] == [1,0,0,1]:
                                                            c,m,e,s,f = bbf(c,m,e,s,f)

I hope I have posted it correctly this time.

macca1111

Recommended Answers

All 27 Replies

Member Avatar for Mouche
  1. You don't need the [inlinecode] tags inside your code.
  2. Instead of "else:" and then another "if", you can use "elif":

    name = raw_input("Username: ")
    if name == "frank":
    print "Welcome, president Frank."
    elif name == "steve":
    print "Welcome, vice president Steve."
    else:
    print "You are not authorized to login."

so here, if the first "if" is true, it prints and the program is done. If it's not, then it goes to the "elif." If the "elif" is true, it prints and the program is done. If the "elif" is false, then the "else" is printed and the program is done.

  1. ch[1:5] starts after the first slow and ends before the fifth slot. You want:

    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
    
  2. Product of my editing:

    # increment variables function
    def bbf(*args):
        '''receive updates to groups'''
        args = list(args)
        index=0
        for arg in args:
            args[index]+=1
            index +=1
        return tuple(args)
    
    # initialize variables
    c = 0
    m = 0
    b = 0
    e = 0
    t = 0
    s = 0
    f = 0
    o = 0
    ch = ['Fname Sname',1,0,0,0,0]
    
    # main code
    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
    elif ch[2:6] == [0,0,0,1]:
        c,m,b,e,f = bbf(c,m,b,e,f)
    elif ch[2:6] == [0,0,1,0]:
        b,e,t,f,o = bbf(b,e,t,f,o)
    elif ch[2:6] == [0,0,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,0]:
        c,m,e,t = bbf(c,m,e,t)
    elif ch[2:6] == [0,1,1,0]:
        c,e,t,f,o = bbf(c,e,t*2,f,o)
    elif ch[2:6] == [0,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,0,0]:
        c,m,e,t,s = bbf(c,m,e,t,s)
    elif ch[2:6] == [1,1,0,0]:
        c,m,e,t = bbf(c,m,e,t*2)
    elif ch[2:6] == [1,1,1,0]:
        e,t,f,o = bbf(e,t*2,f,o)
    elif ch[2:6] == [1,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,1,0]:
        e,t,s,f,o = bbf(e,t,s,f,o)
    elif ch[2:6] == [1,0,0,1]:
        c,m,e,s,f = bbf(c,m,e,s,f)
    

I recommend putting comments next to each variable so you know what each one does

Thanks - this work well now, although a bit chunky.

Is it much to scroll through a list from a file in the order

"name1 surname",1,0,0,0,0
"name2 surname",0,1,1,0,0

I have created the file, opened it and split it with the following code.

ch = open('file.txt','r')
ch1 = ch.readlines()

names = []
for L in ch1:
    names.append(L.split())

This is meant to sit above the if elif statements and run through all names from the file.

just wondering how I associate the names folder with my previous code so I can scroll thru several names instead of the one 'test' var ch.

Member Avatar for Mouche

Here's code that works using a list of names called "names." It prints out the values after each iteration. It might be useful to save those values. I'm not too good with file manipulation, so I didn't apply it in this script, but it's in comments.

# increment variables function
def bbf(*args):
    '''receive updates to groups'''
    args = list(args)
    index=0
    for arg in args:
        args[index]+=1
        index +=1
    return tuple(args)

def reset_vars():
    c = 0
    m = 0
    b = 0
    e = 0
    t = 0
    s = 0
    f = 0
    o = 0
    return c,m,b,e,t,s,f,o

# initialize variables
c = 0
m = 0
b = 0
e = 0
t = 0
s = 0
f = 0
o = 0
names = [['Fname Sname',1,0,0,0,0],['Fname Sname',1,0,0,0,1]]

#ch = open('file.txt','r')
#ch1 = ch.readlines()
#for line in ch1:
#    names.append(line.split()) 

for item in names:
    ch = item
    # main code
    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
    elif ch[2:6] == [0,0,0,1]:
        c,m,b,e,f = bbf(c,m,b,e,f)
    elif ch[2:6] == [0,0,1,0]:
        b,e,t,f,o = bbf(b,e,t,f,o)
    elif ch[2:6] == [0,0,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,0]:
        c,m,e,t = bbf(c,m,e,t)
    elif ch[2:6] == [0,1,1,0]:
        c,e,t,f,o = bbf(c,e,t*2,f,o)
    elif ch[2:6] == [0,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,0,0]:
        c,m,e,t,s = bbf(c,m,e,t,s)
    elif ch[2:6] == [1,1,0,0]:
        c,m,e,t = bbf(c,m,e,t*2)
    elif ch[2:6] == [1,1,1,0]:
        e,t,f,o = bbf(e,t*2,f,o)
    elif ch[2:6] == [1,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,1,0]:
        e,t,s,f,o = bbf(e,t,s,f,o)
    elif ch[2:6] == [1,0,0,1]:
        c,m,e,s,f = bbf(c,m,e,s,f)
    print item # print the name
    print "c m b e t s f o" # variable names
    print c,m,b,e,t,s,f,o   # variable values
    c,m,b,e,t,s,f,o = reset_vars() # reset variables

This shows you a more streamlined way to read in and process your file ...

str1 = """'name1 surname',1,0,0,0,0
'name2 surname',0,1,1,0,0
"""

# create the test file
fout = open("file.txt", "w")
fout.write(str1)
fout.close()

names = []
# now read it in a line at a time
for line in open("file.txt", "r"):
    names.append(line.split())

print names  # [["'name1", "surname',1,0,0,0,0"], ["'name2", "surname',0,1,1,0,0"]]

I am still trying to digest all the if/elif statements to figure out if there is a better way.

BTW, it's okay to initialize your variables this way c = m = b = e = t = s = f = o = 0 . I think it is readable. A matter of taste.

Member Avatar for Mouche

I stuck that in the code, and it doesn't work because the values in the lists are strings. So, I added this:

names = []
# read in the names from the file
for line in open("cards.txt", "r"):
    names.append(line.split())
# convert 1s and 0s from strings to integers
for name in names:
    for item in name[2:7]:
        item = int(item)

This doesn't seem to do anything. I'm not sure what's wrong.

I tried a different approach:

i = 0
while i < len(names):
    for index in range(2,7):
        names[i][index] = int(names[i][index])
    i += 1

This method seems to work...


So... what exactly is this for? What do the variables stand for? I'm just curious.

Thanks - this work well now, although a bit chunky.

Is it much to scroll through a list from a file in the order

"name1 surname",1,0,0,0,0
"name2 surname",0,1,1,0,0

I have created the file, opened it and split it with the following code.

ch = open('file.txt','r')
    ch1 = ch.readlines()
    
    names = []
    for L in ch1:
        names.append(L.split())

This is meant to sit above the if elif statements and run through all names from the file.


just wondering how I associate the names folder with my previous code so I can scroll thru several names instead of the one 'test' var ch.

A big thks for all your help. I am very new to Python.

Can I just ask 1 final q.

I am needing to print a report summing all the values. I was hoping to use a function:

def summary()
        print totals for all variables.
        return var

If i put a print summary statement at the end it scrolls through each time through the loop, therefore I though the function would work best.

Would this work???

Member Avatar for Mouche

what do you mean by a summary? Do you want to print the values for each name?

Ex:

['name', 'name2', 1, 0, 0, 0, 0]
c m b e t s f o
1 1 0 1 1 1 0 0
['name2', 'name3', 1, 0, 0, 0, 1]
c m b e t s f o
1 1 0 1 1 1 0 0
['name3', 'name3', 1, 0, 1, 0, 0]
c m b e t s f o
0 0 0 1 1 1 1 1

Or do you want something like this:

And the total for each variable is: c - 5, m - 3, b - 2, e - 9, t - 30, s - 19, f - 2, o - 12.

Or perhaps:

And the total for each variable is:
c - 5
m - 3
b - 2
e - 9
t - 30
s - 19
f - 2
o - 12.

what do you mean by a summary? Do you want to print the values for each name?

Ex:

['name', 'name2', 1, 0, 0, 0, 0]
c m b e t s f o
1 1 0 1 1 1 0 0
['name2', 'name3', 1, 0, 0, 0, 1]
c m b e t s f o
1 1 0 1 1 1 0 0
['name3', 'name3', 1, 0, 1, 0, 0]
c m b e t s f o
0 0 0 1 1 1 1 1

Or do you want something like this:

And the total for each variable is: c - 5, m - 3, b - 2, e - 9, t - 30, s - 19, f - 2, o - 12.

Or perhaps:

And the total for each variable is:
c - 5
m - 3
b - 2
e - 9
t - 30
s - 19
f - 2
o - 12.

Similar to your last example:

Total for c is
Total for m is
...

kind rgds

Member Avatar for Mouche

Tell me how this works for you.

# increment variables function
def bbf(*args):
    '''receive updates to groups'''
    args = list(args)
    index=0
    for arg in args:
        args[index]+=1
        index +=1
    return tuple(args)

# initialize variables
c = m = b = e = t = s = f = o = 0
c_total = m_total = b_total = e_total = t_total = s_total = f_total = o_total = 0
#names = [['Fname Sname',1,0,0,0,0],['Fname Sname',1,0,0,0,1]]

names = []
# read in the names from the file
for line in open("cards.txt", "r"):
    names.append(line.split())

i = 0
while i < len(names):
    for index in range(2,7):
        names[i][index] = int(names[i][index])
    i += 1
        
for item in names:
    ch = item
    # main code
    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
    elif ch[2:6] == [0,0,0,1]:
        c,m,b,e,f = bbf(c,m,b,e,f)
    elif ch[2:6] == [0,0,1,0]:
        b,e,t,f,o = bbf(b,e,t,f,o)
    elif ch[2:6] == [0,0,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,0]:
        c,m,e,t = bbf(c,m,e,t)
    elif ch[2:6] == [0,1,1,0]:
        c,e,t,f,o = bbf(c,e,t*2,f,o)
    elif ch[2:6] == [0,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,0,0]:
        c,m,e,t,s = bbf(c,m,e,t,s)
    elif ch[2:6] == [1,1,0,0]:
        c,m,e,t = bbf(c,m,e,t*2)
    elif ch[2:6] == [1,1,1,0]:
        e,t,f,o = bbf(e,t*2,f,o)
    elif ch[2:6] == [1,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,1,0]:
        e,t,s,f,o = bbf(e,t,s,f,o)
    elif ch[2:6] == [1,0,0,1]:
        c,m,e,s,f = bbf(c,m,e,s,f)
    #print item # print the name               #FOR TESTING#
    #print "c m b e t s f o" # variable names  #FOR TESTING#
    #print c,m,b,e,t,s,f,o   # variable values #FOR TESTING#
    
    # Add the variable values for this name list to the variable totals
    c_total = c_total + c
    m_total = m_total + m
    b_total = b_total + b
    e_total = e_total + e
    t_total = t_total + t
    s_total = s_total + s
    f_total = f_total + f
    o_total = o_total + o

    c = m = b = e = t = s = f = o = 0 # reset variables for next name list

# Print a summary; list totals of the variables
print "And the total for each variable is:"
print "c - %d" % (c_total)
print "m - %d" % (m_total)
print "b - %d" % (b_total)
print "e - %d" % (e_total)
print "t - %d" % (t_total)
print "s - %d" % (s_total)
print "f - %d" % (f_total)
print "o - %d" % (o_total)

...
I tried a different approach:

i = 0
while i < len(names):
    for index in range(2,7):
        names[i][index] = int(names[i][index])
    i += 1

This method seems to work...

Wow, great job, I was in a hurry and didn't give much attention to the strings/integers in the result.

Wow, great job, I was in a hurry and didn't give much attention to the strings/integers in the result.

Now I get this error msg:


Traceback (most recent call last):
File "H:/qqq.py", line 24, in <module>
names[index] = int(names[index])
IndexError: list index out of range

Maybe its my file.txt thats not correctly formatted.

name surname 0 1 0 0 0
...

Is there only spaces between the data pieces???

Member Avatar for Mouche

Yeah, I know that's where the problem is coming from. See... before the data was being imported from a file, we had the name and surname linked in one slot:

with the split() in the file, we get:

So...the error is here:

i = 0
while i < len(names):
    for index in range(2,7):
        names[i][index] = int(names[i][index])
    i += 1

In the "for" statement, I get correct answers with range(2,7) and range(2,6). I get all 0s if it's range(2,5) and your index error with range(2,8). I don't understand why both would work for me and why range(2,7) wouldn't work for macca. Help, vegaseat?

I did a few corrections. My test file string was incorrect, and I should have split at the commas, not the whitespaces. Here is the correction:

str1 = """name1 surname,1,0,0,0,0
name2 surname,0,1,1,0,0
"""

# create the test file
fout = open("file.txt", "w")
fout.write(str1)
fout.close()

names = []
# now read it in a line at a time
for line in open("file.txt", "r"):
    # remove trailing '\n'
    line = line.rstrip()
    names.append(line.split(","))

print names  # [['name1 surname', '1', '0', '0', '0', '0'], ['name2 surname', '0', '1', '1', '0', '0']]


i = 0
while i < len(names):
    for index in range(1,6):
        names[i][index] = int(names[i][index])
    i += 1

print names  # [['name1 surname', 1, 0, 0, 0, 0], ['name2 surname', 0, 1, 1, 0, 0]]

Time to take the boots off, chase the scorpions out of bed, and start "snoren"!

Member Avatar for Mouche

ah! That's what I wanted to do, but I wasn't sure how to use the split() function to do such a thing. Thanks for teaching me something vegaseat.

Working code:

# increment variables function
def bbf(*args):
    '''receive updates to groups'''
    args = list(args)
    index=0
    for arg in args:
        args[index]+=1
        index +=1
    return tuple(args)

# initialize variables
c = m = b = e = t = s = f = o = 0
c_total = m_total = b_total = e_total = t_total = s_total = f_total = o_total = 0
#names = [['Fname Sname',1,0,0,0,0],['Fname Sname',1,0,0,0,1]]

names = []
# now read it in a line at a time
for line in open("file.txt", "r"):
    # remove trailing '\n'
    line = line.rstrip()
    names.append(line.split(","))

i = 0
while i < len(names):
    for index in range(1,6):
        names[i][index] = int(names[i][index])
    i += 1 
        
for item in names:
    ch = item
    # main code
    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
    elif ch[2:6] == [0,0,0,1]:
        c,m,b,e,f = bbf(c,m,b,e,f)
    elif ch[2:6] == [0,0,1,0]:
        b,e,t,f,o = bbf(b,e,t,f,o)
    elif ch[2:6] == [0,0,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,0]:
        c,m,e,t = bbf(c,m,e,t)
    elif ch[2:6] == [0,1,1,0]:
        c,e,t,f,o = bbf(c,e,t*2,f,o)
    elif ch[2:6] == [0,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,0,0]:
        c,m,e,t,s = bbf(c,m,e,t,s)
    elif ch[2:6] == [1,1,0,0]:
        c,m,e,t = bbf(c,m,e,t*2)
    elif ch[2:6] == [1,1,1,0]:
        e,t,f,o = bbf(e,t*2,f,o)
    elif ch[2:6] == [1,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,1,0]:
        e,t,s,f,o = bbf(e,t,s,f,o)
    elif ch[2:6] == [1,0,0,1]:
        c,m,e,s,f = bbf(c,m,e,s,f)
    c_total = c_total + c
    m_total = m_total + m
    b_total = b_total + b
    e_total = e_total + e
    t_total = t_total + t
    s_total = s_total + s
    f_total = f_total + f
    o_total = o_total + o
    c = m = b = e = t = s = f = o = 0

print "And the total for each variable is:"
print "c - %d" % (c_total)
print "m - %d" % (m_total)
print "b - %d" % (b_total)
print "e - %d" % (e_total)
print "t - %d" % (t_total)
print "s - %d" % (s_total)
print "f - %d" % (f_total)
print "o - %d" % (o_total)

File:

name1 surname,1,0,0,0,0
name2 surname,0,1,1,0,0
name3 surname,0,1,0,1,1
name4 surname,0,1,1,0,0
name5 surname,0,0,0,0,1
name6 surname,0,0,1,1,1

New lines must have a space between the name and surname, and then only commas separating the surname and the numbers.

edit: Macca, I know the code I gave you earlier worked, and so does this. I think this code is better, so I would save this to a file to use instead. Let us know if that works for you (in your compiler and in solving your little project).

ah! That's what I wanted to do, but I wasn't sure how to use the split() function to do such a thing. Thanks for teaching me something vegaseat.

Working code:

# increment variables function
def bbf(*args):
    '''receive updates to groups'''
    args = list(args)
    index=0
    for arg in args:
        args[index]+=1
        index +=1
    return tuple(args)

# initialize variables
c = m = b = e = t = s = f = o = 0
c_total = m_total = b_total = e_total = t_total = s_total = f_total = o_total = 0
#names = [['Fname Sname',1,0,0,0,0],['Fname Sname',1,0,0,0,1]]

names = []
# now read it in a line at a time
for line in open("file.txt", "r"):
    # remove trailing '\n'
    line = line.rstrip()
    names.append(line.split(","))

i = 0
while i < len(names):
    for index in range(1,6):
        names[i][index] = int(names[i][index])
    i += 1 
        
for item in names:
    ch = item
    # main code
    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
    elif ch[2:6] == [0,0,0,1]:
        c,m,b,e,f = bbf(c,m,b,e,f)
    elif ch[2:6] == [0,0,1,0]:
        b,e,t,f,o = bbf(b,e,t,f,o)
    elif ch[2:6] == [0,0,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,0]:
        c,m,e,t = bbf(c,m,e,t)
    elif ch[2:6] == [0,1,1,0]:
        c,e,t,f,o = bbf(c,e,t*2,f,o)
    elif ch[2:6] == [0,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [0,1,0,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,0,0]:
        c,m,e,t,s = bbf(c,m,e,t,s)
    elif ch[2:6] == [1,1,0,0]:
        c,m,e,t = bbf(c,m,e,t*2)
    elif ch[2:6] == [1,1,1,0]:
        e,t,f,o = bbf(e,t*2,f,o)
    elif ch[2:6] == [1,1,1,1]:
        e,f,o = bbf(e,f,o)
    elif ch[2:6] == [1,0,1,0]:
        e,t,s,f,o = bbf(e,t,s,f,o)
    elif ch[2:6] == [1,0,0,1]:
        c,m,e,s,f = bbf(c,m,e,s,f)
    c_total = c_total + c
    m_total = m_total + m
    b_total = b_total + b
    e_total = e_total + e
    t_total = t_total + t
    s_total = s_total + s
    f_total = f_total + f
    o_total = o_total + o
    c = m = b = e = t = s = f = o = 0

print "And the total for each variable is:"
print "c - %d" % (c_total)
print "m - %d" % (m_total)
print "b - %d" % (b_total)
print "e - %d" % (e_total)
print "t - %d" % (t_total)
print "s - %d" % (s_total)
print "f - %d" % (f_total)
print "o - %d" % (o_total)

File:

name1 surname,1,0,0,0,0
name2 surname,0,1,1,0,0
name3 surname,0,1,0,1,1
name4 surname,0,1,1,0,0
name5 surname,0,0,0,0,1
name6 surname,0,0,1,1,1

New lines must have a space between the name and surname, and then only commas separating the surname and the numbers.

edit: Macca, I know the code I gave you earlier worked, and so does this. I think this code is better, so I would save this to a file to use instead. Let us know if that works for you (in your compiler and in solving your little project).

I just have one small q left (they seem to keep popping up)

If I want to add more than one to the varibles:

Say, instead of adding 1 to the var below but add another 1. So under certain conditions, I need to add 2 to c and not 1, is there much of a change.

c,m,b,e,t = bbf(c,m,b,e,t

I have tried putting a *2 after the var in the function it ignores it. Adding another function call immediately below it

c=bbf(c) gives me crazy numbers.

Please, I'm positive this will be the last one...

Member Avatar for Mouche

if you just want to add one to C in a couple of the elif blocks, then just use this:

c += 1

I have code that attempts to do the same, but it reveals a couple of discrepancies. I'm wondering whether my code is wrong, or if perhaps there's something in your code, LaMouche

# create test file
f = open("file.txt", "w")
f.write(\
"""name1 surname,1,0,0,0,0
name2 surname,0,1,1,0,0
name3 surname,0,1,0,1,1
name4 surname,0,1,1,0,0
name5 surname,0,0,0,0,1
name6 surname,0,0,1,1,1""")
f.close()

# initialize variables

# represents the variables c,m,b,e,t,s,f,o
variables = [0,0,0,0,0,0,0,0]

# used only for program clarity; in a speed-critical app, we'd
# use indices directly
indices = {'c':0, 'm':1, 'b':2, 'e':3, 't':4, 's':5, 'f':6, 'o':7}
inv_indices = {0:'c', 1:'m', 2:'b', 3:'e', 4:'t', 5:'s', 6:'f', 7:'o'}

# maps the file patterns to the variables to increment.
# a double increment is simply represented as two separate
# values in the list.

# needs '\' at the end of each line to avoid syntax errors!
hashes = {(1,0,0,0,0):['c','m','b','e','t'], \
          (0,0,0,1):['c','m','b','e','f'], \
          (0,0,1,0):['b','e','t','f','o'], \
          (0,0,1,1):['e','f','o'], \
          (0,1,0,0):['c','m','e','t'], \
          (0,1,1,0):['c','e','t','t','f','o'], \
          (0,1,1,1):['e','f','o'], \
          (0,1,0,1):['e','f','o'], \
          (1,0,0,0):['c','m','e','t','s'], \
          (1,1,0,0):['c','m','e','t','t'], \
          (1,1,1,0):['e','t','t','f','o'], \
          (1,1,1,1):['e','f','o'], \
          (1,0,1,0):['e','t','s','f','o'], \
          (1,0,0,1):['c','m','e','s','f'], \
          }
          
names = []
# now read it in a line at a time
for line in open("file.txt", "r"):
    # remove trailing '\n'
    line = line.rstrip()
    names.append(line.split(","))

for name in names:
    #print name
    bits = tuple([int(x) for x in name[1:6]])
    #print bits
    if bits in hashes:
        inc_vars = [indices[x] for x in hashes[bits]]
    elif bits[1:] in hashes:
        inc_vars = [indices[x] for x in hashes[bits[1:]]]
    else:
        print bits, ": Key not found!"
        inc_vars = []
        
    for i in inc_vars:
        variables[i] += 1

for i in range(len(variables)):
    print inv_indices[i], "-", variables[i]

When I run mine on the test file, I get this:

>>> 
(0, 1, 0, 1, 1) : Key not found!  <---
c - 4
m - 4
b - 2
e - 5
t - 5 <---
s - 0
f - 2
o - 1
>>>

As compared to the output from yours, which is

>>> 
And the total for each variable is:
c - 4
m - 4
b - 2
e - 5
t - 3  <---
s - 0
f - 2
o - 1

I think you wanted the keys (0,1,1,0) and (1,1,0,0) to increment the variable 't' twice, yes? When I parse the test file manually assuming that t should be double-incremented, I get t = 5 as the expected value.

Also, what did you want to have happen for keys that aren't in the list? The test file has one: (0,1,0,1,1) that doesn't correspond to any action.

Jeff

I have code that attempts to do the same, but it reveals a couple of discrepancies. I'm wondering whether my code is wrong, or if perhaps there's something in your code, LaMouche

# create test file
f = open("file.txt", "w")
f.write(\
"""name1 surname,1,0,0,0,0
name2 surname,0,1,1,0,0
name3 surname,0,1,0,1,1
name4 surname,0,1,1,0,0
name5 surname,0,0,0,0,1
name6 surname,0,0,1,1,1""")
f.close()

# initialize variables

# represents the variables c,m,b,e,t,s,f,o
variables = [0,0,0,0,0,0,0,0]

# used only for program clarity; in a speed-critical app, we'd
# use indices directly
indices = {'c':0, 'm':1, 'b':2, 'e':3, 't':4, 's':5, 'f':6, 'o':7}
inv_indices = {0:'c', 1:'m', 2:'b', 3:'e', 4:'t', 5:'s', 6:'f', 7:'o'}

# maps the file patterns to the variables to increment.
# a double increment is simply represented as two separate
# values in the list.

# needs '\' at the end of each line to avoid syntax errors!
hashes = {(1,0,0,0,0):['c','m','b','e','t'], \
          (0,0,0,1):['c','m','b','e','f'], \
          (0,0,1,0):['b','e','t','f','o'], \
          (0,0,1,1):['e','f','o'], \
          (0,1,0,0):['c','m','e','t'], \
          (0,1,1,0):['c','e','t','t','f','o'], \
          (0,1,1,1):['e','f','o'], \
          (0,1,0,1):['e','f','o'], \
          (1,0,0,0):['c','m','e','t','s'], \
          (1,1,0,0):['c','m','e','t','t'], \
          (1,1,1,0):['e','t','t','f','o'], \
          (1,1,1,1):['e','f','o'], \
          (1,0,1,0):['e','t','s','f','o'], \
          (1,0,0,1):['c','m','e','s','f'], \
          }
          
names = []
# now read it in a line at a time
for line in open("file.txt", "r"):
    # remove trailing '\n'
    line = line.rstrip()
    names.append(line.split(","))

for name in names:
    #print name
    bits = tuple([int(x) for x in name[1:6]])
    #print bits
    if bits in hashes:
        inc_vars = [indices[x] for x in hashes[bits]]
    elif bits[1:] in hashes:
        inc_vars = [indices[x] for x in hashes[bits[1:]]]
    else:
        print bits, ": Key not found!"
        inc_vars = []
        
    for i in inc_vars:
        variables[i] += 1

for i in range(len(variables)):
    print inv_indices[i], "-", variables[i]

When I run mine on the test file, I get this:

>>> 
(0, 1, 0, 1, 1) : Key not found!  <---
c - 4
m - 4
b - 2
e - 5
t - 5 <---
s - 0
f - 2
o - 1
>>>

As compared to the output from yours, which is

>>> 
And the total for each variable is:
c - 4
m - 4
b - 2
e - 5
t - 3  <---
s - 0
f - 2
o - 1

I think you wanted the keys (0,1,1,0) and (1,1,0,0) to increment the variable 't' twice, yes? When I parse the test file manually assuming that t should be double-incremented, I get t = 5 as the expected value.

Also, what did you want to have happen for keys that aren't in the list? The test file has one: (0,1,0,1,1) that doesn't correspond to any action.

Jeff

Hi,

In your code you have the following:

i = 0
while i < len(names):
    for index in range(1,6):
        names[i][index] = int(names[i][index])
    i += 1

very briefly I was wondering why this is required???

macca

if you just want to add one to C in a couple of the elif blocks, then just use this:

c += 1

I tried your suggestionL

for item in names:
    ch = item
    # main code
    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
        c=+1
    elif ch[2:6] == [0,0,0,1]:
        c,m,b,e,f = bbf(c,m,b,e,f)

but doesn't seem to add the 1 to the end totals

Member Avatar for Mouche

Hmmm... it should. Have you manually checked the values to see if they're correct, Macca?

Jeff, wow. That's great. I like how you did it with the dictionary and such. It also deals with an incorrect "hash."

Macca, even though we've worked a lot with my code, it would be good to just use Jeff's.

Hmmm... it should. Have you manually checked the values to see if they're correct, Macca?

Jeff, wow. That's great. I like how you did it with the dictionary and such. It also deals with an incorrect "hash."

Macca, even though we've worked a lot with my code, it would be good to just use Jeff's.

Hi,

I tried a few different options. I tested the individual var to see if they were increasing correctly but no luck.

I tried a new function:

def s(x):
     s+=1

then call it the same as the other function but no luck.

macca1111

Member Avatar for Mouche

Did you try Jeff's code?

Did you try Jeff's code?

I was feeling a bit unwell last night (some call it a hangover) so I will be testing it today.

Again thks for everything...:cheesy: :cheesy: :cheesy:

I tried your suggestionL

for item in names:
    ch = item
    # main code
    if ch[1:6] == [1,0,0,0,0]:
        c,m,b,e,t = bbf(c,m,b,e,t)
        c=+1
    elif ch[2:6] == [0,0,0,1]:
        c,m,b,e,f = bbf(c,m,b,e,f)

but doesn't seem to add the 1 to the end totals

A little error here use c = c + 1 or c += 1 not c = +1

Member Avatar for Mouche

heh. minor mistake...so, is your code working?

heh. minor mistake...so, is your code working?

Hi,

I have the following code and it works fine. However, the file it reads from, if I want to change it slightly, is there much too it. I have posted the existing code and existing file data and then what I would like it to look like:

children = []
    # now read it in a line at a time
for line in open("h:/food.txt", "r"):
    # remove trailing '\n' and split at ','
    line = line.rstrip()
    children.append(line.split(","))

    
i = 0
while i < len(children):
    for index in range(1,6):
        children[i][index] = int(children[i][index])
    i += 1

# Main algorithm to determine the food groups    
for item in children:
    ch = item
    # main decision code
    if ch[1:6] == [1,0,0,0,0]: # Standard Child
        ce,mi,ba,eg,to = bbf(ce,mi,ba,eg,to)
    elif ch[2:6] == [0,0,0,1]: # Wheat intolerant
        ce,mi,ba,eg,fr = bbf(ce,mi,ba,eg,fr)

I load a file that looks like this:

name surname,1,0,0,0,0
name surname,0,1,0,0,1

I would like it to read a file like:

name surname 1 0 0 0 0
name surname 0 0 0 1 0

the 0's are random and without the ','.

Hmm, going between strings and lists, do some slicing and concatenation might get you there ...

# wants: ['name surname', '1', '0', '0', '0', '0']
str1 = "name surname 1 0 0 0 0"

list1 = str1.split()  # ['name', 'surname', '1', '0', '0', '0', '0']
# first two items of list
a = list1[:2]         # ['name', 'surname']
# remainder of list
b = list1[2:]         # ['1', '0', '0', '0', '0']
# join a to a space separated string and create a list of that string
c = [" ".join(a)]     # ['name surname']
# concatenate the two sublists
d = c + b             # ['name surname', '1', '0', '0', '0', '0']
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.