user3602484
user3602484

Reputation: 1

Python - Split integer into individual digits (undetermined amount of digits)

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()

Upvotes: 0

Views: 5016

Answers (4)

chapelo
chapelo

Reputation: 2562

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

Upvotes: 0

kmacinnis
kmacinnis

Reputation: 638

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.

Upvotes: 1

Johanan Liebermann
Johanan Liebermann

Reputation: 821

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>

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

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
    

Upvotes: 1

Related Questions