How do you pass loop data from one function to another?
Discuss How do you pass loop data from one function to another? in the Python Programming forum on Dev Shed. How do you pass loop data from one function to another? Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
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.
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.
Posts: 285
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.
Posts: 102
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.
Posts: 1,075
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()
Posts: 1,075
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()
Posts: 6
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.
Posts: 1,075
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()