0

We are reading lines from a file which contain integers. There are an indeterminate amount of lines being read. We must split each integer into the digits of the integer and then add the digits together and create another file which writes in both the integer and the sum of the digits for each integer.

The professor said to use an event-controlled loop, but didn't specify beyond that. We are only permitted to use while loops, not for loops.

I can't figure out how to put code in here so that I can show what I have tested so far just to get reacquainted with the splitting of a certain amount of digits in an integer.

Edit to add:

myFile = open("cpFileIOhw_digitSum.txt", "r")

numbers = 1
numberOfLines = 3
digitList = []
while(numbers <= numberOfLines):
    firstNum = int(myFile.readline())
    while (firstNum != 0):
        lastDigit = firstNum % 10
        digitList.append(lastDigit)
        firstNum = firstNum / 10
        firstDigit = firstNum
    digitList.append(firstDigit)
    digitSum = sum(digitList)
    print digitList
    print digitSum
    numbers += 1


myFile.close()

^Here is what I have so far but now my problem is I need each integer's digits stored in a different list. And this is an undetermined amount of integers being read from the file. The numbers used for the count and to end the loop are simply examples.

LASTEST UPDATE to my code: Pretty much all I need to know now is how to let the while loop know that there are no more lines left in the txt file.

myFile = open("cpFileIOhw_digitSum.txt", "r")
myNewFile = open("cpFileIOhw_output.txt", "w")

total = 0
fullInteger =
while(fullInteger != 0):
    fullInteger = int(myFile.readline())
    firstNum = fullInteger
    while (firstNum != 0):
        lastDigit = firstNum % 10
        total = total + lastDigit
        firstNum = firstNum / 10
        firstDigit = firstNum
    total = total + firstDigit
    myNewFile.write(str(fullInteger) + "-" + str(total))
    print " " + str(fullInteger) + "-" + str(total)
    total = 0


myFile.close()
myNewFile.close()
user3602484
  • 1
  • 1
  • 2
  • Just paste the code in direct from your IDE, select it in the question editing window, then click the `{}` button to format it – jonrsharpe May 04 '14 at 23:10
  • Ask your professor. We don't do your homework, here. – Dustin Oprea May 04 '14 at 23:44
  • That's a little rude. This is my first time ever coming to this site and asking a question and I am at an A in this class and I just needed help figuring out part of my homework assignment that I am stuck on. – user3602484 May 04 '14 at 23:49

4 Answers4

1

Well, there are two ways to approach this:

  • cast the integer to a string and iterate through each character, casting each back to an int (best done with a for loop)

  • repeatedly get the dividend and modulo of dividing the integer by 10; repeat until the dividend is 0 (best done with a while loop).

    And these are the math operators you need:

    mod = 123 %  10     # 3
    div = 123 // 10     # 12
    
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
1

Casting the integers to strings shouldn't be necessary. Since you're reading the integers in from a text file, you'll start with strings.

You'll need an outer while loop to handle reading the lines from the file. Since you're forbidden to use for loops, I would use my_file.readline(), and you'll know you're done reading the file when it returns an empty string.

Nested inside that loop, you'll need one to handle pulling apart the digits. Although-- did your professor require two loops? I thought that your question said that before it was edited, but now it doesn't. If it's not required, I would just use a list comprehension.

kmacinnis
  • 608
  • 5
  • 8
  • We are supposed to have a nested while loop. But I still haven't figured out how to get it to know when there are no more lines of txt to read in from the file. – user3602484 May 05 '14 at 00:33
  • @mpez0 the second paragraph doesn't seem entirely clear to me. I understand what it is telling me to do but if I'm reading the lines inside the while function (and converting them to int right away), how can it know when the file reads an empty string? – user3602484 May 05 '14 at 00:42
  • You can read the first line before you enter the while loop, and then readline again right before the end of the loop, so the test condition tests the new line. – kmacinnis May 05 '14 at 00:45
  • @user3602484 back to "what have you tried?" Maybe you shouldn't be converting right away, but checking first. Get it working before combining actions; getting one item per line debugged is tough enough. – mpez0 May 05 '14 at 00:47
  • @mpez0 so should I convert it to int AFTER reading the line and saving it to fullInteger? Because I'm getting this error: ValueError: invalid literal for int() with base 10: '' – user3602484 May 05 '14 at 00:47
  • @mpez0 and @kmacinnis But my entire program revolves around reading integers from this file. Isn't there a way to make an expression for this `while` using the already converted string? – user3602484 May 05 '14 at 00:52
  • @user3602484 how about something like `while ((fullString= my_file.readline()):` You aren't reading integers from the file, you're reading characters. If you were reading integers, you wouldn't need the `int()`. – mpez0 May 05 '14 at 00:52
  • @user3602484 The `ValueError: invalid literal for int() with base 10` is because you're trying to convert the empty string at the end of the file to an `int` (either that, or there are non-digit characters in the file you're reading). You need to actually check for that empty string somehow. – kmacinnis May 05 '14 at 00:55
  • @mpez0 I got it to work. I converted it to int at the beginning of the while loop – user3602484 May 05 '14 at 00:57
  • @user3602484 congratulations. – mpez0 May 05 '14 at 00:59
0

Try this for splitting into digits:

num = 123456
s = str(num)
summary = 0

counter = 0
while (counter < len(s)):
    summary += int(s[counter])
    counter += 1
print s + ', ' + str(summary)

Result:

C:\Users\Joe\Desktop>split.py
123456, 21

C:\Users\Joe\Desktop>
Johannes Liebermann
  • 811
  • 1
  • 10
  • 20
0

Try the following...

total = lambda s: str(sum(int(d) for d in s))

with open('u3.txt','r') as infile, open('u4.txt','w') as outfile:
    line = '.' # anything other than '' will do
    while line != '':
        line = infile.readline()
        number = line.strip('\n').strip()
        if line != '':
            outfile.write(number + ' ' + total(number) + '\n') 
                            # or use ',' instead of ' 'to produce a CSV text file
chapelo
  • 2,519
  • 13
  • 19
  • Please see my latest update to my question. I don't know what half of what you wrote even means. This is very basic python that we're doing. – user3602484 May 05 '14 at 00:31