Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesPython Programming
Receive the tools necessary to be the rock star of your field. Our 12-month program teaches you the evolving world of multi-channel marketing as well as the complex issues and opportunities found in the industry.

ASP Free and Iron Speed Designer are giving away $5,500+ in FREE licenses. Iron Speed's RAD CASE toolset can save up to 80% of your coding time. One free license per week, one perpetual license per month!
Download and Activate to enter!

Web development can be a daunting task, even for specialists. There is a lot of information to absorb and a lot of technologies to learn in order to manage a superior website. When trying to learn the ropes, developers need a reliable source to introduce new ideas that can be easily implemented. When working on large projects, even web veterans may run into a technology or an aspect of a technology that they are unfamiliar with.

Learn More!


Download to Enter
| Contest Rules

Tutorials | Forums

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old February 3rd, 2012, 01:32 PM
pullingMyHair pullingMyHair is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2012
Posts: 6 pullingMyHair User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 45 m 47 sec
Reputation Power: 0
How do you pass loop data from one function to another?

I am trying to pass multiple lines of lists from one function to another but I cannot figure out how it is done. Here is the code I have so far:

Code:

def readfile():
    '''Read a text file; return a string holding the text'''
    f = open("numbers.txt", 'r')
    line = f.readlines()             
    f.close()           
    return line  
    
def dataConversion(lines):
           
    lst = []
    for element in lines:
        lst = element.strip()
        lst = map(int, lst)
        print lst        
    return lst

def evenNumberList(lsts):
    print lsts

def main():    

    lines = readfile()   
    lsts = dataConversion(lines)
    doubledList = evenNumberList(lsts)

main()


The output of the dataConversion(lines) function is:

Code:

[4, 3, 8, 8, 5, 7, 6, 0, 1, 8, 4, 0, 2, 6, 2, 6]
[4, 3, 8, 8, 5, 7, 6, 0, 1, 8, 4, 1, 0, 7, 0, 7]
[4, 0, 1, 2, 8, 8, 8, 8, 8, 8, 8, 8, 1, 8, 8, 1]
[4, 5, 5, 2, 7, 2, 0, 4, 1, 2, 3, 4, 5, 6, 7, 7]
[4, 5, 3, 9, 9, 9, 2, 0, 4, 3, 4, 9, 1, 5, 6, 2]
[4, 9, 9, 2, 7, 3, 9, 8, 7, 1, 6, 0, 0]
[4, 9, 9, 2, 7, 3, 9, 8, 7, 0, 0, 1, 7]
[8, 0, 8, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 5, 8, 8, 3, 2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 4, 9, 1, 9, 4, 6, 9, 1, 5, 4, 4, 4, 9, 2, 3]
[5, 4, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 8]
[3, 7, 8, 2, 8, 2, 2, 4, 6, 3, 1, 0, 0, 0, 5]
[3, 7, 1, 4, 4, 9, 6, 3, 5, 3, 9, 8, 4, 3, 1]
[3, 7, 1, 4, 4, 9, 6, 3, 5, 3, 9, 8, 4, 3, 1]
[3, 7, 8, 7, 3, 4, 4, 9, 3, 6, 7, 1, 0, 0, 0]
[3, 7, 8, 7, 3, 4, 4, 9, 3, 6, 7, 1, 0, 0, 1]
[6, 0, 4, 1, 2, 7, 3, 9, 9, 0, 1, 3, 9, 4, 2, 4]
[6, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 7]
[6, 0, 1, 1, 0, 0, 0, 9, 9, 0, 1, 3, 9, 4, 2, 4]


While the input to the evenNumberList(lsts) function is:

Code:
[6, 0, 1, 1, 0, 0, 0, 9, 9, 0, 1, 3, 9, 4, 2, 4]


How do I make them match? I need all of the lines of code in the evenNumberList(lsts) function not just the one line. My professor told me I need to call the function from within a loop but I haven't been able to figure out how to do that.

Reply With Quote
  #2  
Old February 3rd, 2012, 02:40 PM
SuperOscar SuperOscar is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2007
Location: Joensuu, Finland
Posts: 285 SuperOscar User rank is Sergeant (500 - 2000 Reputation Level)SuperOscar User rank is Sergeant (500 - 2000 Reputation Level)SuperOscar User rank is Sergeant (500 - 2000 Reputation Level)SuperOscar User rank is Sergeant (500 - 2000 Reputation Level)SuperOscar User rank is Sergeant (500 - 2000 Reputation Level) 
Time spent in forums: 4 Days 4 h 28 m 58 sec
Reputation Power: 16
Do you actually need the contents of the text file as strings at all? If not, you might consider converting the data to ints while reading the file; as in:

Code:
def readfile():
    buff = []
    for line in open('numbers.txt', 'r'):
        buff.append(map(int, line.strip().split(',')))
    return buff


Assuming each line in the file is of the format “n1, n2, n3...”, where n1 etc. are integer, readfile() would now return a list of lists of integers.

Reply With Quote
  #3  
Old February 3rd, 2012, 04:32 PM
WynnDeezl WynnDeezl is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2011
Posts: 102 WynnDeezl User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 Day 12 h 39 m 48 sec
Reputation Power: 1
Elementate

The reason lsts is only one, and the last, line is because that's the last thing you set lst to before you left dataConversion.

need to make lsts have elements by doing something like this:

Code:
dataConversion(lines):
  lst=[]
  for element in range(len(lines)-1):
    lst[element]=element.strip[]
    lst[element]=map(int,lst)
    print list[element]
return lst


now lsts will have more than one line in it.

Last edited by WynnDeezl : February 3rd, 2012 at 05:09 PM.

Reply With Quote
  #4  
Old February 3rd, 2012, 06:14 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Click here for more information.
 
Join Date: Aug 2011
Posts: 1,075 b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 4 Weeks 1 Day 4 h 41 m 27 sec
Reputation Power: 98
There is a way to "pass loop data"

Here are two solutions. The first demonstrates the yield statement which answers your question.

Code:
# This program complies with newer python 2 and with python 3

# The iterator (a function with a yield statement rather than a return)
# answers your question.  This is a poor choice for algorithm, but works.


def readfile(filename):
    '''Read a text file; return a string holding the text'''
    with open(filename, 'r') as f:
        for line in f:
            yield dataConversion(line)

def dataConversion(line):
    return list(map(int,line.strip()))

def verify(number_to_verify):
    unknown = dataConversion(number_to_verify)
    for valid in readfile('numbers.txt'):
        if valid == unknown:
            return True
    return False

def main():    
    print(('GO TO JAIL','Transact!',)
          [verify(str(input('Credit card number: ')))])

main()


Code:
# This program complies with newer python 2 and with python 3

# Sets are a better solution.

def readfile(filename):
    '''Read a text file; return a string holding the text'''
    with open(filename, 'r') as f:
        return set(map(dataConversion,f))

def dataConversion(line):
    return tuple(map(int,line.strip()))

def verify(number_to_verify,set_of_valid_numbers):
    unknown = dataConversion(number_to_verify)
    return unknown in set_of_valid_numbers

def main():
    valid_numbers = readfile('numbers.txt')
    number_to_verify = str(input('Credit card number: '))
    valid = verify(number_to_verify,valid_numbers)
    print(('GO TO JAIL','Transact!',)[valid])

main()

Reply With Quote
  #5  
Old February 3rd, 2012, 08:12 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Click here for more information.
 
Join Date: Aug 2011
Posts: 1,075 b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 4 Weeks 1 Day 4 h 41 m 27 sec
Reputation Power: 98
Oh!

I see where you're going with this. You want to apply the Luhn test
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
to your file credit card numbers.
That explains your Even and Odd function names as well as your desire to map(int,credit_card_number_string)

Code:
# The iterator (a function with a yield statement rather than a return)
# answers your question.  I would read the whole file all at once, and
# use a list comprehension to process all the luhn tests, and thereby remove
# the explicit loop.  But, this is ok.


def readfile(filename):
    '''Read a text file; return a string holding the text'''
    with open(filename, 'r') as f:
        for line in f:
            yield line

def dataConversion(line):
    return list(map(int,line.strip()))

def luhn(cc):
    en = dataConversion(cc)
    ne = list(reversed(en))
    #odds  =     en[1::2]  or ne[..
    #evens =     en[::2]      ne[...
    # whatever.

def main():    
    for cc in readfile('numbers.txt'):
        print(('Neah ','Yeah ',)[luhn(cc)]+cc)

main()

Reply With Quote
  #6  
Old February 4th, 2012, 09:52 AM
pullingMyHair pullingMyHair is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2012
Posts: 6 pullingMyHair User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 45 m 47 sec
Reputation Power: 0
Yes, the Luhn test

Quote:
Originally Posted by b49P23TIvg
I see where you're going with this. You want to apply the Luhn test
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
to your file credit card numbers.
That explains your Even and Odd function names as well as your desire to map(int,credit_card_number_string)

Code:
# The iterator (a function with a yield statement rather than a return)
# answers your question.  I would read the whole file all at once, and
# use a list comprehension to process all the luhn tests, and thereby remove
# the explicit loop.  But, this is ok.


def readfile(filename):
    '''Read a text file; return a string holding the text'''
    with open(filename, 'r') as f:
        for line in f:
            yield line

def dataConversion(line):
    return list(map(int,line.strip()))

def luhn(cc):
    en = dataConversion(cc)
    ne = list(reversed(en))
    #odds  =     en[1::2]  or ne[..
    #evens =     en[::2]      ne[...
    # whatever.

def main():    
    for cc in readfile('numbers.txt'):
        print(('Neah ','Yeah ',)[luhn(cc)]+cc)

main()


Yes, you are correct that is exactly what I am trying to do! However, I cannot implement a lot of what you have shown me because we haven't learned it yet.

I have written the code so that I can process the first line correctly. So all I should have to do is bring all of the lines into each function to be processed instead of just the one line.

I cannot use the yield because that isn't something we've learned about and I have to create the program using loops and/or list comprehensions.

What I cannot seem to get my head around is passing the multiple lines between functions. I have tried the examples that others have given but they all give me is error telling me AttributeError: 'int' object has no attribute 'strip'


For instance, in this code:

Code:

def readfile():

    buff = []
    for line in open('numbers.txt', 'r'):
        buff.append(map(int, line.strip().split(',')))
    return buff

def dataConversion(lines):

    lst=[]
    for element in range(len(lines)-1):
        lst[element]=element.strip()
        print list[element]
    return lst

def main():    

    lines = readfile()   
    lsts = dataConversion(lines)
    doubledList = evenNumberList(lsts)

main()


It doesn't like lst[element]=element.strip(). However, I thought the strip method was what I was supposed to use to separate each line of credit card numbers into lists of individual numbers. For example [8567034592] into [8,5,6,7,0,3,4,5,9,2]. It works for the program I created to process a single number.

I thought that I would be able to create a loop in my first function, pass the data along to the next function and then everything else would work exactly like it did with the single number, but it is looking more and more that I am going to have to make a loop or list consistent for for each function.

Truth be told, I've done so many things to try and get the program to work that I have become thoroughly confused.

By the way, just so there is no confusion, there is more to my program than what i have posted. However, I didn't want to muddy the waters by posting everything. I'm trying to take it a function at a time.

Reply With Quote
  #7  
Old February 4th, 2012, 11:26 AM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Click here for more information.
 
Join Date: Aug 2011
Posts: 1,075 b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level)b49P23TIvg User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 4 Weeks 1 Day 4 h 41 m 27 sec
Reputation Power: 98
Your program has become a pieced-together patchwork of misunderstood advice. I was going to recommend debug statements to investigate. Let's look at the code instead.

Code:
'''
In readfile

  Why use strip?
    strip removes newlines and accidental white space.
    You avoid the exception raised by int('\n') and int(' ')

  Your input file does not contain commas.
    Remove the extra function call   .split(',')
    SuperOscar included .split(',') merely as an example
    because he guessed what your input might be.
    SuperOscar explained the reasonable guess.  You might
    have observed that your input, one credit card number per line,
    varies from that guess.

  buff contains the digit characters converted to int.
    The map(int,line.strip()) does that.

data conversion---I would choose the short readfile and short dataConversion

  readfile already converted the data.  You could leave your program
  that way.  In this case consider renaming readfile to loadData
  since it does more than just "read the file".  And, since the data
  is already converted, you would discard your dataConversion function.

 XOR

  you could retain your dataConversion program and fix readfile as
  shown, giving you a list of text lines to work with.  And you will
  have to fix dataConversion.  It is a mess in this recent version.
'''

import pprint

def readfile(filename):
    return open(filename,'r').readlines()

def dataConversion(lines):
    return [map(int,line.strip()) for line in lines]

# if you actually think you must use a loop########################
def readfile(filename):                                           #
    f = open(filename,'r')                                        #
    lines = []                                                    #
    for line in f:                                                #
        lines.append(line)                                        #
    return lines                                                  #
                                                                  #
def dataConversion(lines):                                        #
    result = []                                                   #
    digit_set = set('%d'%i for i in range(10))                    #
    for line in lines:                                            #
        stripped_line = line.strip()                              #
        assert set(stripped_line).issubset(digit_set)             #
        # we could expand this conversion into a loop as well     #
        result.append(map(int,stripped_line))                     #
    return result                                                 #

def main():
    lines = readfile('numbers.txt')
    lsts = dataConversion(lines)
    pprint.pprint(lsts)  # or just  print lsts  pprint is far better
    doubledList = evenNumberList(lsts)

main()

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > How do you pass loop data from one function to another?


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.

© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap